Re: Why are there no ordered dictionaries?

2005-11-20 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Fredrik Lundh wrote:
> > but you can easily generate an index when you need it:
> >
> > index = dict(d)
> >
> > name, type = index["pid"]
> > print name
> >
> > the index should take less than a microsecond to create, and since it
> > points to the members of the original dict, it doesn't use much memory
> > either...
> >
> Using the same logic, we don't need types other than string in a  DBMS
> as we can always convert a string field into some other types when it
> is needed.

No, that's not the same logic.  The dict() in my example doesn't convert be-
tween data types; it provides a new way to view an existing data structure.
There's no parsing involved, nor any type guessing.  And given the use case,
it's more than fast enough, and doesn't copy any data.

If you think that's the same thing as parsing strings, you've completely missed
the point.





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


Re: setattr for secondary attribute

2005-11-20 Thread Fredrik Lundh
Alex wrote:

> I apologize for asking  maybe a very trivial question.
> I have a new class object A with slots. One of the slots is, for
> example, object spam. Object spam, in turn, also has slots and one of
> them is attribute eggs. I need to assign a new value to eggs. In other
> words, I need to perform the following:
>
> A.spam.eggs=newValue
>
> The problem is that I have only a string s='spam.eggs' with which to
> work, so I cannot write an expression written above. I tried to use
> setattr:
>
> setattr(A, s, newValue)
>
> but this does not work. It says that object A does not have attribute
> spam.eggs

since "eggs" is an attribute of the "spam" attribute, you need to fetch
the latter first:

setattr(getattr(A, "spam"), "eggs")





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


Re: ownership problem?

2005-11-20 Thread Fredrik Lundh
Jeffrey Schwab wrote:

> > the problem isn't determining who owns it, the problem is determining
> > who's supposed to release it.  that's not a very common problem in a
> > garbage-collected language...
>
> Yes it is.  Memory is only one type of resource.

Python's garbage collector deals with objects, not memory.

> I am not a Python Guru

from the sound of it, you haven't written serious programs in any of the
languages you mention.





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


Re: Aproximative string matching

2005-11-20 Thread Tim Roberts
"javuchi" <[EMAIL PROTECTED]> wrote:
>
>I'm searching for a library which makes aproximative string matching,
>for example, searching in a dictionary the word "motorcycle", but
>returns similar strings like "motorcicle".
>
>Is there such a library?

There is an algorithm called Soundex that replaces each word by a
4-character string, such that all words that are pronounced similarly
encode to the same string.

The algorithm is easy to implement; you can probably find one by Googling.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BaseHTTPServer module

2005-11-20 Thread Tim Roberts
"amfr" <[EMAIL PROTECTED]> wrote:
>
>>From the BaseHTTPServer module, how do i gget the POST or GET data sent
>by the client?  Is it stired the the file they requested? e.g.
>objectname.path

Did you check the documentation in the module?  You need to derive your own
class from BaseHTTPServer.  In that module, you need to add functions
called do_GET and do_POST.

In a GET request, the data is all encoded in the URL.  You'll find that in
self.path.

In a POST request, the data is all encoded in the body of the request.
You'll find that in self.rfile.  You'll have to parse and decode it
yourself.

However, as the module documentation also tells you, that has already been
done for you in SimpleHTTPServer.py.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


about dictionary

2005-11-20 Thread Technical Support of Intercable Co
 >>> b=dict.fromkeys(a)

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


Re: Problem printing in Win98

2005-11-20 Thread Tim Roberts
"Maravilloso" <[EMAIL PROTECTED]> wrote:
>
>I'm trying to automatically send a postscript file to be printed to the
>default printer in a Win98 PC, by means of using the instrucction:
>
>  win32api.ShellExecute (0, "print", "file.ps", None, ".", 0)
>
>but it raises an exception with the message:
>
>  error: (31, 'ShellExecute', 'A device attached to the system is not
>functioning.')

Roger is correct.  In order to print a .ps file, you have to have installed
an application that handles .ps files.  You have probably installed
GhostScript on your 2K/XP box.  If you install it on your Win98 box, your
ShellExecute should work.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check if com api is still available

2005-11-20 Thread Tim Roberts
Neil Hodgson <[EMAIL PROTECTED]> wrote:
>
>All running COM servers should be in the "Running Object Table" 
>(ROT). If you search the net for this term you will find code that can 
>show what is in the ROT, so there must be an API.

If only.  The Microsoft Office applications seem to be the only ones in the
world that use the ROT.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python under Citrix Metaframe

2005-11-20 Thread Tim Roberts
"Xaver Hinterhuber" <[EMAIL PROTECTED]> wrote:
>
>I wanted to use python under Citrix Metaframe.
>After installation of the ActivePython 2.4.1 msi-File, printing under Citrix 
>Metaframe no longer worked.

That seems incredible unlikely.  Are you talking about printing to a
printer on the server, or printing to a printer on the local machine?  Did
you change to "/install" mode to do the installation, and then switch back
to "/execute" mode?

Printing to a local printer under Citrix is always a pain in the rear, but
Python doesn't have anything to do with that.

>Do you use python under Citrix Metaframe?
>What problems did you encounter?

I've used Python extensively with Microsoft's Terminal Services.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best cumulative sum

2005-11-20 Thread [EMAIL PROTECTED]

Erik Max Francis wrote:
> Micah Elliott wrote:
>
> > On Nov 21, David Isaac wrote:
>  >
> >> What's the good way to produce a cumulative sum?
> >
>  import operator
>  x = 1,2,3
>  reduce(operator.add, x)
> > 6
> 
> Or just sum(x).
> 
He seems to want scanl

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


Re: Underscores in Python numbers

2005-11-20 Thread bearophileHUGS
Peter Hansen>Or maybe one should instead interpret this as "numeric
literals need more bells and whistles, and I don't care which of these
two we add, but we have to do *something*!". :-)

The purpose of my words was: when you think about adding a new
syntax/functionality to a language, you have to think well if the same
syntax can be used for something more important or more natural for it,
so later you can avoid later problems and silly compromises.

Bye,
bearophile

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


Re: best cumulative sum

2005-11-20 Thread Robert Kern
Erik Max Francis wrote:
> Micah Elliott wrote:
> 
>>On Nov 21, David Isaac wrote:
>>>What's the good way to produce a cumulative sum?
>>
>import operator
>x = 1,2,3
>reduce(operator.add, x)
>>
>>6
> 
> Or just sum(x).

That just gives you the tail end. The OP asked for a cumulative sum;
that is, a list with all of the intermediate sums, too.

-- 
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: ownership problem?

2005-11-20 Thread elbertlev
Yes!
Python uses auto garbage collection. As soon as the object reference
count becomes 0 it is removed from existence. So the problem typical
for C/C++: accessing pointers
to already deleted objects does not exist in Python.

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


Re: best cumulative sum

2005-11-20 Thread Erik Max Francis
Micah Elliott wrote:

> On Nov 21, David Isaac wrote:
 >
>> What's the good way to produce a cumulative sum?
> 
 import operator
 x = 1,2,3
 reduce(operator.add, x)
> 6

Or just sum(x).

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Never contend with a man who has nothing to lose.
   -- Baltasar Gracian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best cumulative sum

2005-11-20 Thread Micah Elliott
On Nov 21, David Isaac wrote:
> What's the good way to produce a cumulative sum?

>>> import operator
>>> x = 1,2,3
>>> reduce(operator.add, x)
6

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Ben Finney wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > [sort by] some other metadata that is not present in the data.
> > [...]
> > Of course, you may say, just put another column that represent
> > this(some reporting programs I have seen do it this way) and that is
> > an option but not the only option.
>
> It's a pretty good option, and very commonly used. It's known as the
> "Schwartzian transform", or more descriptively, the "Decorate, Sort,
> Undecorate" pattern.
>
Whether it is a good option is judged by the person implement it as he
is the one seeing the whole thing, and not some snippet(or concept) on
the usenet.

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Ben Finney
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> [sort by] some other metadata that is not present in the data.
> [...]
> Of course, you may say, just put another column that represent
> this(some reporting programs I have seen do it this way) and that is
> an option but not the only option.

It's a pretty good option, and very commonly used. It's known as the
"Schwartzian transform", or more descriptively, the "Decorate, Sort,
Undecorate" pattern.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234>

-- 
 \ "Experience is that marvelous thing that enables you to |
  `\  recognize a mistake when you make it again."  -- Franklin P. |
_o__)Jones |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] Python API InformixDB-2.1 released

2005-11-20 Thread Carsten Haese
Hi everybody:

I am proud to announce a new release of InformixDB, the IBM Informix
implementation of the Python DB API. This release adds the following new 
features:

* Scroll cursors and cursors with hold
* Support for INTERVAL types
* Support for Smart Large Objects
* Support for User Defined Types

Downloads and more info at http://informixdb.sourceforge.net/

Enjoy,

Carsten Haese.

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Bengt Richter wrote:
> On Sun, 20 Nov 2005 22:03:34 +0100, Christoph Zwerschke <[EMAIL PROTECTED]> 
> wrote:
> >> Ordering the keys isn't the normal case, and can be done easily when
> >> needed.
> >
> >That depends. Maybe I do not want the keys to be sorted alphabetically,
> >but according to some criteria which cannot be derived from the keys
> >themselves.
> You mean involving also the values? What's wrong with
> sorted(plaindict.items(), key=your_ordering_function) ?
>
Not according to the content of the data, not just the "key". Or in
other words, some other metadata that is not present in the data. A
typical thing, like order of creation. Or some arbitary order. For
example :

I present a data grid/table in a HTML form and the user just drag and
drop and rearrange the columns order.

Of course, you may say, just put another column that represent
this(some reporting programs I have seen do it this way) and that is an
option but not the only option.

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Bengt Richter
On Sun, 20 Nov 2005 22:03:34 +0100, Christoph Zwerschke <[EMAIL PROTECTED]> 
wrote:
>> Ordering the keys isn't the normal case, and can be done easily when
>> needed.
>
>That depends. Maybe I do not want the keys to be sorted alphabetically, 
>but according to some criteria which cannot be derived from the keys 
>themselves.
You mean involving also the values? What's wrong with
sorted(plaindict.items(), key=your_ordering_function) ?

 >>> def show(*a): print a
 ...
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=show)
 (('a', 97),)
 (('c', 99),)
 (('b', 98),)
 (('d', 100),)
 [('a', 97), ('c', 99), ('b', 98), ('d', 100)]

What key function would you like, to generate the value that is actually used
to define the ordering?

 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[0])
 [('a', 97), ('b', 98), ('c', 99), ('d', 100)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[1])
 [('a', 97), ('b', 98), ('c', 99), ('d', 100)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:-t[1])
 [('d', 100), ('c', 99), ('b', 98), ('a', 97)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[1]&1)
 [('b', 98), ('d', 100), ('a', 97), ('c', 99)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda 
 >>> t:(t[1]&1,t[1]))
 [('b', 98), ('d', 100), ('a', 97), ('c', 99)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda 
 >>> t:(t[1]&1,-t[1]))
 [('d', 100), ('b', 98), ('c', 99), ('a', 97)]
And being able to reverse the end result is handy
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda 
 >>> t:(t[1]&1,-t[1]), reverse=True)
 [('a', 97), ('c', 99), ('b', 98), ('d', 100)]

You may need to upgrade your Python though ;-)

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


Re: Any royal road to Bezier curves...?

2005-11-20 Thread Robert Kern
Warren Francis wrote:
> I'm fairly new to Python (2-3 months) and I'm trying to figure out a simple 
> way to implement Bezier curves...  So far I've tried the following:
> 
> http://runten.tripod.com/NURBS/
> ...which won't work because the only compiled binaries are for Windows 2000, 
> python 2.1.  I'm on Windows XP (for now), using Python 2.4.  I downloaded 
> the source distribution, but the header files aren't included, so I'm not 
> sure how to compile it.
> 
> It appears there's some bezier functionality in the python that comes 
> Blender... but I'm not savvy enough yet to try and extract whatever makes 
> beziers work there, to make it work in my general-purpose Python programs.
> 
> Basically, I'd like to specify a curved path of an object through space.  3D 
> space would be wonderful, but I could jimmy-rig something if I could just 
> get 2D... 

There's some 2D code (which could be trivially adapted to 3D) in
PIDDLE/Sping. In the latest Sping download, look in the file pid.py at
the Canvas.curvePoints() method.

  http://piddle.sourceforge.net/

> Are bezier curves really what I want after all?

I dunno. It depends on how much flexibility you need.

-- 
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


setattr for secondary attribute

2005-11-20 Thread Alex
I apologize for asking  maybe a very trivial question.
I have a new class object A with slots. One of the slots is, for
example, object spam. Object spam, in turn, also has slots and one of
them is attribute eggs. I need to assign a new value to eggs. In other
words, I need to perform the following:

A.spam.eggs=newValue

The problem is that I have only a string s='spam.eggs' with which to
work, so I cannot write an expression written above. I tried to use
setattr:

setattr(A, s, newValue)

but this does not work. It says that object A does not have attribute
spam.eggs

How would you do it? TIA.

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


Any royal road to Bezier curves...?

2005-11-20 Thread Warren Francis
I'm fairly new to Python (2-3 months) and I'm trying to figure out a simple 
way to implement Bezier curves...  So far I've tried the following:

http://runten.tripod.com/NURBS/
...which won't work because the only compiled binaries are for Windows 2000, 
python 2.1.  I'm on Windows XP (for now), using Python 2.4.  I downloaded 
the source distribution, but the header files aren't included, so I'm not 
sure how to compile it.

It appears there's some bezier functionality in the python that comes 
Blender... but I'm not savvy enough yet to try and extract whatever makes 
beziers work there, to make it work in my general-purpose Python programs.

Basically, I'd like to specify a curved path of an object through space.  3D 
space would be wonderful, but I could jimmy-rig something if I could just 
get 2D...  Are bezier curves really what I want after all?

Any thoughts would be much appreciated.  I've got some ideas I want to test, 
but if I can't find a simple implementation of curves, I'm going to get so 
bogged down in trying to do that part, I'll never get to what I'm excited 
about. :-P

Warren 


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


Re: about dictionary

2005-11-20 Thread Bengt Richter
On Sun, 20 Nov 2005 07:12:08 -0800, Shi Mu <[EMAIL PROTECTED]> wrote:

>d is a dictionary.
 d
>{0: [[0, 1], [0, 2]], 1: [[0, 1], [1, 2], [1, 3]], 2: [[0, 2], [1, 2],
>[2, 3]], 3: [[1, 3], [2, 3]]}
>
>for the value under each key, if the possible connection is in the
>dictionary, for example, under key 0. 1 and 2 were found to have a
>pair in some other places so get [0,1,2]
>hence, how to design a dictionary,
>let dicTry=3D
>{0: [[0, 1,2], 2: [[0, 1, 2], [1, 2,3]], 2: [[0, 1,2], [1, 2,3], 3: [1,2,3]=
>}
>Thanks a lot!
Sounds like some graph application? Maybe you can find something useful
in a link from
http://wiki.python.org/moin/PythonGraphApi

(which I found by googling for "vertex graph site:python.org" (without the 
quotes) ;-)

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


Re: best cumulative sum

2005-11-20 Thread Steven D'Aprano
David (Alan) Isaac wrote:

> What's the good way to produce a cumulative sum?
> E.g., given the list x,
> cumx = x[:]
> for i in range(1,len(x)):
>  cumx[i] = cumx[i]+cumx[i-1]
> 
> What's the better way?

Is there something that this doesn't do, or something 
it does do that it shouldn't?

You could do it this way:

# untested
def cumulative_sum(L):
 CL = []
 csum = 0
 for x in L:
 csum += x
 CL.append(csum)
 return CL

Whether it is better or worse depends on what you 
consider better or worse.


-- 
Steven.

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


Re: best cumulative sum

2005-11-20 Thread Robert Kern
David Isaac wrote:
> What's the good way to produce a cumulative sum?
> E.g., given the list x,
> cumx = x[:]
> for i in range(1,len(x)):
>  cumx[i] = cumx[i]+cumx[i-1]
> 
> What's the better way?

Define better. More accurate? Less code?

-- 
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: Aproximative string matching

2005-11-20 Thread Steven D'Aprano
[EMAIL PROTECTED] wrote:

> This algorithm is called soundex. Here is one implementation example.
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213
> 
> here is another:
> http://effbot.org/librarybook/soundex.htm

Soundex is *one* particular algorithm for approximate 
string matching. It is optimised for matching 
Anglo-American names (like Smith/Smythe), and is 
considered to be quite old and obsolete for all but the 
most trivial applications -- or so I'm told.

Soundex will not match arbitrary changes -- it will 
match both cat and cet, but it won't match cat and mat.

A more sophisticated approximate string matching 
algorithm will use the Levenshtein distance. You can 
find a Useless implementation here:

http://www.uselesspython.com/download.php?script_id=108


Given a function levenshtein(s1, s2) that returns the 
distance between two strings, you could use it for 
approximate matching like this:

def approx_matching(strlist, target, dist=1):
 """Matches approximately strings in strlist to
 a target string.

 Returns a list of strings, where each string
 matched is no further than an edit distance of
 dist from the target.
 """
 found = []
 for s in strlist:
 if levenshtein(s, target) <= dist:
 found.append(s)
 return s



-- 
Steven.

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


best cumulative sum

2005-11-20 Thread David Isaac
What's the good way to produce a cumulative sum?
E.g., given the list x,
cumx = x[:]
for i in range(1,len(x)):
 cumx[i] = cumx[i]+cumx[i-1]

What's the better way?

Thanks,
Alan Isaac


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


Re: about list

2005-11-20 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> Shi Mu wrote:
> 
>>How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
>>Thanks!
> 
> 
> You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
> from
> the list?  You might want to look at:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
> 
> 
import * from xpermutations
[x for x in UniqueCombinations ([1,2,4], 2)]
> 
> [[1, 2], [1, 4], [2, 4]]
> 
> That web page also gives urls to other recipies that do the same thing.

Dang, that's better than my version.

$ ./combinations.py 2 1 2 4
[['1', '2'], ['1', '4'], ['2', '4']]

def combinations( universe, n=None ):

 """
 Return all possible combinations of length "n," where the
 elements of each combination are taken from the list "universe."
 """

 result = []

 if n == None:
 n = len( universe )

 if n > len( universe ):
 # No combination of elements can have cardinality
 # greater than universe, which is by definition the list
 # of all possible elements.
 pass
 elif n < 0:
 # No combination can have negative cardinaltiy.
 pass
 elif n == 0:
 # Only the empty combination has cardinality 0.
 result.append( [ ] )
 else:   # 0 < n <= len( universe )
 for i in xrange( len( universe ) ):
 elem = universe[i]
 post = universe[i+1:]
 for c in combinations( post, n - 1 ):
 choice = [ elem ]
 choice.extend( c )
 result.append( choice )

 return result

if __name__ == "__main__":

 import sys

 if len( sys.argv ) < 2:
 sys.stderr.write(
 "usage: %s  [elements ...]\n" % sys.argv[0] )
 sys.exit(1)

 n = int( sys.argv[1] )
 print repr( combinations( sys.argv[2:], n ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type-checking unpickled objects

2005-11-20 Thread Gordon Airporte
> I guess I'll 
> need a throwaway instance of the class to run type() on to get a usable 
> type object for comparison, but I'll work something out.

Never mind - I can just pass the name of the class, as it should be.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aproximative string matching

2005-11-20 Thread elbertlev
This algorithm is called soundex. Here is one implementation example.

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

here is another:
http://effbot.org/librarybook/soundex.htm

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


How to install python2.4.2 on IRIX6.5 ?

2005-11-20 Thread Xiao Jianfeng
Hello,

I am trying to install python2.4.2 on a SGI origin3200 machine running
IRIX6.5.
The native c compiler was used to compile python.

"./configure --prefix=/my/path/to/install" runs ok,
then, "smake OPT= " runs ok
but "smake test" gets errors, here is the output:

247 tests OK.
2 tests failed:
test_fpformat test_locale
41 tests skipped:
test_aepack test_al test_applesingle test_bsddb test_bsddb185
test_bsddb3 test_bz2 test_cd test_cl test_codecmaps_cn
test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr
test_codecmaps_tw test_curses test_dl test_gdbm test_gl test_gzip
test_imgfile test_ioctl test_linuxaudiodev test_macfs
test_macostools test_nis test_normalization test_ossaudiodev
test_pep277 test_plistlib test_scriptpackages test_socket_ssl
test_socketserver test_sunaudiodev test_tcl test_timeout
test_urllib2net test_urllibnet test_winreg test_winsound
test_zipimport test_zlib
Ask someone to teach regrtest.py about which tests are
expected to get skipped on irix6.
*** Error code 1
smake: Error: 1 error

I also tried regrtest.py according the above instruction,

origin3200% ./Lib/test/regrtest.py -s test_fpformat
test_fpformat
test test_fpformat failed -- Traceback (most recent call last):
File
"/disk2/jfxiao/local/source/Python-2.4.2/Lib/test/test_fpformat.py",
line 51, in test_reasonable_values
self.checkFix(realVal, d)
File
"/disk2/jfxiao/local/source/Python-2.4.2/Lib/test/test_fpformat.py",
line 28, in checkFix
self.assertEquals(result, expected)
AssertionError: '-0' != '0'

1 test failed:
test_fpformat
origin3200% ./Lib/test/regrtest.py -s test_locale
test_frozen
1 test OK.
-

Can somebody tell me what's the problem ?
Thanks!

Regards,

xiaojf

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

global definition

2005-11-20 Thread Shi Mu
I have a code here. I understand i can not draw lines without the
global definition of lastX and lastY. But still confused by its use.
when should we use global definition?

from Tkinter import *

root = Tk()

c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
frame = c
lastX=""
lastY=""
def click(event):
  global lastX, lastY
  if lastX != "":
 c.create_line(lastX,lastY,event.x,event.y,fill="white")
  lastX = event.x
  lastY = event.y


c.bind('<1>',click)

c.pack()

root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-20 Thread Paul Watson
John J. Lee wrote:
> Paul Watson <[EMAIL PROTECTED]> writes:
> 
> 
>>What are the options?
>>
>>The user to hits a web page, downloads code (Python I hope), execute it, 
>>and be able to return the results.  It needs to be able to go through 
>>standard HTTP so that it could be run from behind a corporate firewall 
>>without any other ports being opened.
>>
>>Am I stuck doing an ActiveX control?
> 
> [...]
> 
> If you just need to talk on port 80, just go ahead and do that (module
> socket, module httplib, module urllib2, urllib.getproxies, etc), and
> write a normal desktop application.
> 
> 
> If it must run in a browser, here is some food for thought:
> 
> 
> Compile Python to JavaScript -- very cool
> 
> http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework
> 
> http://www.aminus.org/blogs/index.php/phunt/2005/10/09/psst_crackajax_is_in_svn
> 
> 
> Plain old AJAX with Python on server side
> 
> https://sourceforge.net/projects/json-py/
> 
> http://www.google.co.uk/search?q=ajax+python&btnG=Search (um, ignore the 1st 
> result)
> 
> 
> Write Java applets in Python
> 
> http://www.jython.org/
> 
> 
> Flash 'local storage'
> 
> http://www.macromedia.com/support/documentation/en/flashplayer/help/help02.html
> 
> Sort-of AJAX-for-Flash stuff
> 
> http://www.cs.unc.edu/~parente/tech/tr04.shtml
> http://www.simonf.com/flap/
> 
> Flash itself (boo;-)
> 
> http://www.macromedia.com/
> 
> 
> XUL and PyXPCOM (Firefox only)
> 
> http://www.xulplanet.com/
> 
> http://trac.nunatak.com.au/projects/nufox
> 
> 
> Firefox future capabilities in this direction (probably most of this
> is relevant)
> 
> http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html
> 
> http://weblogs.mozillazine.org/roadmap/archives/2005_09.html
> 
> 
> John

I appreciate your long list of references.  For this task, I think the 
first answer may have to be the one with which to go.  A standard 
application that talks through port 80 and perhaps can use proxies.

My desire to have the code distributed through a web page is just to 
ensure that the user is running the correct version and has not hacked 
it in any way.  I suppose I can checksum the local client application 
and compare it with what is on the server.  Then, make a way to 
update... ARGH!

Even when future browsers embed Python interpreters, the security 
considerations may be such that no one will want to accept code which 
can do much locally anyway.  Probably the right thing for the public 
Internet,  Makes it harder to develop internal system management tools.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-20 Thread Kent Johnson
Paul Watson wrote:
> Kent Johnson wrote:
>> Stephen Kellett wrote:
>>> ActiveState do a version of Python that can run in a script tag like 
>>> JavaScript and VBScript. This requires Windows Scripting Host. They 
>>> also do a similar thing for Perl, not sure about TCL.
>>
>> See
>> http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830
> 
> Please correct my misunderstanding if I am wrong, but I thought that 
> this runs server-side only and requires Microsoft IIS as the httpd 
> server.  Is that correct?

I haven't tried it but the referenced article seems to be about including 
Python in a web page to be run in-browser by IE.

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


Re: Type-checking unpickled objects

2005-11-20 Thread Gordon Airporte
isinstance! Now why didn't I know about that? Thanks you. I guess I'll 
need a throwaway instance of the class to run type() on to get a usable 
type object for comparison, but I'll work something out.
As to the security considerations...this is a small enough program with 
a limited enough release that I'm not going to sweat it, although I will 
keep this in mind.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-20 Thread Paul Watson
David Wahler wrote:
> Steve wrote:
> 
>>AJAX works because browsers can execute javascript.  I don't know of a
>>browser that can execute python.  Basically your stuck with java or
>>javascript because everything else really isn't cross platform
> 
> 
> Don't jump to conclusions...
> http://dwahler.ky/python/
> 
> If you really, really want Python in a browser, it's certainly
> possible. :)
> 
> -- David

This looks interesting, but looks even more fragile than CrackAJAX.

http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework

All of this comes down to Javascript which will still not allow me to 
read local, client files.  Right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about list

2005-11-20 Thread rurpy

Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
from
the list?  You might want to look at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465

>>> import * from xpermutations
>>> [x for x in UniqueCombinations ([1,2,4], 2)]
[[1, 2], [1, 4], [2, 4]]

That web page also gives urls to other recipies that do the same thing.

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


Re: Underscores in Python numbers

2005-11-20 Thread Bengt Richter
On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <[EMAIL PROTECTED]> wrote:

>Mike Meyer <[EMAIL PROTECTED]> writes:
>
>> I've seen at least one language (forget which one) that allowed such
>> separators, but only for groups of three. So 123_456 would be valid,
>> but 9_1 would be a syntax error. 
>
>Ada allows underscores in numeric literals since 1983, without
>enforcing any grouping. The Ruby language allows also this
>notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
>same for real numbers...). 
>
Actually, I guess I could be convinced, even though I posted a
you-can-do-this-now decorator to bracket the op's desired function defs.

>When you have the habit to represent literals like that, all other
>big numeric literals or workarounds to create grouping seem cryptic. 
>
>-- 
>Eric Jacoboni, ne il y a 1435938104 secondes
My previous smiley re your sig in this thread context still applies ;-)

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


Re: Web-based client code execution

2005-11-20 Thread Paul Watson
Kent Johnson wrote:
> Stephen Kellett wrote:
> 
>> In message <[EMAIL PROTECTED]>, 
>> Steve <[EMAIL PROTECTED]> writes
>>
>>> AJAX works because browsers can execute javascript.  I don't know of a
>>> browser that can execute python.  Basically your stuck with java or
>>> javascript because everything else really isn't cross platform.
>>
>>
>>
>> ActiveState do a version of Python that can run in a script tag like 
>> JavaScript and VBScript. This requires Windows Scripting Host. They 
>> also do a similar thing for Perl, not sure about TCL.
> 
> 
> See
> http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830
> 
> Kent

Please correct my misunderstanding if I am wrong, but I thought that 
this runs server-side only and requires Microsoft IIS as the httpd 
server.  Is that correct?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Underscores in Python numbers

2005-11-20 Thread Bengt Richter
On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <[EMAIL PROTECTED]> wrote:

>Mike Meyer <[EMAIL PROTECTED]> writes:
>
>> I've seen at least one language (forget which one) that allowed such
>> separators, but only for groups of three. So 123_456 would be valid,
>> but 9_1 would be a syntax error. 
>
>Ada allows underscores in numeric literals since 1983, without
>enforcing any grouping. The Ruby language allows also this
>notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
>same for real numbers...). 
>
>When you have the habit to represent literals like that, all other
>big numeric literals or workarounds to create grouping seem cryptic. 
>
>-- 
>Eric Jacoboni, ne il y a 1435938104 secondes
Um, about your sig ... ;-)

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


Re: Underscores in Python numbers

2005-11-20 Thread Bengt Richter
On Sun, 20 Nov 2005 15:37:40 +, Steve Holden <[EMAIL PROTECTED]> wrote:

>David M. Cooke wrote:
>> Peter Hansen <[EMAIL PROTECTED]> writes:
>> 
>> 
>>>Steven D'Aprano wrote:
>>>
Dealing with numeric literals with lots of digits is
a real (if not earth-shattering) human interface problem: it is hard for
people to parse long numeric strings.
>>>
>>>I'm totally unconvinced that this _is_ a real problem, if we define 
>>>"real" as being even enough to jiggle my mouse, let alone shattering the 
>>>planet.
>>>
>>>What examples does anyone have of where it is necessary to define a 
>>>large number of large numeric literals?  Isn't it the case that other 
>>>than the odd constants in various programs, defining a large number of 
>>>such values would be better done by creating a data file and parsing
>>>it?
>> 
>> 
>> One example I can think of is a large number of float constants used
>> for some math routine. In that case they usually be a full 16 or 17
>> digits. It'd be handy in that case to split into smaller groups to
>> make it easier to match with tables where these constants may come
>> from. Ex:
>> 
>> def sinxx(x):
>> "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
>> a2 = -0.1 4
>> a4 =  0.00833 33315
>> a6 = -0.00019 84090
>> a8 =  0.0 27526
>> a10= -0.0 00239
>> x2 = x**2
>> return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10
>> 
>> (or least that's what I like to write). Now, if I were going to higher
>> precision, I'd have more digits of course.
>> 
>Right, this is clearly such a frequent use case it's worth changing the 
>compiler for.
>
Agreed, let the OP hack a special-purpose solution for a special-case problem, 
e.g.
(tested just enough to show the idea on this post ;-)

 >>> def fundef(funsrc, preprocess=None):
 ... def doprep(f):
 ... protect_f = {}
 ... try:
 ... src = funsrc.lstrip().rstrip()+'\n' # remove leading/trailing 
blank lines
 ... exec (preprocess and preprocess(src) or src) in protect_f
 ... return type(f)(protect_f[f.func_name].func_code,
 ... f.func_globals, f.func_name, f.func_defaults, 
f.func_closure)
 ... except Exception, e:
 ... raise ValueError, 'Unable to translate %r ... due to\n%s'%(
 ... funsrc.lstrip().splitlines()[0][:30], '%s: 
%s'%(e.__class__.__name__, e))
 ... return doprep
 ...

Now that decorator allows you to pre-process a function source
(e.g. according to what the OP might want for a preprocess argument):

 >>> import re
 >>> numgap = re.compile(r'(\d+) (?=\d)')
 >>> def prep(s): return numgap.sub(r'\1', s)
 ...

Then use it on the OP's example [1]

 >>> @fundef("""
 ... def sinxx(x):
 ... "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
 ... a2 = -0.1 4
 ... a4 =  0.00833 33315
 ... a6 = -0.00019 84090
 ... a8 =  0.0 27526
 ... a10= -0.0 00239
 ... x2 = x**2
 ... return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10
 ... """, preprocess=prep)
 ... def sinxx(x): pass # (defines signature and defaults in current scope)
 ...

[1] Note that no editing of previous source
is required except bracketing like

 @fundef("""
 
 ... """, preprocess=prep)
 

That last line is required for the decorator, but also (I think, not tested) 
defines
the signature and arg defaults in the current scope, as opposed to where exec 
compiles
in the decorator.

 >>> sinxx
 
 >>> import math
 >>> def mxx(x): return x and math.sin(x)/x or 1.0
 ...
 >>> sinxx(0), mxx(0)
 (1.0, 1.0)
 >>> sinxx(.1), mxx(.1)
 (0.99833416647076856, 0.99833416646828155)
 >>> sinxx(.2), mxx(.2)
 (0.99334665398326816, 0.99334665397530608)
 >>>

Seems to work, approximately ;-)

 >>> @fundef("""
 ... def poo()
 ... syntax problems
 ... """)
 ... def poo(): pass
 ...
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 10, in doprep
 ValueError: Unable to translate 'def poo()' ... due to
 SyntaxError: invalid syntax (line 1)
 
Some hope of somewhat useful exceptions too ;-)

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Peter Hansen wrote:
> [EMAIL PROTECTED] wrote:
> > Using the same logic, we don't need types other than string in a  DBMS
> > as we can always convert a string field into some other types when it
> > is needed.
>
> You mean, like SQLite does? (http://www.sqlite.org/datatypes.html)
> 
Yup, they are using similar logic.

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


Aproximative string matching

2005-11-20 Thread javuchi
I'm searching for a library which makes aproximative string matching,
for example, searching in a dictionary the word "motorcycle", but
returns similar strings like "motorcicle".

Is there such a library?

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> Using the same logic, we don't need types other than string in a  DBMS
> as we can always convert a string field into some other types when it
> is needed.

You mean, like SQLite does? (http://www.sqlite.org/datatypes.html)

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


Re: path module / class

2005-11-20 Thread Peter Hansen
Neil Hodgson wrote:
>>> There is a cost to the change as there will be two libraries that 
>>> have to be known to understand code. 
...
>At that point I was thinking about os.path and path.py. Readers will 
> encounter code that uses both of these libraries.

Okay, granted.  I guess this is the same as in any other case of 
deprecation (e.g. some people still have to work with code that uses 
apply() or string module methods).

> Peter Hansen:
>> We've mandated use of path.py internally for all projects because 
>> we've noticed (especially with non-expert Python programmers... i.e. 
>> junior and intermediate types, and senior types new to Python) a 
>> decrease in errors.  
> 
>A list of fault reports in this area would be useful evidence. 

Unfortunately, in an agile group such reports tend not to exist, and in 
many cases the errors are caught by a partner even as they are created, 
or by someone refactoring the code a day later.  I have only anecdotal 
evidence, I'm afraid, unless I start digging through past subversion 
revisions in several projects.

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Alex Martelli wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>...
> > there are at least two behaviour. What I need is a "preferred order".
> > Say if I have designed a web form(correspond to a database table), I
> > just want say 3 fields that goes before anything else in the
> > presentation. The rest I don't care as the DBA may create more fields
> > later which I don't want to then update my code yet again.
>
> preferred_fields = ['foo', 'bar', 'baz']
>
> def process_preferred_fields():
> global preferred_fields
> temp = {}
> for i, field in enumerate(preferred_fields):
> temp[field] = '%s%s' % (chr(0), chr(i))
> preferred_fields = temp
> process_preferred_fields()
> del process_preferred_fields
>
> def sort_key(akey, preferred_fields=preferred_fields):
> return preferred_fields.get(akey, akey)
> del preferred_fields
>
> ## ...build dictionary d...
>
> # now output d...:
> for k in sorted(d, key=sort_key):
> print k, d[k]
>
> Season to taste if you want non-preferred fields emitted other than
> alphabetically, or if you want to wrap this stuff into a class, etc.
> (Note: untested code, so typos &c are quite possible).  This assumes
> that no 'real' key is a non-string, and no 'real' key starts with
> chr(0), but it's quite easy to tweak for slightly different specs (at
> worst by defining a custom type designed to always compare less than any
> real key, and wrapping the preferred_fields entry in instances of that
> custom type... having such instances compare with each other based on
> the index within preferred_fields of the key they're wrapping, etc etc).
>
Thanks. For me, I don't need such complex thing, it is just like :

d = somedict_from_db()
prefer=['f','a',b']

def my_order(d):
   for x in prefer:
 if x in d: yield x
   s = frozenset(prefer)
   for x in d:
 if x not in s: yield x

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Mike Meyer
Christoph Zwerschke <[EMAIL PROTECTED]> writes:
> Ben Finney wrote:
>> Another possibility: ordered dictionaries are not needed when Python
>> 2.4 has the 'sorted' builtin.
> The 'sorted' function does not help in the case I have indicated,
> where "I do not want the keys to be sorted alphabetically, but
> according to some criteria which cannot be derived from the keys
> themselves."

And how would an ordered dictionary help in this case?

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Alex Martelli
Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
   ...
> The 'sorted' function does not help in the case I have indicated, where
> "I do not want the keys to be sorted alphabetically, but according to
> some criteria which cannot be derived from the keys themselves."

Ah, but WHAT 'some criteria'?  There's the rub!  First insertion, last
insertion, last insertion that wasn't subsequently deleted, last
insertion that didn't change the corresponding value, or...???


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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Alex Martelli
Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
   ...
> I have started the thread in the first place because I believed it is
> pretty unabmiguous what an "ordered dictionary" is and how it should 

I think you're wrong here.  People in the past who have requested or
implemented stuff they called 'ordered dicts' in the past had in mind
drastically different things, based on some combination of insertion
orders, keys, and _values_.  So, ambiguity is definitely present in the
phrase 'ordered dictionary', because there are so many different
criteria whereby the 'ordering' could take place.

Note the plural in 'insertion orderS': some people care about the FIRST
time a key was added to a dict, some about the LAST time it was added,
some about the latest time it was 'first inserted' (added and wasn't
already there) as long as it's never been deleted since that occasion --
and these are just a few of the multifarious orders based on the time of
insertions and deletions of keys.  The number of variations is
staggering, e.g., consider

x['a'] = 1
x['b'] = 2
x['a'] = 1

in some applications you'd want to have 'b' come before 'a' because the
last time of addition was earlier for 'b' -- but in others you might
want 'a' first because the latest addition wasn't really one, since it
didn't really change anything (because the value inserted was the same
as the one already there -- it would be different, for those other apps,
if the RHS of the third assignment was 0 rather than 1...).

To get 'ordered dicts' into Python, you have to identify ONE unambiguous
definition which has a large-enough number of use-cases, possibly
customizable through some reasonably SIMPLE combination of flags and a
callable or two, like the 'sorted' built-in has a 'reversed' flag and
'key' and 'cmp' optional callables.  Expect a lot of flak from those who
have been pining for an 'ordered dict' which does NOT match your one
unambiguous definition...;-)

If the field of use cases for 'ordered dicts' is just too fragmented,
it's quite possible that it's best not to have any single kind built-in,
even though, could all different use cases be combined (which by
hypothesis is unfeasible), "critical mass" would be reached...


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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
   ...
> there are at least two behaviour. What I need is a "preferred order".
> Say if I have designed a web form(correspond to a database table), I
> just want say 3 fields that goes before anything else in the
> presentation. The rest I don't care as the DBA may create more fields
> later which I don't want to then update my code yet again.

preferred_fields = ['foo', 'bar', 'baz']

def process_preferred_fields():
global preferred_fields
temp = {}
for i, field in enumerate(preferred_fields):
temp[field] = '%s%s' % (chr(0), chr(i))
preferred_fields = temp
process_preferred_fields()
del process_preferred_fields

def sort_key(akey, preferred_fields=preferred_fields):
return preferred_fields.get(akey, akey)
del preferred_fields

## ...build dictionary d...

# now output d...:
for k in sorted(d, key=sort_key):
print k, d[k]

Season to taste if you want non-preferred fields emitted other than
alphabetically, or if you want to wrap this stuff into a class, etc.
(Note: untested code, so typos &c are quite possible).  This assumes
that no 'real' key is a non-string, and no 'real' key starts with
chr(0), but it's quite easy to tweak for slightly different specs (at
worst by defining a custom type designed to always compare less than any
real key, and wrapping the preferred_fields entry in instances of that
custom type... having such instances compare with each other based on
the index within preferred_fields of the key they're wrapping, etc etc).


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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Christoph Zwerschke
[EMAIL PROTECTED] wrote:
> Personally, I have needs for ordered dict but I don't think it should
> be in standard library though, as different situation called for
> different behaviour for "ordered" and skewing my code to a standard lib
> way is no good.

I have started the thread in the first place because I believed it is 
pretty unabmiguous what an "ordered dictionary" is and how it should 
behave. That's why I asked myself why something that straigthforward has 
not been added to the standard lib yet. Maybe I'm wrong; I must admit 
that I haven't meditated about it very much.

Do you have an example for different options of behavior?

-- Christoph

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Christoph Zwerschke wrote:
> [EMAIL PROTECTED] wrote:
> > Personally, I have needs for ordered dict but I don't think it should
> > be in standard library though, as different situation called for
> > different behaviour for "ordered" and skewing my code to a standard lib
> > way is no good.
>
> I have started the thread in the first place because I believed it is
> pretty unabmiguous what an "ordered dictionary" is and how it should
> behave. That's why I asked myself why something that straigthforward has
> not been added to the standard lib yet. Maybe I'm wrong; I must admit
> that I haven't meditated about it very much.
>
> Do you have an example for different options of behavior?
>
As mentioned, most ordered dict I saw is "insertion order" based. I
assume that is the need of their creators. But that is not my need, so
there are at least two behaviour. What I need is a "preferred order".
Say if I have designed a web form(correspond to a database table), I
just want say 3 fields that goes before anything else in the
presentation. The rest I don't care as the DBA may create more fields
later which I don't want to then update my code yet again.

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


Re: about list

2005-11-20 Thread Adonis
Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

 From what I gather try:

a = [1,2,4]
n = list()
for i in a:
 index = a.index(i) + 1
 for x in a[index:]:
 n.append([i, x])
print n

more elegant ways to do this, but its a start.
hope this helps.

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Christoph Zwerschke
Ben Finney wrote:

> Without an example, it's hard to know what you want to do and whether
> an ordered dictionary is the best way to do it.

I have indicated an example, discussed in more detail in another subthread.

>> There are already enough competing implementations.
> Have they been sufficiently shaken out to show a clearly superior
> version? Is any version sufficiently beneficial to write a PEP for its
> inclusion in the standard library?

At least it shows I'm not the only one who thinks ordered dictionaries 
may be sometimes nice to have.

 >> I simply wanted to ask why it is not available in the standard lib, 
 >> since I simply don't know
 >> - has it not been demanded loud enough?
> Loud demands don't count for much. PEPs with popular working
> implementations do.

Sorry, I did not mean "loud enough" but "often enough". The same what 
you are calling "popular."

>> - because nobody presented a satisfying implementation yet?
> I'm not sure what you mean by "satisfying".

You can take your own definition: "sufficiently shaken out", "working", 
"popular", and "succifiently beneficial" and "proven (to the BDFL's 
criteria)".

> Another possibility: ordered dictionaries are not needed when Python
> 2.4 has the 'sorted' builtin.

The 'sorted' function does not help in the case I have indicated, where 
"I do not want the keys to be sorted alphabetically, but according to 
some criteria which cannot be derived from the keys themselves."

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


Re: about list

2005-11-20 Thread [EMAIL PROTECTED]
try to describe what you want as it is not very obvious, and has syntax
error.

Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

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


about list

2005-11-20 Thread Shi Mu
How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Ben Finney wrote:
> Another possibility: ordered dictionaries are not needed when Python
> 2.4 has the 'sorted' builtin.
>
What does sorted() have anythng to do with orders like insertion order,
or some arbitary order that instead of a,b,c,d,e, I want it as e, c, b,
d, a ?

Personally, I have needs for ordered dict but I don't think it should
be in standard library though, as different situation called for
different behaviour for "ordered" and skewing my code to a standard lib
way is no good.

What I think is better is like the itertools recipe of giving example
of how one can make their own based on the needs.

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


Re: path module / class

2005-11-20 Thread Neil Hodgson
Peter Hansen:

>> There is a cost to the change as there will be two libraries that have 
>> to be known to understand code. 
> 
> Could you please clarify?  Which two do you mean?

At that point I was thinking about os.path and path.py. Readers will 
encounter code that uses both of these libraries.

> We've mandated use of path.py internally for all projects because we've 
> noticed (especially with non-expert Python programmers... i.e. junior 
> and intermediate types, and senior types new to Python) a decrease in 
> errors.  

A list of fault reports in this area would be useful evidence. The 
relative occurence of particular failures (such as incorrect path 
joining) is difficult to estimate which leads to the common messy 
handwaving over API choices.

To me, one of the bigger benefits of path.py is that it 
automatically uses Unicode strings on Windows NT+ which will behave 
correctly in more cases than byte strings.

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


Re: ownership problem?

2005-11-20 Thread Jeffrey Schwab
Fredrik Lundh wrote:
> Jeffrey Schwab wrote:
> 
> 
>>>Is it correct to say that the typical ownership problem, which
>>>frequently arises in C++, does not occur normally in Python?
>>
>>What "typical ownership problem" do you feel frequently arises in C++?
>>If you are referring to the sometimes difficult task of determining
>>which object owns a particular resource, why would it occur less in
>>Python than in C++?
> 
> 
> the problem isn't determining who owns it, the problem is determining
> who's supposed to release it.  that's not a very common problem in a
> garbage-collected language...

Yes it is.  Memory is only one type of resource.  There are still files 
and sockets to close, pipes to flush, log messages to be printed, GDI 
contexts to free, locks to release, etc.  In C++, these things are 
generally done by destructors, which are called automatically and 
deterministically.  I am not a Python Guru, but in Perl, Java, and other 
languages that have built-in garbage collectors, these tasks have to be 
done explicitly.  I find that this forces a procedural approach, even in 
an otherwise object-oriented program.

If you want something like automatic garbage collection in C++, I 
recommend the use of Factories with destructors that release the 
Factories' products.  The zeitgeist in c.l.c++.moderated seems to prefer 
the use of smart (reference-counted) pointers, which also rely on 
destructors to release resources automatically.  Plentry of free, 
open-source implementations are available.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Christoph Zwerschke
Fredrik Lundh wrote:
> if you restructure the list somewhat
> d = (
> ('pid', ('Employee ID', 'int')),
> ('name', ('Employee name', 'varchar')),
> ('sal', ('Salary', 'float'))
> )
> you can still loop over the list
> ...
> but you can easily generate an index when you need it:
> index = dict(d)

That's exactly the kind of things I find myself doing too often and what 
I was talking about: You are using *two* pretty redundant data 
structures, a dictionary and a list/tuple to describe the same thing. 
Ok, you can use a trick to automatically create the dictionary from the 
tuple, but still it feels somewhat "unnatural" for me. A "ordered 
dictionary" would be the more "natural" data structure here.

I also wanted to mention the uglyness in the definition (nested tuples), 
but then I understood that even an ordered dictionary would not 
eliminate that uglyness, since the curly braces are part of the Python 
syntax and cannot be used for creating ordered dictionaries anyway. I 
would have to define the ordered dictionary in the very same ugly way:

d = odict(('pid', ('Employee ID', 'int')),
('name', ('Employee name', 'varchar')),
('sal', ('Salary', 'float')))

(Unless the Python syntax would be extend to use double curly braces or 
something for ordered dictionaries - but I understand that this is not 
an option.)

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread [EMAIL PROTECTED]

Fredrik Lundh wrote:
> but you can easily generate an index when you need it:
>
> index = dict(d)
>
> name, type = index["pid"]
> print name
>
> the index should take less than a microsecond to create, and since it
> points to the members of the original dict, it doesn't use much memory
> either...
>
Using the same logic, we don't need types other than string in a  DBMS
as we can always convert a string field into some other types when it
is needed.

Of course there are more than one way to skin a cat(well it may be
against the general idiom of python) but in some situation certain way
is preferred.

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


Re: what happens when the file begin read is too big for all lines tobe?read with "readlines()"

2005-11-20 Thread Mike Meyer
"Ross Reyes" <[EMAIL PROTECTED]> writes:

> Yes, I have read this part
> How does one tell exactly what the limitation is to the size of  the
> returned list of strings?

There's not really a good platform-indendent way to do that, because
you'll get memory until the OS won't give you any more.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: examining python objects

2005-11-20 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> Bruno Desthuilliers wrote:
> 
>>[EMAIL PROTECTED] a écrit :
>>
>>>Is there a function/class/module/whatever I can use to
>>>look at objects?  I want something that will print the object's
>>>value (if any) in pretty-printed form, and list all it's attributes
>>>and their values.  And do all that recursively.
>>>I want to be able to find out everything about an object that
>>>Python can introspectively find out.
>>
>>Then check the inspect module
> 
> 
> I want a callable, ready-to-use class or function.
> Inspect provides soime funtions that would be useful for wrinting
> such a class or function, but does not provide one.
> 
> I seems that nobody who has written or used such a tool reads
> this group, or feels like responding.
> 
> FWIW, (for anyone looking for something similar in the future)
> I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951
> which will format and print an object's attributes.  By combining that
> and pprint in the Python distrib, I think can coble up what I am
> looking
> for.
> 
> Still, it is discouraging that such a basic thing is not provided with
> python, or at lleast easily available in some library.
> 
In the interactive mode, you might try >> help(object)

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


Re: Underscores in Python numbers

2005-11-20 Thread [EMAIL PROTECTED]

Peter Hansen wrote:
> [EMAIL PROTECTED] wrote:
> > Peter Hansen wrote:
> >
> >>But why would anyone want to create numeric literals for credit card
> >>numbers?
> >>
> > May be for space saving ? But storage space being so cheap, this is not
> > a very good reason, but still a reason.
>
> Space saving where?  Why would you have any credit card numbers stored
> in any application?  Even a credit card company isn't going to write
> code that has the numbers stored as *literals*!
I am not the one asking for it, only guessing the reason and credit
card company does save it in the database. So saving as half byte
numeric(or 64 bit integer) does save a bit of space comparing with
string.

>
> There's only one place I can think of right now where you might want
> that: in automated tests for code that processes credit card numbers.
> And you definitely do not need to "save space" in that situation...
>
That usually don't need it as one big number but usually more easier to
code if treating as string(like checksum), something like:

for digits in cc:
  checksum += int(digits)

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


Re: HTML generation vs PSP vs Templating Engines

2005-11-20 Thread riplin
>> Using templates means that the code can work with different templates,
>> and this should be seamless, it also means that different code can be
>> used with the templates, for example if different languages are used.

> This seems to contradict your statement that you dislike 'embedding
> code or html in each other', since the scenarios you describe still
> involve embedding presentation logic in markup. (The only templating
> systems that *completely* separate logic from markup are the DOM-style
> ones.)

Perhaps that is why I implemented my own mechanisms for templating. My
templates contain no logic at all and can be used from my Python
programs, Cobol or C equally well.

Contrarywise, my Python programs choose at runtime the required
template (depending on configuration, user request or other) and then
the same program code will output HTML, XML, EDIFACT, CSV, printed
report or other dependant entirely on the content of the template file.

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


Re: How to draw a dash line in the Tkinter?

2005-11-20 Thread Shi Mu
On 11/20/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Ben Bush wrote:
>
> > How to draw a dash line in the Tkinter?
>
> use the dash option.  e.g.
>
>canvas.create_line(xy, fill="red", dash=(2, 4))
>canvas.create_line(xy, fill="red", dash=(6, 5, 2, 4))
>
> (the tuple contains a number of line lengths; lengths at odd positions
> are drawn, lengths at even positions are gaps.  note that not all com-
> binations are supported on all platforms; if Tkinter cannot find an exact
> match, it will pick a the "closest possible").
>
> 
where can I find the option settings for dash line?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combine doxygen and doc-strings?

2005-11-20 Thread Diez B. Roggisch
Gabriel Zachmann wrote:
> Is there a way to combine doxygen comments, like this one

If you are not tied to doxygen, you might consider epydoc - it uses the 
docstrings, and restructured text which is friendly to the eye.

Regards,

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


Re: [Tutor] need a tutorial in tokens ,different types

2005-11-20 Thread Alan Gauld
>  could any one suggest me tutorials in different tokenizations and 
> clear describtion of how can i use token type and assign diff attributes 
> to tokens  

What kind of tokens? Are we talking l;exical tokens in a parser 
or security tokens or what?

> also good tutorials in diff data types in python 

The official documentaton explains most of it.

You can try the Raw Materials topic in my tutorial if you like.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: Underscores in Python numbers

2005-11-20 Thread Bruno Desthuilliers
Raymond Hettinger a écrit :
> Gustav Hållberg wrote:
> 
>>I tried finding a discussion around adding the possibility to have
>>optional underscores inside numbers in Python. This is a popular option
>>available in several "competing" scripting langauges, that I would love
>>to see in Python.
>>
>>Examples:
>>  1_234_567
>>  0xdead_beef
>>  3.141_592
> 
> 
> I suppose it could be done.  OTOH, one could argue that most production
> code has no business hardwiring-in numerical constants greater than 999
> ;-)
> 
That's what I thought at first, but Steven D'Aprano made some good 
points here IMHO, ie :

"""
Not all numeric constants used have simple formulae, or *any* formulae, or
can be calculated on the fly in any reasonable time. Numeric programming
often uses magic constants which truly are "magic" (in the sense that
where they come from requires deep, difficult, and sometimes hidden
knowledge).

Nobody sensible wants to be typing in long strings of digits, but
sometimes it is unavoidable.
"""

and

"""
Another sensible usage case is in the interactive interpreter. If you are
using Python interactively, you may wish to use numeric literals with
large numbers of digits. It is not feasible to read them from a data file,
and using a special converter function is impractical and unnecessary.
"""

So even if it's far from a common use case for *most* Python users, it 
may be a common use case for *some* Python users.

Also, someone mentionned the use of Python as a configuration langage - 
which is probably a much more common use case.


So FWIW, I'd be +1 on adding it *if and only if*:
- it's trivial to implement [1]
- it doesn't break older code

and +1 on the space as group delimiter BTW.


[1]: I never wrote a language by myself, but I've played a bit with 
parsers and lexers, and I _guess_ (which implies I may be wrong !-) it 
wouldn't require much work to add support for a "literal numeric 
grouping" syntax  in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-20 Thread Fredrik Lundh
Jeffrey Schwab wrote:

> > Is it correct to say that the typical ownership problem, which
> > frequently arises in C++, does not occur normally in Python?
>
> What "typical ownership problem" do you feel frequently arises in C++?
> If you are referring to the sometimes difficult task of determining
> which object owns a particular resource, why would it occur less in
> Python than in C++?

the problem isn't determining who owns it, the problem is determining
who's supposed to release it.  that's not a very common problem in a
garbage-collected language...





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


Re: Ajax for the Developers

2005-11-20 Thread John J. Lee
"Sabin.A.K, Bangalore" <[EMAIL PROTECTED]> writes:
[...]
> 1. Changing state with links (GET requests)
> 2.Asynchronously performing batch operations

I don't understand those two.


> 3.Breaking the back button
[...]

http://en.wikipedia.org/wiki/AJAX


Also of interest:

http://www.mozillazine.org/talkback.html?article=7162


John

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


Re: Underscores in Python numbers

2005-11-20 Thread Steven D'Aprano
On Sun, 20 Nov 2005 15:52:29 -0500, Roy Smith wrote:

> You have described, if memory serves, a Taylor series, and those 
> coefficients are 1/3!, 1/5!, 1/7!, etc.  What I would do, rather than 
> embedding the numeric constants in the code, is embed the formula and have 
> the machine compute the actual values at import time.  At the very least, 
> have them machine generated and saved.  You certainly don't want to be 
> typing in long strings of digits like that.

Not all numeric constants used have simple formulae, or *any* formulae, or
can be calculated on the fly in any reasonable time. Numeric programming
often uses magic constants which truly are "magic" (in the sense that
where they come from requires deep, difficult, and sometimes hidden
knowledge).

Nobody sensible wants to be typing in long strings of digits, but
sometimes it is unavoidable.

-- 
Steven.

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


Re: Underscores in Python numbers

2005-11-20 Thread Steven D'Aprano
On Sun, 20 Nov 2005 09:27:28 -0500, Peter Hansen wrote:

> But why would anyone want to create numeric literals for credit card 
> numbers?


Credit card numbers is not a sensible usage case. Neither are books'
ISBNs, or tax file numbers, or telephone numbers -- these are all
instances where it makes sense to read them from a data file and use a
converter function.

One sensible usage case is numeric calculations, where you often are
using numeric constants in some formula, and those constants may have ten,
twelve, fifteen digits. Being able to group digits makes it considerable
easier to enter the numbers, as well as proof-read your code.

c = 25.173 268 901 910 023

is considerably easier for the human reader to parse than:

c = 25.173268901910023

Calculating the number in place is not an acceptable solution:

c = 25.173 + 268e-3 + 901e-6 + 910e-9 + 23e-12

is bad for a number of reasons:

- it implies c is a calculated sum when it is not;
- it harms comprehension;
- it may very well lose accuracy;
- it is easy to miscalculate and end up with a completely wrong number;
- it complicates and obfuscates the compiled code.

Another sensible usage case is in the interactive interpreter. If you are
using Python interactively, you may wish to use numeric literals with
large numbers of digits. It is not feasible to read them from a data file,
and using a special converter function is impractical and unnecessary.

I don't know whether these two usage cases will be enough to justify
changing the way Python handles numeric literals -- Guido seems quite
conservative in what he adds to the language, so unless there is either
great demand or it scratches a particular itch he has personally, I doubt
it will fly. But we'll never know unless we try, hey? *wink*


-- 
Steven.

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


Re: Delays getting data on sys.stdin.readline() ?

2005-11-20 Thread Fredrik Lundh
Christian Convey wrote:

> So here's what I don't get: If "producer" was retaining its output for
> a while for the sake of efficiency, I would expect to see that effect
> when I just run "producer" on the command line. That is, I would
> expect the console to not show any output from "producer" until
> "producer" terminates.  But instead, I see the output immediately. So
> why, when I pipe the output to "consumer", doesn't "consumer" get
> access to that data as its produced unless "consumer" is explicitely
> calling sys.stdout.flush().
>
> Any thoughts?

your terminal is not a pipe.

$ man stdout

...

CONSIDERATIONS
 The stream stderr is unbuffered. The stream stdout is line-buffered when
 it points to a terminal. Partial lines will not appear until fflush(3) or
 exit(3) is called, or a newline is printed. This can produce unexpected
 results, especially with debugging output.  The buffering mode of the
 standard streams (or any other stream) can be changed using the setbuf(3)
 or setvbuf(3) call.  Note that in case stdin is associated with a termi­
 nal, there may also be input buffering in the terminal driver, entirely
 unrelated to stdio buffering.  (Indeed, normally terminal input is line
 buffered in the kernel.)  This kernel input handling can be modified
 using calls like tcsetattr(3); see also stty(1), and termios(3).

...





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

Re: ownership problem?

2005-11-20 Thread Jeffrey Schwab
Gabriel Zachmann wrote:
> Is it correct to say that the typical ownership problem, which 
> frequently arises in C++, does not occur normally in Python?

What "typical ownership problem" do you feel frequently arises in C++? 
If you are referring to the sometimes difficult task of determining 
which object owns a particular resource, why would it occur less in 
Python than in C++?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-20 Thread Ben Finney
Gabriel Zachmann <[EMAIL PROTECTED]> wrote:
> Is it correct to say that the typical ownership problem, which
> frequently arises in C++, does not occur normally in Python?

Could you explain what you mean by "the typical ownership problem"?

-- 
 \ "Jealousy: The theory that some other fellow has just as little |
  `\  taste."  -- Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python weak on the web side?

2005-11-20 Thread Ravi Teja
Too many options.
Google: python web frameworks
The first couple of links will point you to enough resources.

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


Re: Web-based client code execution

2005-11-20 Thread John J. Lee
Paul Watson <[EMAIL PROTECTED]> writes:

> What are the options?
> 
> The user to hits a web page, downloads code (Python I hope), execute it, 
> and be able to return the results.  It needs to be able to go through 
> standard HTTP so that it could be run from behind a corporate firewall 
> without any other ports being opened.
> 
> Am I stuck doing an ActiveX control?
[...]

If you just need to talk on port 80, just go ahead and do that (module
socket, module httplib, module urllib2, urllib.getproxies, etc), and
write a normal desktop application.


If it must run in a browser, here is some food for thought:


Compile Python to JavaScript -- very cool

http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework

http://www.aminus.org/blogs/index.php/phunt/2005/10/09/psst_crackajax_is_in_svn


Plain old AJAX with Python on server side

https://sourceforge.net/projects/json-py/

http://www.google.co.uk/search?q=ajax+python&btnG=Search (um, ignore the 1st 
result)


Write Java applets in Python

http://www.jython.org/


Flash 'local storage'

http://www.macromedia.com/support/documentation/en/flashplayer/help/help02.html

Sort-of AJAX-for-Flash stuff

http://www.cs.unc.edu/~parente/tech/tr04.shtml
http://www.simonf.com/flap/

Flash itself (boo;-)

http://www.macromedia.com/


XUL and PyXPCOM (Firefox only)

http://www.xulplanet.com/

http://trac.nunatak.com.au/projects/nufox


Firefox future capabilities in this direction (probably most of this
is relevant)

http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html

http://weblogs.mozillazine.org/roadmap/archives/2005_09.html


John

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


Re: ownership problem?

2005-11-20 Thread Bruno Desthuilliers
Gabriel Zachmann a écrit :
> Is it correct to say that the typical ownership problem, which 
> frequently arises in C++, does not occur normally in Python?

What is this "typical ownership problem" ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Fredrik Lundh
Christoph Zwerschke wrote:

> The example above is a bit misleading, because using 'a', 'b' as keys
> can give the impression that you just have to sort() the keys to have
> what you want. So let's make it more realistic:
>
> d = { 'pid': ('Employee ID', 'int'),
>'name': ('Employee name', 'varchar'),
>'sal': ('Salary', 'float') }
>
> Now if I want these things to be presented in this order, I need to run
> through a separate list ('pid', 'name', 'sal') that holds the order.
>
> Ok, you could simply use a list instead of a dictionary:
>
> d = ( ('pid', 'Employee ID', 'int'),
>('name', 'Employee name', 'varchar'),
>('sal', 'Salary', 'float') )

if you restructure the list somewhat

d = (
('pid', ('Employee ID', 'int')),
('name', ('Employee name', 'varchar')),
('sal', ('Salary', 'float'))
)

you can still loop over the list

for key, (name, type) in d:
print key, name, type # e.g. generate form entry

> This works as long as you *only* have to go through the list
> sequentially. But maybe you want to print the name with its description
> at some other place as well. Now how do you access its description
> 'Employee name' so easily?

but you can easily generate an index when you need it:

index = dict(d)

name, type = index["pid"]
print name

the index should take less than a microsecond to create, and since it
points to the members of the original dict, it doesn't use much memory
either...





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


Re: Is Python weak on the web side?

2005-11-20 Thread Simon Brunning
On 19/11/05, Michael Goettsche <[EMAIL PROTECTED]> wrote:
> On Sunday 20 November 2005 00:24, Tony wrote:
> > If I'd like to learn Python for web-development, what are the options
> > available?
>
> A nice framework is CherryPy: http://www.cherrypy.org
> or Turbogears, which is based on CherryPy: http://www.turbogears.org/

See also Django for CMS type sites.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python weak on the web side?

2005-11-20 Thread Bruno Desthuilliers
Tony a écrit :
> If I'd like to learn Python for web-development, what are the options 
> available?

There are too many *good* options for web developpement in Python.

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


ownership problem?

2005-11-20 Thread Gabriel Zachmann
Is it correct to say that the typical ownership problem, which frequently 
arises in C++, does not occur normally in Python?

Best regards,
Gabriel.

-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-20 Thread Robin Becker
David Wahler wrote:
> Steve wrote:
> 
>>AJAX works because browsers can execute javascript.  I don't know of a
>>browser that can execute python.  Basically your stuck with java or
>>javascript because everything else really isn't cross platform
> 
> 
> Don't jump to conclusions...
> http://dwahler.ky/python/
> 
> If you really, really want Python in a browser, it's certainly
> possible. :)
> 
> -- David
> 
well in firefox 1.07 I seem to be getting

Error: unmarshal is not defined
Source File: http://dwahler.ky/python/
Line: 133

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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Ben Finney
[restored my attribution line so we know who said what]

Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Ben Finney wrote:
> > In what cases do you find yourself needing a dict that preserves
> > its key order? Can you present a use case that would be improved
> > by an ordered dict?
> 
> There are too many different situations and it would be too much to
> explain them here, usually in the case mentioned above where the
> keys are not sorted alphabetically.

Without an example, it's hard to know what you want to do and whether
an ordered dictionary is the best way to do it.

> > For my part, I consider it a virtue of Python that the standard
> > library doesn't change rapidly. It allows many competing
> > implementations to be shaken out before everyone starts depending
> > on any one of them.
> 
> Ok, but this can be used as an argument to not add anything to the
> standard lib any more.

I hope not. Rather, it's an argument not to add something to the
standard library until it's proven (to the BDFL's criteria) that it's
better in than out.

> There are already enough competing 
> implementations.

Have they been sufficiently shaken out to show a clearly superior
version? Is any version sufficiently beneficial to write a PEP for its
inclusion in the standard library?

> I simply wanted to ask why it is not available in the standard lib,
> since I simply don't know
> 
> - has it not been demanded loud enough?

Loud demands don't count for much. PEPs with popular working
implementations do.

> - is it really not needed (if you need it it shows you are doing
> something wrong)?

You dismissed a request for your use cases with handwaving. How can we
know?

> - because nobody presented a satisfying implementation yet?

I'm not sure what you mean by "satisfying".

> - are there hidden difficulties or controversial issues?

Another possibility: ordered dictionaries are not needed when Python
2.4 has the 'sorted' builtin.

-- 
 \   "Those who will not reason, are bigots, those who cannot, are |
  `\ fools, and those who dare not, are slaves."  -- "Lord" George |
_o__)Gordon Noel Byron |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: func(*params)

2005-11-20 Thread Fredrik Lundh
David Duerrenmatt wrote:

> For some reasons, I've to use Python 1.5.2 and am looking for a workaround:
>
> In newer Python versions, I can call a function this way:
>
> func = some_function
> func(*params)
>
> Then, the list/tuple named params will automatically be "expanded" and
> n=len(params) arguments will be submitted.
>
> Python 1.5.2 doesn't support this kind of function call.

use

apply(func, params)

or

result = apply(func, params)

more info:

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

apply(...)
apply(object[, args[, kwargs]]) -> value

Call a callable object with positional arguments taken from the tuple 
args,
and keyword arguments taken from the optional dictionary kwargs.
Note that classes are callable, as are instances with a __call__() 
method.

Deprecated since release 2.3. Instead, use the extended call syntax:
function(*args, **keywords).





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


Re: Command line

2005-11-20 Thread Fredrik Lundh
"amfr" wrote:

> Hoe would I call something on the command line from python, e.g. "ls
> -la"?

os.system(cmd), or some relative:

http://docs.python.org/lib/os-process.html
http://docs.python.org/lib/os-newstreams.html#os-newstreams

or

http://docs.python.org/lib/module-subprocess.html

:::

also note that you shouldn't use external commands for trivial things like
getting a list of files or getting the size of a file; you can get a list of all
files in a directory with

files = os.listdir(directory)
for file in files:
file = os.path.join(directory, file) # full path
...

or

files = glob.glob(pattern)
for file in files:
...

and you can get information about a given file with

st = os.stat(file)

size = st.st_size
mtime = st.st_mtime
(etc)

or

size = os.path.getsize(file)
mtime = os.path.getmtime(file)
(etc)





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


Re: Why are there no ordered dictionaries?

2005-11-20 Thread Christoph Zwerschke
[EMAIL PROTECTED] schrieb:
> By ordered dict, one usually wants order that is arbitary which cannot
> be derived from the content, say insertion order(most ordered dict I
> saw use this order).
> I am writing a web applications(simple forms) which has a number of
> fields. Each field naturally has a name and a number of
> attributes(formatting etc.), like this :
> d = {'a':{...}, 'b':{}}

Things like that are also my typical use case. The keys usually contain 
things like database fields or html form fields, the values contain the 
corresponding description, formatting, data type or data itself etc.

The example above is a bit misleading, because using 'a', 'b' as keys 
can give the impression that you just have to sort() the keys to have 
what you want. So let's make it more realistic:

d = { 'pid': ('Employee ID', 'int'),
   'name': ('Employee name', 'varchar'),
   'sal': ('Salary', 'float') }

Now if I want these things to be presented in this order, I need to run 
through a separate list ('pid', 'name', 'sal') that holds the order.

Ok, you could simply use a list instead of a dictionary:

d = ( ('pid', 'Employee ID', 'int'),
   ('name', 'Employee name', 'varchar'),
   ('sal', 'Salary', 'float') )

This works as long as you *only* have to go through the list 
sequentially. But maybe you want to print the name with its description 
at some other place as well. Now how do you access its description 
'Employee name' so easily?

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


BaseHTTPServer module

2005-11-20 Thread amfr
>From the BaseHTTPServer module, how do i gget the POST or GET data sent
by the client?  Is it stired the the file they requested? e.g.
objectname.path

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


BaseHTTPServer module

2005-11-20 Thread amfr
>From the BaseHTTPServer module, how do i gget the POST or GET data sent
by the client?  Is it stired the the file they requested? e.g.
objectname.path

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


Re: Web-based client code execution

2005-11-20 Thread Robert Kern
Paul Watson wrote:

> I have read some about AJAX.  Is there an APAX coming for Python?

Not until browsers have embedded Python interpreters. There's been talk
about doing this in Mozilla, but I don't think the talk has turned into
usable code, yet.

-- 
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: Why are there no ordered dictionaries?

2005-11-20 Thread Christoph Zwerschke
> What answers have you received that have not been satisfactory?

I googled a little bit and haven't found many answers at all. Some were 
in the posting I mentioned: Stuff should go into the standard lib only 
when it is mature and "right" enough. However, we are already at Python 
2.4 and there is still no ordered dictionary, though there is a lot of 
other specialized stuff.

> Some possible answers: The native dict is very fast, partly because
> the implementation doesn't need to ensure any particular ordering.

Ok, but that's not an argument against providing ordered dictionaries as 
well.

> Ordering the keys isn't the normal case, and can be done easily when
> needed.

That depends. Maybe I do not want the keys to be sorted alphabetically, 
but according to some criteria which cannot be derived from the keys 
themselves.

> You asked "why not" rather than "has anyone done this anyway"; if
> you asked the latter of the Python Cookbook, you might find something
> like this.

Yes, I also found that others have done it more than once, and I know 
that it's not so difficult to do. There are at least two recipes in the 
mentioned cookbook and there is odict in pythonutils. The question was 
why is it not available in the *standard* lib.

> In what cases do you find yourself needing a dict that preserves its
> key order? Can you present a use case that would be improved by an
> ordered dict?

There are too many different situations and it would be too much to 
explain them here, usually in the case mentioned above where the keys 
are not sorted alphabetically. I often solve them by using two data 
structures, a list or tuple, plus a dictionary. For instance, the list 
could contain the names of database fields which shall be output in a 
certain order, and the dictionary values could contain human readable 
description of the database fields for headers or something. Instead of 
maintaining both data structures I feel it would be more natural to use 
only one ordered dictionary.

> For my part, I consider it a virtue of Python that the standard
> library doesn't change rapidly. It allows many competing
> implementations to be shaken out before everyone starts depending on
> any one of them.

Ok, but this can be used as an argument to not add anything to the 
standard lib any more. There are already enough competing 
implementations. Also, the implementation details are not so important, 
there must be only agreement on the interface and behavior which should 
not be so difficult in this case.

I simply wanted to ask why it is not available in the standard lib, 
since I simply don't know

- has it not been demanded loud enough?
- is it really not needed (if you need it it shows you are doing 
something wrong)?
- because nobody presented a satisfying implementation yet?
- are there hidden difficulties or controversial issues?

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


Re: Delays getting data on sys.stdin.readline() ?

2005-11-20 Thread Christian Convey
On 11/19/05, Mike Meyer <[EMAIL PROTECTED]> wrote:
> Christian Convey <[EMAIL PROTECTED]> writes:
> > I've got a program that (ideally) perpetually monitors sys.stdin for
> > lines of text. As soon as a line comes in, my program takes some
> > action.
> > The problem is, it seems like a very large amount of data must
> > accumulate on sys.stdin before even my first invocation of readline()
> > returns.  This delay prevents my program from being responsive in the
> > way it must be.
>
> readline normally returns as soon as it sees a newline. External
> conditions may cause this to change, or make it impossible. Without
> knowing those external conditions, the best we can do is guess as to
> what might be the problem.
>
> > Has anyone else seen this effect?  If so, is there a reasonable workaround?
>
> Yes, and maybe. Depends on what's causing the problem. Tell us more
> about the program, and what sys.stdin is connected to, and the
> platform you're running on, and someone should be able to provide
> explicit information.

OK, I've fixed it, but I don't understand why the fix works.

Let's say I've got two Python programs, I'll call "producer" and
"consumer". "producer" runs for a long time and occasionally while
running sends lines of text to stdout. "consumer" is typically blocked
in a call to sys.stdin.readline().

When I run "producer" on its own, I see its output appear on the
console pretty much immediately after calling the "print" command.

But when I pipe "producer"s output to "consumer"s stdin on the Linux
command line, "consumer" stays blocked on its first call to
sys.stdin.readline() until the "producer" program terminates. At that
point, "consumer" seems to immediately get access to all of the stdout
produced by "producer".

I've found I can fix this problem by modifying "producer" so that
immediately after each "print" command, I call sys.stdout.flush(). 
When I make this modification, I find that "consumer" has access to
the output of "producer" immediately after "producer" issues a "print"
statement.

So here's what I don't get: If "producer" was retaining its output for
a while for the sake of efficiency, I would expect to see that effect
when I just run "producer" on the command line. That is, I would
expect the console to not show any output from "producer" until
"producer" terminates.  But instead, I see the output immediately. So
why, when I pipe the output to "consumer", doesn't "consumer" get
access to that data as its produced unless "consumer" is explicitely
calling sys.stdout.flush().

Any thoughts?

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


Re: Speeding up multiple regex matches

2005-11-20 Thread Fredrik Lundh
"Talin" wrote:

> I've run in to this problem a couple of times. Say I have a piece of
> text that I want to test against a large number of regular expressions,
> where a different action is taken based on which regex successfully
> matched. The naive approach is to loop through each regex, and stop
> when one succeeds. However, I am finding this to be too slow for my
> application -- currently 30% of the run time is being taken up in the
> regex matching.
>
> I thought of a couple of approaches, but I am not sure how to make them
> work:
>
> 1) Combine all of the regular expressions into one massive regex, and
> let the regex state machine do all the discriminating. The problem with
> this is that it gives you no way to determine which regex was the
> matching one.

use a capturing group for each alternative, and use lastindex to quickly
find the match:

http://docs.python.org/lib/match-objects.html

lastindex

The integer index of the last matched capturing group, or None if
no group was matched at all.

also see:

http://effbot.org/zone/xml-scanner.htm





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


Re: Underscores in Python numbers

2005-11-20 Thread Roy Smith
[EMAIL PROTECTED] (David M. Cooke) wrote:

> One example I can think of is a large number of float constants used
> for some math routine. In that case they usually be a full 16 or 17
> digits. It'd be handy in that case to split into smaller groups to
> make it easier to match with tables where these constants may come
> from. Ex:
> 
> def sinxx(x):
> "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
> a2 = -0.1 4
> a4 =  0.00833 33315
> a6 = -0.00019 84090
> a8 =  0.0 27526
> a10= -0.0 00239
> x2 = x**2
> return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10
> 
> (or least that's what I like to write). Now, if I were going to higher
> precision, I'd have more digits of course.

You have described, if memory serves, a Taylor series, and those 
coefficients are 1/3!, 1/5!, 1/7!, etc.  What I would do, rather than 
embedding the numeric constants in the code, is embed the formula and have 
the machine compute the actual values at import time.  At the very least, 
have them machine generated and saved.  You certainly don't want to be 
typing in long strings of digits like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command line

2005-11-20 Thread Diez B. Roggisch
amfr wrote:
> Hoe would I call something on the command line from python, e.g. "ls
> -la"?

Use the module subprocess - otherwise maybe popen2 or os.

Regards,

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


need a tutorial in tokens ,different types

2005-11-20 Thread enas khalil
hello all  could any one suggest me tutorials in different tokenizations and clear describtion of how can i use token type and assign diff attributes to tokens  ,also good tutorials in diff data types in python   thanks every body  enas
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

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

Re: Command line

2005-11-20 Thread avnit
What OS are you using. I'm not sure about anything else but on a mac
it's:

>>import os
>>os.system("ls -la")

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


Command line

2005-11-20 Thread amfr
Hoe would I call something on the command line from python, e.g. "ls
-la"?

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


  1   2   >