Re: 'isa' keyword

2005-09-03 Thread Bengt Richter
On Thu, 01 Sep 2005 21:25:20 -0500, D H [EMAIL PROTECTED] wrote:

talin at acm dot org wrote:
 Although I realize the perils of even suggesting polluting the Python
 namespace with a new keyword, I often think that it would be useful to
 consider defining an operator for testing whether or not an item is a
 member of a category.

It's a good idea but not likely to be added to python, at least not til 
python 3000 comes out with type checking.  The default way is if 
isinstance(image, jpeg).
Also there is if image |isa| jpeg: using one of the various python 
hacks out there:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122

But since Python doesn't have interfaces or type checking today, there 
really is not much need for isa or isinstance anyway, but you might use 
hasattr or try/except instead: http://www.canonical.org/~kragen/isinstance/

I recently experimented with an ast-rewriting importer, and I suspect could
set up a configurable importer that would recognize '|isa|' (or with any other
legal binary op in place of '|'). Maybe '**' would stand out in
if image **isa** jpeg and reduce processing since it's less commonly used
than e.g., + or -. OTOH, the latter would permit unary operator definitions
as well, e.g., -inv- mx could translate to mx**-1 meaning

Sub((UnarySub(Name('inv')), Name('mx')))

int the ast is translated to opmod.inv(mx) replacing the above with

CallFunc(Getattr(Name('opmod'), 'inv'), [Name('mx')], None, None)

You could just write a module so that names to use would be given by

[name for name in dir(opmod) if not name.startswith('_') and 
callable(getattr(opmod, name)]

and then have the importer do that when given the module as config info, and 
look
for the names, e.g., 'inv' in an ast subtree context as above, or for left 
-isa- right
look for

Sub((Sub((Name('left'), Name('isa'))), Name('right')))

and rewite it as

CallFunc(Getattr(Name('opmod'), 'isa'), [Name('left'), Name('right')], 
None, None)

My recent post was doing 'a/b' = safediv(a, b) in a similar fashion,
which gives me the feeling that -xx- as custom infix operator would
work for a lot of contexts. BTW, the ast for left |isa| right is

Bitor([Name('left'), Name('isa'), Name('right')])

which probably makes it faster to recognize. Obviously subtrees not
involving the specal op names would be ignored.

I don't know if ast-rewriting on the fly during customizable import
excites anyone, or if those who understand what I'm doing would just
rather I didn't post about it devant les enfants ;-)

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


Re: defining classes

2005-09-03 Thread Steve Holden
LeRoy Lee wrote:
 I have been searching for the answer to this as it will determine how I use 
 classes.  Here are two bits of code.

[snip already well-quoted examples]

 
 I can't figure out why it is working this way.  I figure I must be thinking 
 about this wrong.  I was thinking that I could bind attributes to the class 
 from within methods using the self prefix.  According to this example I can 
 only when passing other info into the init.  Is there a rule that I am just 
 not aware off?  Am I totally off base (I am not real experienced)?  What is 
 the self prefix for then if not to bind up the tree?
 
You are clearly Doing Something Wrong (tm), as I and a number of other 
experienced Python programmers don't see the problems you are seeing. Is 
it possible that you didn't cut-and-paste those examples, but instead 
retypes them, and in so doing accidentally corrected your error in the 
posting you made to the group?

You seem to understand how classes should (and do) work, so it was 
probably a PICNIC error :-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: urllib.urlopen doesn't work

2005-09-03 Thread Steve Holden
Josef Cihal wrote:
 Hallo,
  
 i need a help with module URLLIB.
  
 I am trying to open url via:
 -urllib.urlopen
 ('http://brokerjet.ecetra.com/at/markets/stocks/indices.phtml?notation=92866')
  
  
 Problem is, that I am always redirecting to
 - LOGIN page (www.brokerjet.at http://www.brokerjet.at),
 and cannot get my page with news, which I want to download.
  
 Can it be, that I forgot to pass all (hidden too) parameters to form by 
 submit?
  
 Is it possible to get (ask) for all existing valid parameters, which I 
 need to pass to form
 for getting requested page?
 Is action submit correct in my case?
  
  
 Thank you very much for all your help or ideas
  
I suspect that the problem is you are attempting to access a web 
application in which every page checks for a valid login and, if this 
isn't present, redirects you to the login page.

You might try a URL for the form

 http://username:[EMAIL PROTECTED]/path/resource

as this is the easiest way to achieve basic authentication. Otherwise 
there are other ways, which you can get back to us about.

Also you might try just starting a new browser session an entering the 
URL that gave you problems in your code. If the browser displays the 
page correctly then *either* it has cookies set that you aren't setting 
when you call urllib.urlopen() *or* I'm wrong. :-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Problem with response object

2005-09-03 Thread Steve Holden
Harish Kotian wrote:
 Hi Steve
 I copied the lines from your mail and again got the error.
 I am only pasting the relevant error lines below.
 
 • Error Type:
 Python ActiveX Scripting Engine (0x80020009)
 Traceback (most recent call last): File Script Block , line 1, in ? 
 response.redirect(http://www.holdenweb.com/;) NameError: name 
 'response' is not
 defined
 /test/test7.asp, line 3
 response.redirect(http://www.holdenweb.com/;)
 
 The code now reads as below
 %@ LANGUAGE = Python%
 %
 response.redirect(http://www.holdenweb.com/;)
 
 %
 
 
 - Original Message - From: Steve Holden [EMAIL PROTECTED]
 To: Harish Kotian [EMAIL PROTECTED]
 Cc: python-list@python.org
 Sent: Saturday, September 03, 2005 10:42 AM
 Subject: Re: Problem with response object
 
 
 Harish Kotian wrote:

 Hi Steve
 Thank you for getting back. I suspect I am having problem with the 
 response object in Python.
  I also tried with response.write it didn't work.
 I pasted your code into my page and tried it. I am again pasting the 
 code followed by the error page.
 I shall be grateful if you can figure  out the problem.
 harish.
 %@ LANGUAGE = Python%
  %
  response.redirect(http://yahoo.com/;)

 ^^^


 %
 The page cannot be displayed
  The page cannot be displayed
  There is a problem with the page you are trying to reach and it 
 cannot be displayed.
  Please try the following:
 List of 2 items
 • Click the
 Refresh
 button, or try again later.
 • Open the
 kotian
 home page, and then look for links to the information you want.
 list end
  HTTP 500.100 - Internal Server Error - ASP error
 Internet Information Services
  Technical Information (for support personnel)
 List of 5 items
 • Error Type:
 Python ActiveX Scripting Engine (0x80020009)
 invalid syntax
 /test/test7.asp, line 4, column 4
 response.redirect(http://yahoo.com/;)
 ---^
  • Browser Type:
 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 
 1.1.4322)
  • Page:
 GET /test/test7.asp
  • Time:
 Saturday, September 03, 2005, 10:32:03 AM
  • More information:
 Microsoft Support
  list end

 The traceback explains the problem: Python programs must start with no 
 indentation. Even when writing in ASP code-brackets (% ... %) each 
 code block must be a valid Python snippet.

 Also each code block stands alone, so you start afresh with no 
 indentation whenever you open a new code-bracket. Try

 %
 response.redirect(http://www.holdenweb.com/;)
 %

OK. This is excellent. You will notice you are no longer receiving 
syntax error reports. It may not seem like it, but this is progress! 
Could you now try

%
Response.Redirect(http://www.holdenweb.com/;)
%

Hint: Python is case-sensitive.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with response object

2005-09-03 Thread Steve Holden
Harish Kotian wrote:
 Hi Steve
 Thank you for getting back. I suspect I am having problem with the 
 response object in Python.
  
 I also tried with response.write it didn't work.
 I pasted your code into my page and tried it. I am again pasting the 
 code followed by the error page.
 I shall be grateful if you can figure  out the problem.
 harish.
 %@ LANGUAGE = Python%
  
 %
  response.redirect(http://yahoo.com/;)
^^^
 
 %
 The page cannot be displayed
  
 The page cannot be displayed
  
 There is a problem with the page you are trying to reach and it cannot 
 be displayed.
  
 Please try the following:
 List of 2 items
 • Click the
 Refresh
 button, or try again later.
 • Open the
 kotian
 home page, and then look for links to the information you want.
 list end
  
 HTTP 500.100 - Internal Server Error - ASP error
 Internet Information Services
  
 Technical Information (for support personnel)
 List of 5 items
 • Error Type:
 Python ActiveX Scripting Engine (0x80020009)
 invalid syntax
 /test/test7.asp, line 4, column 4
 response.redirect(http://yahoo.com/;)
 ---^
  
 • Browser Type:
 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)
  
 • Page:
 GET /test/test7.asp
  
 • Time:
 Saturday, September 03, 2005, 10:32:03 AM
  
 • More information:
 Microsoft Support
  
 list end
  
The traceback explains the problem: Python programs must start with no 
indentation. Even when writing in ASP code-brackets (% ... %) each 
code block must be a valid Python snippet.

Also each code block stands alone, so you start afresh with no 
indentation whenever you open a new code-bracket. Try

%
response.redirect(http://www.holdenweb.com/;)
%

and see if that works.

regards
  Steve

-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


python logo

2005-09-03 Thread Xah Lee
i noticed that Python uses various logos:

http://python.org/pics/pythonHi.gif
http://python.org/pics/PyBanner038.gif
http://python.org/pics/PyBanner037.gif
http://python.org/pics/PythonPoweredSmall.gif
http://wiki.python.org/pics/PyBanner057.gif

 is this some decision that python should use various different logos?

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: To the python-list moderator

2005-09-03 Thread Fredrik Lundh
Terry Reedy wrote:

  What's
 happening is that Spambayes is marking the message as UNSURE.  The
 message that mailman sends to the sender is unfortunate.  The
 Message has a suspicious header notice is misleading because the
 user did not have any header in their message that caused it to be
 held (at least normally not).

 Is that hardwired into Spambayes or can it be edited.

it's a mailman thing.  I suspect that they run things through spambayes,
and use mailman filters to look for UNSURE in the X-Spam-Status
header added by spambayes.  see e.g.

http://www.python.org/cgi-bin/faqw-mm.py?req=showfile=faq03.059.htp

I'm pretty sure the python.org administrators have the mailman source
code, so it shouldn't be that hard to fix the message...

/F 



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


Re: Help for NewBies at WikiBooks

2005-09-03 Thread Do Re Mi chel La Si Do
Hi !

I had read the article on Python's concept  Metaclass: zero error in 
the content !

@-salutations

Michel Claveau



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


Re: python logo

2005-09-03 Thread Steve Holden
Xah Lee wrote:
 i noticed that Python uses various logos:
 
 http://python.org/pics/pythonHi.gif
 http://python.org/pics/PyBanner038.gif
 http://python.org/pics/PyBanner037.gif
 http://python.org/pics/PythonPoweredSmall.gif
 http://wiki.python.org/pics/PyBanner057.gif
 
  is this some decision that python should use various different logos?
 
  Xah
  [EMAIL PROTECTED]
 ∑ http://xahlee.org/
 
Yes.
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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

Re: PyBool_FromLong

2005-09-03 Thread Reinhold Birkenfeld
Michael Hoffman wrote:
 Andrew MacKeith wrote:
 In the C API Docs, the signature of PyBool from long seems to be incorrect.
 
 int PyBool_FromLong(long v)
 Returns Py_True or Py_False depending on the truth value of v. New 
 in version 2.3.
 
 The description would suggest:
 
 PyObject* PyBool_FromLong(long v)
 
 That's in the source too (dist/src/Objects/boolobject.c, 
 dist/src/Include/boolobject.h). Want to submit a documentation bug?

Not necessary. I just fixed it.

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


Re: python logo

2005-09-03 Thread Michele Petrazzo
Xah Lee ha scritto:
 i noticed that Python uses various logos:
 


Ok, this are not a logo, but better image are this:
http://python.org/pics/PythonIndented_Back.jpg

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


Re: python logo

2005-09-03 Thread Xah Lee
what's the decision? any reference to the discussion?

i thought it is better for Python to have one single recognizable logo.
Perhaps python doesn't have a logo and the official python people
decided it shouldn't or just doesn't have one currently?

of course, a logo helps in identity and as well as advertisement.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

Steve Holden wrote:
 Xah Lee wrote:
  i noticed that Python uses various logos:
 
  http://python.org/pics/pythonHi.gif
  http://python.org/pics/PyBanner038.gif
  http://python.org/pics/PyBanner037.gif
  http://python.org/pics/PythonPoweredSmall.gif
  http://wiki.python.org/pics/PyBanner057.gif
 
   is this some decision that python should use various different logos?
 
   Xah
   [EMAIL PROTECTED]
  ∑ http://xahlee.org/
 
 Yes.
 --
 Steve Holden   +44 150 684 7255  +1 800 494 3119
 Holden Web LLC http://www.holdenweb.com/

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

Re: python logo

2005-09-03 Thread Tim Churches
Xah Lee wrote:

i noticed that Python uses various logos:

http://python.org/pics/pythonHi.gif
http://python.org/pics/PyBanner038.gif
http://python.org/pics/PyBanner037.gif
http://python.org/pics/PythonPoweredSmall.gif
http://wiki.python.org/pics/PyBanner057.gif

 is this some decision that python should use various different logos?

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

  

A foolish consistency is the hobgoblin of little minds.
  - Ralph Waldo Emerson

Tim C

PS Yes, I know that I shouldn't feed the trolls (or hobgoblins), but I 
invoke Screwtape's Defence: other people who should know better don't 
seem to be able to resist the temptation either...

PPS Emerson's assertion might well apply not just to Python logos, but 
also, ahem, to certain aspects of the Python standard library.

TC


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

Re: Proposal: add sys to __builtins__

2005-09-03 Thread tiissa
Michael Hoffman wrote:
 To the contrary, I agree with Larry Wall that laziness is one of the 
 cardinal virtues of a programmer.

There's lazy and too lazy.
You don't want to be too lazy to even get out of bed to code in Python. 
Of course, with Perl, that's entirely another mattress^Wmatter.


 Would you argue that the language is superior because half of its 
 modules must have import sys at the beginning

I wouldn't dare arguing about superiority.

I was just stating your proposal didn't really solve anything. A good 
editor/template and .pythonrc already save you the typing of 'import 
sys' in scripts for the former and shell command for the latter.


 Sorry, that's incorrect

Alright, that was a bit of an overstatement.
I should have said your proposal is perceptibly useful in those shell 
one-liners. The distribution of script and modules is another matter.


As for my opinion, you've already guessed I don't perceive 'import sys' 
as an issue. Therefore, the special case of an implicit import of sys 
does not appeal to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python logo

2005-09-03 Thread Diez B. Roggisch
 A foolish consistency is the hobgoblin of little minds.
  - Ralph Waldo Emerson
 
 Tim C
 
 PS Yes, I know that I shouldn't feed the trolls (or hobgoblins), but I 
 invoke Screwtape's Defence: other people who should know better don't 
 seem to be able to resist the temptation either...
 
 PPS Emerson's assertion might well apply not just to Python logos, but 
 also, ahem, to certain aspects of the Python standard library.

AMEN!

and +1 QOTW

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


Re: 'isa' keyword

2005-09-03 Thread Devan L
talin at acm dot org wrote:
 Thanks for all the respones :) I realized up front that this suggestion
 is unlikely to gain approval, for reasons eloquently stated above.
 However, there are still some interesting issues raised that I would
 like to discuss.

 Let me first respond to a few of the comments:

 What's the difference between this and ``isinstance`` ?

 What's the difference between 'in' and 'has_key()? 1) Its shorter and
 more readable, 2) it can be overridden to mean different things for
 different container types.

Your analogy doesn't apply to non dictionaries. In any case, nothing
stops you from writing your own has_key() method for a different
container type. Likewise, if you made an isa keyword, it would just
call a method to have the traits you described above. You could write
your own method to see if it was an instance of the class, but it would
end up being more or less similar to isinstance().

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


Re: python logo

2005-09-03 Thread Devan L

Xah Lee wrote:
 what's the decision? any reference to the discussion?

 i thought it is better for Python to have one single recognizable logo.
 Perhaps python doesn't have a logo and the official python people
 decided it shouldn't or just doesn't have one currently?

 of course, a logo helps in identity and as well as advertisement.

  Xah
  [EMAIL PROTECTED]
 ∑ http://xahlee.org/

 Steve Holden wrote:
  Xah Lee wrote:
   i noticed that Python uses various logos:
  
   http://python.org/pics/pythonHi.gif
   http://python.org/pics/PyBanner038.gif
   http://python.org/pics/PyBanner037.gif
   http://python.org/pics/PythonPoweredSmall.gif
   http://wiki.python.org/pics/PyBanner057.gif
  
is this some decision that python should use various different logos?
  
Xah
[EMAIL PROTECTED]
   ∑ http://xahlee.org/
  
  Yes.
  --
  Steve Holden   +44 150 684 7255  +1 800 494 3119
  Holden Web LLC http://www.holdenweb.com/

There should only be one obvious way to do it, but there are many
creative ways to do it too.

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

How to identify which interface a broadcast packet comes in on?

2005-09-03 Thread Lincoln Yeoh
Hi,

If I have a program listening on 0.0.0.0:(someport) on all interfaces,
how do I know which network interface a broadcast packet is coming in
on - assuming Linux and _many_ interfaces. And how do I set which
interface a frame will leave on, assuming I'm sending a raw frame (no
IP address, just the ethernet address).

If I use C, it seems I'm to use the IP_PKTINFO socket options,
send/recv the ancillary messages and set/check the  ipi_ifindex value.

struct in_pktinfo {
unsigned intipi_ifindex;/* Interface index */
struct in_addr  ipi_spec_dst;   /* Local address */
struct in_addr  ipi_addr;   /* Header Destination address
*/
};

How would I achieve the same thing in Python? 

This would be useful for writing something like a DHCP server - such a
server could receive packets with source IP addresses of 0.0.0.0
destined to 255.255.255.255, and will need to know which interface the
packet is coming in from AND the source ethernet (or other link layer)
address so that it can send the replies out the right interface.

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


embedding python in C, working but with exception at the end

2005-09-03 Thread brobigi
well I manage to figure it out myself. I'm using Bloodshed Dev-cpp
Here's the code:


#include python.h
#include stdio.h

int main(int argc, char* argv[])
{
double answer = 0;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;

Py_Initialize();
modname = PyString_FromString(Test);
mod = PyImport_Import(modname);
if (mod)
{
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, doit); /* borrowed 
reference */
if (func)
{
if (PyCallable_Check(func))
{
stringarg = PyString_FromString(5);/*pay 
attention here*/
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, stringarg);
rslt = PyObject_CallObject(func, args);
if (rslt)
{
answer = PyFloat_AsDouble(rslt);
Py_XDECREF(rslt);
}
  Py_XDECREF(stringarg);
  Py_XDECREF(args);
}
}

Py_XDECREF(mod);
}

Py_XDECREF(modname);

Py_Finalize();

printf(%g,answer);

return 0;
}

I need to add include and lib directories to the project in order to
everything works fine. Also Test.py  is copied in Dev-cpp source code's
folder.
Test file contains the following code

def doit(x1):
try:
x2 = eval(x1)
except:
print 'Error!'
return 0

else:
return x2




However there is an error. Look at the line stringarg =
PyString_FromString(5); If I put this:
stringarg = PyString_FromString(5+2); or even this stringarg =
PyString_FromString(5.0);
Program crashes at line Py_Finalize(). Program tries to read some
memory location and suffer run time exception.
Only suggestion is to try to send it to Microsoft.
Why is this happening?
Everything (seems to) works fine I comment line Py_Finalize(), but I
know that this is not a real solution.

Does anybode have a clue what is happening?

Thanks

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


Re: 'isa' keyword

2005-09-03 Thread phil hunt
On Sat, 03 Sep 2005 00:45:19 -0500, Steve Holden [EMAIL PROTECTED] wrote:
 I'm not talking about a change in *paradigm* merely a change in 
 *syntax*; this:
 
receiver selector argument
 
 would mean the same as the current Python:
 
receiver.selector(argument)
 
Aah, I see. I had assumed that selector was always going to be an 
operator. 3 . (+ 4) does indeed seem very SmallTalkative. I don't 
think that Python method (or attribute) selection bears any relationship 
to SmallTalk message-passing, but I hope you will feel free to enlighten me.

Let's consider the Python example first.

You have two classes A and B. Each has a method called 'selector'.

When the line of code above is executed, the Python virtual machine 
decides whether (receiver) is a member of A or B, and then executed 
one of A.selector() or B.selector() depending on which it is. 
Whichever function is executed, it is passed with (reciever) as the 
self argument so that the correct data is operated on.

And now let's consider the Smalltalk example. How does it do it? 
Essentially it does *exactly the same thing*.

(Yes, I know there are many differneces in detail between how 
Snalltalk and Python  work, but they are only *details*; the 
fundamental idea governing how these two object-oriented languages 
work is the same).

would necessarily 
benefit Python at this stage. Some people are still under the 
misapprehension that message-passing is a fundamental of object-oriented 
programming because of Smalltalk, but they are wrong.
 
 
 I don't see how it can reasonably said that STK has 
 message-passing but other OOPLs don't. Consider these code 
 fragments:
 
 Smalltalk:
receiver selector: argument
 
 C++ or Java:
receiver.selector(argument);
 
 Python:
receiver.selector(argument)
 
 PHP:
$receiver-selector($argument)
 
 (I'm not sure if the last one is right since I've not done much OO 
 stuff in PHP)
 
 These all mean essentially the same thing so how can one be message 
 passing and the others not?
 
Sorry, they don't all mean essentially the same thing at all. It seems 
to me you are looking at SmallTalk in entirely too superficial a light. 

OK, allow me to reprase it. Imagine a language ith the semantics of 
Python but the syntax of C++ or PHP or Smalltalk (or Lisp for that 
matter). It would still basically be Python, wouldn't it?

  In SmallTalk, control structures aren't syntactic primitives, they are 
also examples of message-passing, so code blocks are sent as messages to 
objects. Python eschews such obscurity and (IMHO) gains clarity by so 
doing. But that is, of course, a matter of opinion.

I agree, that's a major point of departure between Python and 
Smalltalk.

Also, remember that just because two expressions in different languages 
mean the same thing doesn't mean they are implemented using the same 
techniques.

Of course not. 

CPython and JPython are different implementations, but they are 
still the same language (mostly).

I would contend (if backed into a corner) that there is a significant 
difference between passing the arguments 3 and 4 to a + operator 
(which is what Python and most other languages implementing standard 
ideas of operator precedence do) and sending the message + 4 to the 
integer 3 (which is effectively what SmallTalk does).

In both python and smalltalk you can override the operator to mean 
what you want, so I disagree that there is any fundamental 
difference. Why do you think there is?

Of course, I realise that you can argue that the two are equivalent in 
the sense that they perform the same computation. But SmallTalk's choice 
led to the loss of operator precedence, which is something that is 
pretty fundamental to mathematics. 

Surely that's a separate issue, one purely of syntax. Imagine two 
languages:

   (* (+ a b) c)

and:

   (a + b) * c

These both mean the same thing, they just say it differently.

Also Python allows much more 
flexibility by hard-wiring operators and allowing alternatives to be 
considered (if the left operand doesn't have an __add__ method then 
try to use the right operand's __radd__ method). SmallTalk doesn't 
have any parallel to this that I can think of.

You're right; in Smalltalk you'd have to code that functionality in
the method for the left-hand object.

Of course it isn't only mathematicians who are taught to us the 
precedence rules, so I contend that SmallTalk would seem 
counter-intuitive in a Programming for Everyone context as well. 

Probably. 

However consider that a language (e.g. C++) may have lots of 
operators, e.g:   | ||   = =   ^ % etc. Is there an 
obvious natural order of precedence for all these? I suspect that 
many C++ programmers couldn't put all its operators in the correect 
order.

I speak as one who was partly, and in a minor way, responsible for 
implementing the SmallTalk system on the Perq architecture back in the 
1980's. 

What's Perq?

(Mario Wolczko did the real work). So it's not that I've 

Re: Find day of week from month and year

2005-09-03 Thread Paul McGuire
Donn,

You didn't look closely enough at those results.  The OP's point was
that he did not know how to set all the tuple values correctly.  Here's
a clearer example, I think:

import time
print time.asctime((2005,9,1,0,0,0,0,0,0))
print time.asctime((2005,9,1,0,0,0,1,0,0))
print time.asctime((2005,9,1,0,0,0,2,0,0))
print time.asctime((2005,9,1,0,0,0,3,0,0))

Prints:
Mon Sep 01 00:00:00 2005
Tue Sep 01 00:00:00 2005
Wed Sep 01 00:00:00 2005
Thu Sep 01 00:00:00 2005

No matter what time zone you're in, Sep 1, 2005 can't be all those days
of the week! :)

Your code works because you use mktime, which appears to ignore the
dayOfWeek element of the input tuple, as shown by the following:

print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,0,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,1,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,2,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,3,0,0

Prints:
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005

-- Paul

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


Re: python logo

2005-09-03 Thread Fredrik Lundh
Tim Churches wrote:

 PPS Emerson's assertion might well apply not just to Python logos, but
 also, ahem, to certain aspects of the Python standard library.

you've read the python style guide, I presume?

http://www.python.org/peps/pep-0008.html

/F 



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


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 Program crashes at line Py_Finalize(). Program tries to read some
memory location and suffer run time exception.

PyTuple_SetItem steals a reference, so changing

Py_XDECREF(stringarg);
Py_XDECREF(args);

to just

Py_XDECREF(args);

might fix the problem.

/F 



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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-09-03 Thread Scott David Daniels
Bengt Richter wrote:
 On Wed, 31 Aug 2005 14:16:28 GMT, Ron Adam [EMAIL PROTECTED] wrote:
 [...]
 
The problem with negative index's are that positive index's are zero 
based, but negative index's are 1 based.  Which leads to a non 
symmetrical situations.
Although it is _way_ too late to try something like this, once upon
a time you could have done all of this using the one's complement
operator:
 ~0  does exist and is distinct from 0.
So you could talk about a slice:
 str[4 : ~2]
and so on.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread jepler
I see a couple of problems.  First, because I'm using Unix, where filenames are
case-sensitive, I had to '#include Python.h' instead of '#include
python.h'.

Next, it looks like the behavior that '.' is placed on sys.path isn't done
automatically when embedding.  So I had to set the environment variable
PYTHONPATH=. since Test.py was in the current directory.

Before I did this, I got this output:
Exception exceptions.ImportError: 'No module named Test' in 'garbage
collection' ignored
Fatal Python error: unexpected exception during garbage collection
Aborted
which was a clue about the problem you were running into.  This ImportError was
being caused back at PyImport_Import but was being transmuted into a fatal
error down at Py_Finalize().  By adding 'else { PyErr_Print(); }' to the end of
'if(mod)', I got the error message printed and cleared.  Now, garbage
collection which is kicked off by Py_Finalize() doesn't find the existing error
condition and treat it as a fatal error.

In your code, 'rslt' will be a Python Integer, not a Python Float, so
PyFloat_AsDouble will fail.  You could either write something like
if (rslt)
{   
if(PyFloat_Check(rslt)) {
answer = PyFloat_AsDouble(rslt);
} else {
printf(not a float\n);
answer = 1.0;
}
Py_XDECREF(rslt);
}
instead, or use PyErr_Check() + PyErr_Print() or PyErr_Clear().
If you want to accept integer or float returns, then maybe you want
if(PyFloat_Check(rslt)) { answer = PyFloat_AsDouble(rslt); }
else if(PyInt_Check(rslt)) { answer = PyInt_AsLong(rslt); }
else probably not a numeric type

Jeff


pgpsNcJ3ylwlJ.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Decrypting GPG/PGP email messages

2005-09-03 Thread Alessandro Bottoni
Piet van Oostrum wrote:
 What benefit is there in encrypting the messages? It would only prevent
 people intercepting the message from seeing what's inside, but it won't
 give you any additional protection on the server.

You are right. Bad guys can still try to send garbage to my system and, with
some luck, can mess everything up. After reading your message I decided to
add some more control over what the remote user can do and how he can reach
the server:
- a list of allowed users (based on e-mail identity plus OTP, see below)
- a list of allowed commands (still with root-level ones, I'm afraid)
- chroot for the most dangerous commands, when possible
It is still dangerous but, frankly, I could not do any better.

 And if somebody can intercept the messages there is a much bigger danger:
 They could save the message and replay it later. You can't protect against
 this with encryption (well, with encryption they won't know what they
 are doing). Neither with a digital signature. Only checking timestamps,
 keeping track of the messages received and/or a challenge/response system
 will help in this case.

You are right again. As a consequence, I decided to add a one-time-password
to the encrypted message, in order to be sure of the sender identity and of
the uniqueness of the message (the OTP works as a sequence item identifier,
as well).

I'm going to use my own implementation of OTP because the existing mechanism
are devoted to protect the remote login channel and cannot be easily
adapted to my weird e-mail-based mechanism. Anyway, I'm going to use a
(encrypted) very long pseudo-random alpha-numeric sequence as a OTP so it
should be quite safe.

 If you only sign, it will be sufficient, but there is a more complete one
 (including decryption) in
 http://trac.t7a.org/isconf/file/trunk/lib/python/isconf/GPG.py

Thanks for this info. I'm studying it.

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


pyNMS

2005-09-03 Thread Colin J. Williams
The pyNMS package is available for network management using Linux.

Is there anything similar for Win32?

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


Problems with Python for Windows extensions

2005-09-03 Thread KK
the code below is taken from M$ technet as an example on using vb
script to do a replace all in word:

Const wdReplaceAll  = 2

Set objWord = CreateObject(Word.Application)
objWord.Visible = True

Set objDoc =
objWord.Documents.Open(K:\Development\Fabricbase\prod\Test.doc)
Set objSelection = objWord.Selection

objSelection.Find.Text = Contoso
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = True

objSelection.Find.Replacement.Text = Fabrikam
objSelection.Find.Execute ,,wdReplaceAll




I did a rewrite and made it pythonic:

from win32com.client import *

wdReplaceAll  = 2

objWord = Dispatch(Word.Application)
objWord.Visible = True

objDoc =
objWord.Documents.Open(K:\Development\Fabricbase\prod\Test.doc)
objSelection = objWord.Selection

objSelection.Find.Text = Contoso
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = True

objSelection.Find.Replacement.Text = Fabrikam
objSelection.Find.Execute (Replace = wdReplaceAll)


However, the document juz loaded up in word but no action was taken. I
am using Word 2003. Any ideas?

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


Re: Find day of week from month and year

2005-09-03 Thread Peter Hansen
Paul Rubin wrote:
 Peter Hansen [EMAIL PROTECTED] writes:
 
(And, if I were optimizing, I would of course dispense with the
dynamic creation of the static table upon every execution of
expiration(), and move it outside the function.)
 
 Replacing it with a tuple might be enough for that.

You're right, and in fact that would actually be even faster since then 
it's a LOAD_CONST instead of a LOAD_GLOBAL.

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


Re: using common lisp with python.

2005-09-03 Thread [EMAIL PROTECTED]
Thank you all for the advice, I think I'll be writing my lisp code in
python.

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


Re: How to identify which interface a broadcast packet comes in on?

2005-09-03 Thread Jorgen Grahn
On Sat, 03 Sep 2005 18:46:05 +0800, Lincoln Yeoh [EMAIL PROTECTED] wrote:
 Hi,

 If I have a program listening on 0.0.0.0:(someport) on all interfaces,
 how do I know which network interface a broadcast packet is coming in
 on - assuming Linux and _many_ interfaces. And how do I set which
 interface a frame will leave on, assuming I'm sending a raw frame (no
 IP address, just the ethernet address).

 If I use C, it seems I'm to use the IP_PKTINFO socket options,
 send/recv the ancillary messages and set/check the  ipi_ifindex value.
...
 How would I achieve the same thing in Python? 

Someone may want to correct me, but from what I can see, the socket module
is almost a 1:1 mapping between the socket support your C lib has, and
Python. Plus some compatibility code for Windows.

You should be able to do everything you can do in C. Your code may
become Linux-specific if you're not careful, though.

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find day of week from month and year

2005-09-03 Thread Jorgen Grahn
On Fri, 02 Sep 2005 20:53:44 -0400, Peter Hansen [EMAIL PROTECTED] wrote:
 Carsten Haese wrote:
 On Fri, 2005-09-02 at 16:46, Laguna wrote:
def expiration(year, month):
 weekday = calendar.weekday(year, month, 1)
 table = [19, 18, 17, 16, 15, 21, 20]
 return table[weekday]
...
 True, but do you find that more readable?  If I saw that in code I was 
 maintaining I would likely rewrite it, probably to look a lot like the 
 first one (though likely with a more descriptive name than table... 
 maybe expirationTable?).

That doesn't explain anything, IMHO. What 'table' really is is a list of
day-of-month candidates for the third Friday.

For some pieces of code, I find that it's better to document what it /does/
than to try to document /how/ it does it. And maybe add a bunch of unit
tests to /demonstrate/ that it seems to work.

The next programmer can then choose to either (a) understand the code or (b)
rip it out and replace it.

I would leave the body alone, but rename the function 'third_friday_of_month',
and do 'expiration = third_friday_of_month'.

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extend Python

2005-09-03 Thread Jorgen Grahn
On Thu, 1 Sep 2005 19:09:55 +0200, Filip Dreger [EMAIL PROTECTED] wrote:
 My Question:
 Swig offers some great features but is to basic for us. Is there
 another program that creates more readble code that can be easily
 edited? How much work is it to write our own wrappers?

 Not too much, and practicaly not at all if you want to wrap procedures 
 (not objects or types):
  - marshaslling an argument list from Python to C and from C to Python 
 takes exactly 1 line of code,
  - handling errors takes 2 lines of code (unless you want to do 
 something fancy with them; I mean just catching an exception and 
 getting the error message).
  - entry in the PyMethodDef is one simple line
 Bottomline: you need 5 additional lines of C code per procedure to 
 make it usable from Python.
 Unless you have hundreds of procedures, there is no point in using 
 special tools to do that. Especially if you need full control over the 
 results.

My experience too. At least if you are a C programmer.

If it gets hard, it's because the things you wrap do something funky: take
complex memory structures as arguments, have odd resource management, etc.
A tool cannot help you with that anyway.

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Managing events

2005-09-03 Thread cantabile
Hi,

I have a class (a gui) with buttons and other controls. A button, for 
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.

Now, if I want the OnClick method to call some of my main class methods, 
I need to write:

 UI = None
 ...
 class MainClass:
 ...
 global UI = self


Then,
def OnClik(button):
UI.do_something(button.get_label())

Is this the correct way to do it in Python ? Isn't there a potential 
flaw in declaring my MainClass instance as a global variable ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
Bryan wrote:
 Do you want to be a network engineer?
lol... definetely not! It's just my curiosity.
At my work my tools are: vba, vbs, jet-sql (ms access),
t-sql (ms sql server). The pretty humble set.

 My first two guess are:
 The client is trying to make more than one connection.
 Putting accept in a loop and moving some stuff will support
 that.
BUT your *1st version* does NOT support more than ONE client's
connection! How do I know that? I just ran several (3) instances
of my.vbs (almost) simultaneously and only the first of them could
connect to SQL Server via Python!
Just in case: SQL Server itself can accept up to 32767 clients.

Then (if I'm not wrong here) what's the difference with my own
version? Maybe replacing send() with sendall() will be quite enough
to make it working over LAN? I've NOT tested this!

PS Yes! Your last version works like a champ. It easily handles up
to 5 instances of my.vbs! Except of this thing:
 AttributeError: 'module' object has no attribute 'SHUT_WR'
Seems it's a pure Unix constant.

 But it does NOT work without IDLE!
 Odd. What happens if you run it from a command line?
In a moment - AFTER I start my.vbs - in console window new prompt
D:\ appears... and vbs reports General Network Error.

Dennis;
No no no! It's NOT firewalls trick. It's NOT db permissions issue.
VBS and SQL Server work with each other ABSOLUTELY FINE - from ANY
machine at ANY time at ANY free port - BUT WITHOUT Python being a
mediator for them.

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


Re: Decrypting GPG/PGP email messages

2005-09-03 Thread Paul Rubin
Alessandro Bottoni [EMAIL PROTECTED] writes:
 I'm going to use my own implementation of OTP because the existing
 mechanism are devoted to protect the remote login channel and cannot
 be easily adapted to my weird e-mail-based mechanism. Anyway, I'm
 going to use a (encrypted) very long pseudo-random alpha-numeric
 sequence as a OTP so it should be quite safe.

Be very careful.  You have to really know what you're doing to have
any chance of implementing something like this securely.  See the book
Practical Cryptography by Schneier and Ferguson.  You're much better
off using GPG/PGP if you can.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find

2005-09-03 Thread Ron Adam
Terry Reedy wrote:

b[-1:] = ['Z']# replaces last item
b[-1:-0] = ['Z']  # this doesn't work

If you are using negative index slices, you need to check for end
conditions because you can't address the end of the slice in a
sequential/numerical way.
 
 OK, now I understand your question, the answer 'get a one's complement 
 machine', and your point that without a -0 separate from +0, there is a 
 subtle asymmetry that is easy to overlook.

Yes, I don't thinks it falls in the catagory of bugs,  probably closer 
to a minor wart.

As I posted before (but perhaps it arrived after you sent this), one 
number
indexing rounds down, introducing a slight asymmetry.

I didn't see that one,
 
 Perhaps you did not see my other long post, where I drew ascii pictures?

Yes, I saw it.  I think we are expressing the same things in different ways.


 In the US (and UK?), the ground level floor of a multifloor building is the 
 first floor.  In continental Europe (all or just some?), the ground floor 
 is the ground (effectively zeroth) floor while the first floor up is the 
 first stage (resting place on the stairway).

In the VA Hospital here in Tampa, the ground floor in the front elevator 
is on the same level as the lobby, while the ground floor in the 
elevator on the other side of the building is on the floor below. ;-)


I don't think people would miss negative strides much if they were
removed. Replacing these case's with reverse() methods shouldn't be that
difficult.
 
 Yes, the introduction of reversed partly obsoleted the use of negative 
 strides, at least outside of its numerical array origin.
 
 Terry J. Reedy



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


Re: 'isa' keyword

2005-09-03 Thread Steve Holden
phil hunt wrote:
 On Sat, 03 Sep 2005 00:45:19 -0500, Steve Holden [EMAIL PROTECTED] wrote:
 
I'm not talking about a change in *paradigm* merely a change in 
*syntax*; this:

   receiver selector argument

would mean the same as the current Python:

   receiver.selector(argument)


Aah, I see. I had assumed that selector was always going to be an 
operator. 3 . (+ 4) does indeed seem very SmallTalkative. I don't 
think that Python method (or attribute) selection bears any relationship 
to SmallTalk message-passing, but I hope you will feel free to enlighten me.
 
 
 Let's consider the Python example first.
 
 You have two classes A and B. Each has a method called 'selector'.
 
 When the line of code above is executed, the Python virtual machine 
 decides whether (receiver) is a member of A or B, and then executed 
 one of A.selector() or B.selector() depending on which it is. 
 Whichever function is executed, it is passed with (reciever) as the 
 self argument so that the correct data is operated on.
 
 And now let's consider the Smalltalk example. How does it do it? 
 Essentially it does *exactly the same thing*.
 
 (Yes, I know there are many differneces in detail between how 
 Snalltalk and Python  work, but they are only *details*; the 
 fundamental idea governing how these two object-oriented languages 
 work is the same).
 
It's the differences we are talking about. All you have said above is 
that Python and SmallTalk both use late-binding to resolve names, 
allowing them to implement polymorphic behavior.

 
would necessarily 
benefit Python at this stage. Some people are still under the 
misapprehension that message-passing is a fundamental of object-oriented 
programming because of Smalltalk, but they are wrong.


I don't see how it can reasonably said that STK has 
message-passing but other OOPLs don't. Consider these code 
fragments:

Smalltalk:
   receiver selector: argument

C++ or Java:
   receiver.selector(argument);

Python:
   receiver.selector(argument)

PHP:
   $receiver-selector($argument)

(I'm not sure if the last one is right since I've not done much OO 
stuff in PHP)

These all mean essentially the same thing so how can one be message 
passing and the others not?

Sorry, they don't all mean essentially the same thing at all. It seems 
to me you are looking at SmallTalk in entirely too superficial a light. 
 
 
 OK, allow me to reprase it. Imagine a language ith the semantics of 
 Python but the syntax of C++ or PHP or Smalltalk (or Lisp for that 
 matter). It would still basically be Python, wouldn't it?
 
I'm not sure I understand this. You appear to be saying, in essence, 
they are all programming languages, so despite the fact that they work 
slightly differently the similarity is we can write programs in them all.

 
 In SmallTalk, control structures aren't syntactic primitives, they are 
also examples of message-passing, so code blocks are sent as messages to 
objects. Python eschews such obscurity and (IMHO) gains clarity by so 
doing. But that is, of course, a matter of opinion.
 
 
 I agree, that's a major point of departure between Python and 
 Smalltalk.
 
Right, but it's precisely SmallTalk's message-passing techniques that 
allow this to work. Of course Python can create code blocks with 
compiler.compile(), but this is not mainstream, and Python has so many 
more-useful mechanisms to implement program control that using code 
objects as data is correctly regarded as being ion the boundaries of 
language voodoo.

 
Also, remember that just because two expressions in different languages 
mean the same thing doesn't mean they are implemented using the same 
techniques.
 
 
 Of course not. 
 
 CPython and JPython are different implementations, but they are 
 still the same language (mostly).
 
That we can agree on. But both differ substantially from SmallTalk.
 
I would contend (if backed into a corner) that there is a significant 
difference between passing the arguments 3 and 4 to a + operator 
(which is what Python and most other languages implementing standard 
ideas of operator precedence do) and sending the message + 4 to the 
integer 3 (which is effectively what SmallTalk does).
 
 
 In both python and smalltalk you can override the operator to mean 
 what you want, so I disagree that there is any fundamental 
 difference. Why do you think there is?
 
Because in Python the interpreter has hard-wired code associated with 
each operator. This code examines the left- and right-hand operands, 
calling various methods on them if they exist.

In SmallTalk the operator is the first element of a message sent to the 
left-hand operand, and if the object (or one of its superclasses) has no 
method corresponding with the operator then a don't understand 
operator exception is raised.

In other words, the differences aren't purely syntactic.
 
Of course, I realise that you can argue that the two are equivalent in 
the sense that they perform the same computation. But 

Re: pickling the objects returned by array.array()

2005-09-03 Thread Reinhold Birkenfeld
Raymond Hettinger wrote:
 John Machin wrote:
 Looks like arrays are NOW (2.4.1) pickleable but not unpickleable
 
 Please file a bug report and assign to me.

Done. http://python.org/sf/1281383

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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Bryan Olson
n00m wrote:
  Your last version works like a champ. It easily handles up
  to 5 instances of my.vbs! Except of this thing:
 
 AttributeError: 'module' object has no attribute 'SHUT_WR'
 
  Seems it's a pure Unix constant.

No, my guess is that you're running an old version of Python.
The constant was added in the source on 27 Nov 2003; I'm not
sure what version that would first appear in. You can fix it
either by upgrading your Python distribution (a good idea
anyway), or replacing:

 sock.shutdown(socket.SHUT_WR)

with:

 sock.shutdown(1)


 But it does NOT work without IDLE!
 
 Odd. What happens if you run it from a command line?
 
  In a moment - AFTER I start my.vbs - in console window new prompt
  D:\ appears... and vbs reports General Network Error.

Hmmm... not much to go on there. I tested it on Win-XP, running
it from a command line. I set the server to ('www.googl.com',
80), and I was able to web-search through it.

Are you running XP's local firewall?


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-09-03 Thread Ron Adam
Bengt Richter wrote:

 IMO the problem is that the index sign is doing two jobs, which for zero-based
 reverse indexing have to be separate: i.e., to show direction _and_ a _signed_
 offset which needs to be realtive to the direction and base position.

Yes, that's definitely part of it.


 A list-like class, and an option to use a zero-based reverse index will 
 illustrate:
 
class Zbrx(object):
 
  ... def __init__(self, value=0):
  ... self.value = value
  ... def __repr__(self): return 'Zbrx(%r)'%self.value
  ... def __sub__(self, other): return Zbrx(self.value - other)
  ... def __add__(self, other): return Zbrx(self.value + other)
  ...
   class Zbrxlist(object):
  ... def normslc(self, slc):
  ... sss = [slc.start, slc.stop, slc.step]
  ... for i,s in enumerate(sss):
  ... if isinstance(s, Zbrx): sss[i] = len(self.value)-1-s.value
  ... return tuple(sss), slice(*sss)
  ... def __init__(self, value):
  ... self.value = value
  ... def __getitem__(self, i):
  ... if isinstance(i, int):
  ... return '[%r]: %r'%(i, self.value[i])
  ... elif isinstance(i, Zbrx):
  ... return '[%r]: %r'%(i, self.value[len(self.value)-1-i.value])
  ... elif isinstance(i, slice):
  ... sss, slc = self.normslc(i)
  ... return '[%r:%r:%r]: %r'%(sss+ (list.__getitem__(self.value, 
 slc),))
  ... def __setitem__(self, i, v):
  ... if isinstance(i, int):
  ... list.__setitem__(self, i, v)
  ... elif isinstance(i, slice):
  ... sss, slc = self.normslc(i)
  ... list.__setitem__(self.value, slc, v)
  ... def __repr__(self): return 'Zbrxlist(%r)'%self.value
  ...
   zlast = Zbrx(0)
   zbr10 = Zbrxlist(range(10))
   zbr10[zlast]
  '[Zbrx(0)]: 9'
   zbr10[zlast:]
  '[9:None:None]: [9]'
   zbr10[zlast:zlast] = ['end']
   zbr10
  Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9])
   ztop = Zbrx(-1)
   zbr10[ztop:ztop] = ['final']
   zbr10
  Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9, 'final'])
   zbr10[zlast:]
  [11:None:None]: ['final']
   zbr10[zlast]
  [Zbrx(0)]: 'final'
   zbr10[zlast+1]
  '[Zbrx(1)]: 9'
   zbr10[zlast+2]
  [Zbrx(2)]: 'end'
 
   a = Zbrxlist(list('abcde'))
   a
  Zbrxlist(['a', 'b', 'c', 'd', 'e'])
 
 Forgot to provide a __len__ method ;-)
   a[len(a.value):len(a.value)] = ['end']
   a
  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'end'])
 
 lastx refers to the last items by zero-based reverse indexing
   a[lastx]
  [Zbrx(0)]: 'end'
   a[lastx:lastx] = ['last']
   a
  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end'])
 
 As expected, or do you want to define different semantics?
 You still need to spell len(a) in the slice somehow to indicate
 beond the top. E.g.,
 
   a[lastx-1:lastx-1] = ['final']
   a
  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end', 'final'])
 
 Perhaps you can take the above toy and make something that works
 they way you had in mind? Nothing like implementation to give
 your ideas reality ;-)

Thanks, I'll play around with it.  ;-)

As you stated before the index is doing two jobs, so limiting it in some 
way may be what is needed.  Here's a few possible (or impossible) options.

(Some of these aren't pretty.)


* Disallow *all* negative values, use values of start/stop to determine 
direction. Indexing from far end needs to be explicit (len(n)-x).

a[len(a):0]reverse order
a[len(a):0:2]  reveres order, even items

(I was wondering why list's couldn't have len,min, and max attribute 
that are updated when ever the list is modified in place of using 
len,min, and max functions? Would the overhead be that much?)

   a[len.a:0]


* Disallow negative index's,  use negative steps to determine indexing 
direction. Order of index's to determine output order.

a[len(a):0:-1] forward order, zero based indexing from end.
a[0:len(a):-1] reverse order, zero based from end.
a[0:1:-1]  last item

I works, but single a[-1] is used extremely often.  I don't think having 
to do a[0:1:-1] would be very popular.


* A reverse index symbol/operator could be used ...

a[~0]  -   last item,  This works BTW. :-)  ~0 == -1
a[~1]  -   next to last item

(Could this be related to the original intended use?)


a[~0:~0]   slice after end ?.  Doesn't work correctly.

What is needed here is to index from the left instead of the right.

a[~0] - item to left of end gap.

*IF* this could be done; I'm sure there's some reason why this won't 
work. ;-), then all indexing operations with '~' could be symmetric with 
all positive indexing operations. Then in Python 3k true negative 
index's could cause an exception... less bugs I bet.  And then negative 
steps could reverse lists with a lot less confusion, keeping that 
functionality as well.

Maybe a[~:~] == a[-len(a):-0]
   a[~:]  == a[-len(a):len(a)]
   a[:~]  == a[0:-0]

   a[~:~] == a[:]

This 

Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Peter Hansen
n00m wrote:
 Bryan wrote:
 PS Yes! Your last version works like a champ. It easily handles up
 to 5 instances of my.vbs! Except of this thing:
 
AttributeError: 'module' object has no attribute 'SHUT_WR'
 
 Seems it's a pure Unix constant.

Definitely not.  Are you sure you've got a proper Python install?

c:\python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
  import socket
  dir(socket)
['AF_APPLETALK', 'AF_DECnet', ... 'SHUT_RD', 'SHUT_RDWR', 'SHUT_WR',
'SOCK_DGRAM', ... 'sys', 'timeout']

  socket.SHUT_WR
1

If you're really getting this error it would seem something is very 
wrong on your machine.

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


Re: plotting with gnuplot.py

2005-09-03 Thread [EMAIL PROTECTED]
Thanks for the response Varun,

I guess I still not sure the distingtion betweein gnuplot.py and its
implentation in scipy.

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,wasRe: Bug in slice type

2005-09-03 Thread Terry Reedy

Ron Adam [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 (I was wondering why list's couldn't have len,min, and max attribute
 that are updated when ever the list is modified in place of using
 len,min, and max functions?

Python's list and, I believe, other builtin roster objects do have a 
C-level length attribute.  For mutables, it is updated.  __len__ is just a 
get of int value the and conversion to int object.  Min and max are defined 
and sensible for only a subset of lists, and when they are, are very seldom 
need repeated updates.

 Would the overhead be that much?)

For the fraction of times used, yes.

Terry J. Reedy



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


Re: Managing events

2005-09-03 Thread Steve Holden
cantabile wrote:
 Hi,
 
 I have a class (a gui) with buttons and other controls. A button, for 
 example, has a callback method, so that writing
 
 b = Button(label, OnClick)
 
 will call the global OnClick method.
 
 Now, if I want the OnClick method to call some of my main class methods, 
 I need to write:
 
  UI = None
  ...
  class MainClass:
  ...
  global UI = self
 
 
 Then,
 def OnClik(button):
 UI.do_something(button.get_label())
 
 Is this the correct way to do it in Python ? Isn't there a potential 
 flaw in declaring my MainClass instance as a global variable ?

Yes. Normally graphical widgets are declared as object classes (in both 
wxPython and Tkinter, at least) for precisely this reason.

Then the onClick() can be a method of the class, and the callback is a 
bound method of the class (in other words a method that's already 
identified with a specific instance).

Here's a simple-ish piece of wxPython code to demonstrate. Notice that 
each paramDialog closes its own dialog box, because the callback 
provided in the event binding is already bound to the instance.

import wx

class paramDialog(wx.Dialog):
 count = 0  # Class variable counts # of instances
 def __init__(self, parent):
 wx.Dialog.__init__(self, parent, id=-1, title=This is a 
Dialog, size=(300, 250))
 btn = wx.Button(self, -1, Close Me, (100, 75))
 # THIS LINE ASSOCIATES A BOUND METHOD OF THE CURRENT
 # INSTANCE WITH A CLICK ON THE Close Me BUTTON OF
 # THIS PARTICULAR DIALOG INSTANCE
 btn.Bind(wx.EVT_BUTTON, self.shutdown)
 self.Bind(wx.EVT_CLOSE, self.shutdown)
 self.SetAutoLayout(True)
 paramDialog.count += 1

 def shutdown(self, evt):
 paramDialog.count -= 1
 self.Destroy()
 if paramDialog.count == 0:
 app.Destroy()
 import sys
 sys.exit(Done)


class MyApp(wx.App):
 # wxWidgets calls this method to initialize the application
 def OnInit(self):
 frame = wx.Frame(None, -1, This is the main frame)
 self.SetTopWindow(frame)
 d1 = paramDialog(frame)
 d2 = paramDialog(frame)
 d3 = paramDialog(frame)
 d1.Show()
 d2.Show()
 d3.Show()
 return True

if __name__ == '__main__':
 app = MyApp(0)
 app.MainLoop()



regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Managing events

2005-09-03 Thread Rob Williscroft
cantabile wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Hi,
 
 I have a class (a gui) with buttons and other controls. A button, for 
 example, has a callback method, so that writing
 
 b = Button(label, OnClick)
 
 will call the global OnClick method.
 
 Now, if I want the OnClick method to call some of my main class 
 methods, 
 I need to write:
 
  UI = None
  ...
  class MainClass:
  ...
  global UI = self
 
 
 Then,
 def OnClik(button):
 UI.do_something(button.get_label())
 
 Is this the correct way to do it in Python ? 

Try:

class MainClass:
  def do_something( self, label ):
pass

  def OnClick( self, button ):
self.do_something( button.get_label() )

  def some_method( self ):
b = Button( label, self.OnClick )


With the above you could also do:

main = MainClass()
b = Button( A Label, main.OnClick )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Submitting doc bug reports without SF registration

2005-09-03 Thread Terry Reedy
In response to posts about the overhead of registering as SourceForge to 
submit quick doc typo/bug reports, I sent an email to docs AT python.org 
(== Fred Drake) about submitting via that address instead.

He responded that he really does not want specific action items sent there 
because such email only goes to him and can get lost or not read for 
awhile.  Tracker reports, on the other hand, give immediate feedback of 
reception and are immediately readable and possibly acted on by anyone who 
reviews tracker items.  Indeed, fixes sometimes happen within a day or two.

On the other hand, he can see that registration could be just enough 
barrier to stop someone and does not want that either.  He knows that the 
docs 'need more attention and fresh eyes!'  So he suggested two 
possibilities:

1. A DocImprovement wiki.  People could optionally sign up for update 
reports on specific wiki pages.

2. A new SF tracker, only for doc bugs, that would accept anonymous 
submissions.  The other trackers require login because most items need 
additional feedback from requestors.  But reports like On page x.y.x, 
'seperate' should be 'separate' do not require feedback unless the 
requestor wants the 'fixed, thank you' comment emailed.

As an item reviewer, I prefer the second, but we are both curious as to the 
preference of potential no-login reporters.

Terry J. Reedy



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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
1.
Python 2.3.4

2.
Win98 and Win2k Professional

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


ANN: PyInstaller 1.0 in the works: package your Python app into a single-file executable

2005-09-03 Thread Giovanni Bajo
Hello,

http://pyinstaller.hpcf.upr.edu/

PyInstaller is a program that packages Python programs into stand-alone
executables, under both Windows and Linux. This is similar to the famous
py2exe, but PyInstaller is also able to build fully-contained (single file)
executables, while py2exe can only build directories containing an executable
with multiple dynamic libraries.
PyInstaller is an effort to rescue, maintain and further develop Gordon
McMillan's Python Installer (now PyInstaller). Their official website is not
longer available and the original package is not longer maintained. Believing
that it is still far superior to py2exe we have setup this page to continue its
further development.

We have just begun development on PyInstaller. Feel free to join us in the
effort! Please consult our Roadmap
(http://pyinstaller.hpcf.upr.edu/pyinstaller/roadmap) to check our plans.

-- 
Giovanni Bajo



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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Bryan Olson
Dennis Lee Bieber wrote:
 Bryan Olson declaimed the following in comp.lang.python:
 
No, my guess is that you're running an old version of Python.
The constant was added in the source on 27 Nov 2003; I'm not
 
 
   Are you sure of that 2003?

Yes, but that's when it went into the source, in the sense of
first being edited into a file. It was Revision 1.279 of
socketmodule.c.

http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/socketmodule.c?rev=1.312view=log


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


descriptors for container items

2005-09-03 Thread Brock Filer
 I personally would first try to dump the quotes and use standard
 attributes --  countries.us.Colorado... -- and the  __get/set/delattr__
 methods.

If I do that, the attributes (that was a stupid name for me to choose) 
and children would have to not share any names with each other, with 
the object's regular attrs, or python keywords.

I toyed with the idea of having __div__ create a descriptor, assign it 
to a temporary attr, and access that. But then I realized that the 
children should never be directly assigned to anyways. I can live with 
one set of brackets at the end of the expression.

__methods__ are delightfully evil :-)

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


Re: PyChecker lives, version 0.8.15 released

2005-09-03 Thread Al Christians
Neal Norwitz wrote:
 Special thanks to Ken Pronovici.  He did a lot of work for this
 release and helped ensure it occurred.
 
 Version 0.8.15 of PyChecker is available.  It's been over a year since
 the last release.  Wow, time really does fly.  Since it's been so long
 I'm sure I screwed something up, treat it delicately.  It may have bugs
 and erase your hard drive.  If that happens, look on the bright side, 
 you won't have any more bugs. :-)
 
 PyChecker is a tool for finding bugs in Python source code.
 It finds problems that are typically caught by a compiler for less
 dynamic languages, like C and C++.  It is similar to lint.
 
 Comments, criticisms, new ideas, and other feedback is welcome.
 
 Since I expect there may be a bit more bugs than normal, I will try to
 put out another release in a few weeks.  Please file bug reports
 including problems with installation, false positives, c on Source Forge.
 You are welcome to use the mailling list to discuss anything pychecker 
 related, including ideas for new checks.
 
 Changes from 0.8.14 to 0.8.15:
 
   * Fix spurious warning about catching string exceptions
   * Don't barf if there is # -*- encoding: ... -*- lines and unicode strings
   * setup.py was rewritten to honor --root, --home, etc options
   * Fix internal error on processing nested scopes
   * Fix constant tuples in Python 2.4
   * Don't warn about implicit/explicit returns in Python 2.4, we can't tell
   * Fix crash when __slots__ was an instance w/o __len__
   * Fix bug that declared {}.pop to only take one argument, it takes 1 or 2
   * Fix spurious warning when using tuples for exceptions
   * Fix spurious warning stack / stack 
   * Fix spurious warnings for sets module about __cmp__, __hash__
   * Changed abstract check to require raising NotImplementedError
 rather than raising any error
   * Fix spurious warnings in Python 2.4 for Using is (not) None warnings
   * Fix spurious warnings for some instances of No class attribute found
   * Fix spurious warnings for implicit returns when using nested functions
 
 PyChecker is available on Source Forge:
 Web page:   http://pychecker.sourceforge.net/
 Project page:   http://sourceforge.net/projects/pychecker/
 Mailing List:   [EMAIL PROTECTED]
 
 Neal
 --
 [EMAIL PROTECTED]

Not to complain, as this is a very useful one-of-a-kind tool, but it 
does appear to use more memory than I can imagine how when you run it on 
a substantial program.  Like a few kilobytes per line of code, maybe. 
It's slow, too, but that's ok for the usefulness of it, but trying to 
let it run and do something else with someone else's code bloat (like MS 
Word or something) in another window leads to something 
indistinguishable from system meltdown.  Any reason for hope of future 
improvements in this regard?


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


Digest MD5 authentication over using ZSI

2005-09-03 Thread trapeze . jsg
Hi.

I am trying to get through to Microsoft MapPoint Services using ZSI for
soap handling. I can generate the service classes and also the
soap-requests generated by the service classes seem to be OK. The
problem I am facing is that I can't seem to authenticate myself. I have
made a small change to ZSI.client so that when I get a 401
Unauthorized response from the remote server I build up a nice
authorization request:

POST /Find-30/FindService.asmx HTTP/1.1
Host: findv3.staging.mappoint.net
Accept-Encoding: identity
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client
Protocol 1.1.4322.573)
SOAPAction: http://s.mappoint.net/mappoint-30/FindAddress;
Authorization: Digest username=106288, realm=MapPoint,
nonce=91168da8e3a097f41264875211009a194b99a94ffe5bc619415820880a5b,
uri=/Find-30/FindService.asmx,
response=26aa9e36f9ff2a8308030810ab83dad1, qop=auth, nc=0001,
cnonce=623c12f33f0eb883
Content-length: 0
Expect: 100-continue


The problem is that the server won't authorize me. I have a C# .net
program that does exactly the same I'm trying in python, and it is
authorized nicely:

POST /Find-30/FindService.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client
Protocol 1.1.4322.573)
Content-Type: text/xml; charset=utf-8
SOAPAction: http://s.mappoint.net/mappoint-30/FindAddress;
Authorization: Digest
username=106288,realm=MapPoint,nonce=487911f02ed2ef706326675211008a8ec39cfa4fb09304757c8dde417354,uri=/Find-30/FindService.asmx,cnonce=e1ed9880c5e3777a4ba280cec1c9e362,nc=0001,qop=auth,response=b4119a4db73814fd09ae5fec11fc9730
Content-Length: 523
Expect: 100-continue
Host: findv3.staging.mappoint.net

So I guess the problem is in the Digest calculation. Unfortunately I
don't know much about the issue but I have managed to steel this from
urllib2 and changed it a bit to fit my usage (see below).

1. Can I do this another way?
2. Has anybody made a digest MD5 authenticator for ZSI?
3. Whats wrong with my calculation or is it the header??
4. Can I use urllib2 to test the authentication part of a Soap Service.

- My authentication calculator 

import md5
import sha
import re
import time
import random
import os.path


def randombytes(n):
Return n random bytes.
# Use /dev/urandom if it is available.  Fall back to random module
# if not.  It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists(/dev/urandom):
f = open(/dev/urandom)
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return .join(L)


class Challenge:
  def __init__(self,challenge):
self.params = {}
self.no_chal=0
if challenge.upper().find('WWW-Authenticate:'.upper())==-1:
  self.no_chal=1
rx =
re.compile('WWW-Authenticate:.*qop=(\w+)',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['qop'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*realm=(\w+)',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['realm'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*algorithm=(\w+)',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['algorithm'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*nonce=(\w+)',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['nonce'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*opaque=(\w+)',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['opaque'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*Digest.*',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['Digest'] = 1


  def get(self,keyword,default=None):
if self.params.has_key(keyword):
  return self.params[keyword]
else:
  return default

  def no_challenge(self):
return self.no_chal


class AbstractDigestAuthHandler:
# Digest authentication is specified in RFC 2617.

# XXX The client does not inspect the Authentication-Info header
# in a successful response.

# XXX It should be possible to test this implementation against
# a mock server that just generates a static set of challenges.

# XXX qop=auth-int supports is shaky

def __init__(self, user, passwd):
self.user = user
self.passwd = passwd
self.retried = 0
self.nonce_count = 0

def reset_retry_count(self):
self.retried = 0

def retry_http_digest_auth(self, req, auth):
token, challenge = auth.split(' ', 1)
chal = parse_keqv_list(parse_http_list(challenge))
auth = self.get_authorization(req, chal)
if auth:
auth_val = 'Digest %s' % auth
if req.headers.get(self.auth_header, None) == auth_val:
return None

Re: python logo

2005-09-03 Thread Tim Churches
Fredrik Lundh wrote:
 Tim Churches wrote:
 
 
PPS Emerson's assertion might well apply not just to Python logos, but
also, ahem, to certain aspects of the Python standard library.
 
 
 you've read the python style guide, I presume?
 
 http://www.python.org/peps/pep-0008.html

A Foolish Consistency is the Hobgoblin of Little Minds.
 --often ascribed to Ralph Waldo Emerson but
   in fact due to[1] G. van Rossum and B Warsaw.

[1] The convention that quotes are ascribed to those who first used them
is, of course, a foolish consistency.

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


Language Work Benches in Py

2005-09-03 Thread yoda
Hi,
I recently read Martin Fowler's article on language workbenches and
domain specific
languages(http://www.martinfowler.com/articles/languageWorkbench.html).
I then had the pleasure of reading Rainer Jowsig's implementation of
the sample in Lisp(http://lispm.dyndns.org/news?ID=NEWS-2005-07-08-1).

The lisp code was so sexy that I was inspired to write a sample in
Python. I'm relatively new to coding in Python so I'd love any barbs,
comments or criticisms about the code. You can find my article here :
(http://billionairebusinessman.blogspot.com/2005/09/drop-that-schema-and-put-your-hands-in.html).

I also made a screen cast of the same
(http://openenterpriseafrica.com/neo/blogs/010905/dsl-in-python.wmv.bz2).
Unfortunately, I had to make it using a windows machine so it's encoded
as wmv. (If anyone finds it useful and is inspired to encode it in a
more palatable format e.g. mov, I'd be honoured to create a torrent and
host it)

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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
Bryan;
Look at how I corrected your the very first version
(see added arguments in both functions). And now it
really can handle multiple connections!


import socket, thread

sqls_host, sqls_port = '127.0.0.1', 1433
proxy_host, proxy_port = '127.0.0.1', 1434

# How I tested it:
# sqls_host, sqls_port = 'www.google.com', 80

def VB_SCRIPT(s2, cn):
 while 1:
 data = cn.recv(4096)
 if not data: return
 s2.sendall(data)
 print 'VB_SCRIPT:' + data + '\n'

def SQL_SERVER(s2, cn):
 while 1:
 data = s2.recv(4096)
 if not data: return
 cn.sendall(data)
 print 'SQL_SERVER:' + data + '\n'

s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind((proxy_host, proxy_port))
s1.listen(5)

while 1:
 cn, addr = s1.accept()
 s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s2.connect((sqls_host, sqls_port))
 thread.start_new_thread(VB_SCRIPT,(s2, cn))
 thread.start_new_thread(SQL_SERVER,(s2, cn))


Without these corrections I got these error messages
when I launched SIMULTANEOUSLY 3 instances of my.vbs:


Unhandled exception in thread started by
Unhandled exception in thread started by
Traceback (most recent call last):
Traceback (most recent call last):
  File D:\Python23\00\socket_Br10.py, line 18, in SQL_SERVER
  File D:\Python23\00\socket_Br10.py, line 13, in VB_SCRIPT
data = s2.recv(4096)
s2.sendall(data)
socket  File string, line 1, in sendall
.socketerror.: error: (10054, 'Connection reset by peer')
(10054, 'Connection reset by peer')

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


Re: descriptors for container items

2005-09-03 Thread Terry Reedy

Brock Filer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 I personally would first try to dump the quotes and use standard
 attributes --  countries.us.Colorado... -- and the  __get/set/delattr__
 methods.

 If I do that, the attributes (that was a stupid name for me to choose)
 and children would have to not share any names with each other,

Since multiple objects can indeed have duplicate attribute names, and such 
duplication is rampant in Python, I am not sure what you mean.

Terry J. Reedy 



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


Re: plotting with gnuplot.py

2005-09-03 Thread [EMAIL PROTECTED]
Still having some issues plotting:

In attempting as explained above:

import Gnuplot,Numeric
filename = ('Default.PL1')
data = scipy.io.array_import.read_array(filename)

y = data[:,1]
x = data[:,0]
z = data[:,2]

//I think u need to take the transpose of this column before
plotting..

x=Numeric.transpose(x)
y=Numeric.transpose(y)

g=Gnuplot.Gnuplot(debug=1)
d=Gnuplot.Data(x,y)
g('set logscale xy')
g.plot(d)

The file executes without generating any plot being displayed however
the debug option generates this output:

gnuplot set terminal windows
.
.
gnuplot plot 'c:\documen~1\leon\loca`l\temp\tmpuskt1' notitle

When I open this file in wordpad it contains the contents of the d
array.

Any ideas why gnuplot is not outputing to the screen??

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


os.system(rls) prints to screen??

2005-09-03 Thread Xah Lee
does anyone know why the folllowing prints to the screen?

# python
import os
os.system(rls)

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Add lists to class?

2005-09-03 Thread Mike Meyer
BBands [EMAIL PROTECTED] writes:

 Why don't you use a real list instead?

 I am using lists... I just showed the naming schema. Here is how they
 are implemented.

 for var in range(len(self.symbols)):
 setattr(self, _ + str(var), [])

That's not the list he's talking about. And I agree with him.

Why are you setting the attreibutes _ + str(var)? Why not just store
them in a dictionary?

 I don't understand what
 self.__dict__[_ + str(var)] gets you.
 It let's me access lists that aren't known at write time.

Yes, but it's ugly, makes one address space server for two different
sets of variables, and has potential for some nasty bugs. Why not just
do:

self.lists[var] = []

Or, if you're really tied to _, do:

self._[var] = []

Or, given that your example used increasing numeric names, just use a
list here:

 self._.append([])

which you would then reference as self._[0], self._[1], etc.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: Add lists to class?

2005-09-03 Thread Mike Meyer
Paolino [EMAIL PROTECTED] writes:
 Mike Meyer wrote:
 BBands [EMAIL PROTECTED] writes:
I have a list with some strings in in it, 'one', 'two' 'three' and so
on. I would like to add lists to a class with those names. I have no
way of knowing what will be in the list or how long the list will be in
advance.
 Others have told you how to do it. Now I'm going to tell you why you
 shouldn't.
 First, since you don't know the names of the attributes you added,
 you
 can't possibly write code that references them in the normal way. So
 is there really much point in making them an attribute at all?
 Second, since you don't know the names of the attributes you added,
 you don't know if one of more of them is going to clobber a feafure of
 the class that you want to use for something else. I.e., consider:

class C:
 ...  pass
 ...
c = C()
print c
 __main__.C instance at 0x8270b4c

c.__str__ = 'foo'
print c
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: 'str' object is not callable
 I.e. - if someone adds a __str__ attribute to your class, you won't
 be
 able to print it any more. Not a good thing.
 In general, you probably want a dictionary instead of attributes:

class C(dict):
 ...  def __init__(self, l):
 ...   for i in l:
 ...self[i] = []
 ...
c = C(['a', 'b', 'c'])
c['a']
 []

 and 2c more to use attributes but prevent overriding of real attributes

 def __getattr__(self,name):
   if name in self:
 return self[name]
   raise AttributeError

Good point. The problem with this is that your real attributes will
now hide things stored in the dictionary. The bugs I listed above are
all caused by trying to conflate two different name spaces: the
attributes of the object and the variables stored in it as
data. Separating them out and then layering one back on top of the
other just gives you those bugs back.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: os.system(rls) prints to screen??

2005-09-03 Thread Robert Kern
Xah Lee wrote:
 does anyone know why the folllowing prints to the screen?
 
 # python
 import os
 os.system(rls)

os.system() starts a shell and has the shell execute the program as a
separate process. If you want to get the output of the given program,
then use the subprocess module.

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


Command config, quitting, binary, Timer

2005-09-03 Thread bearophileHUGS
Hello, I have four things to ask or to suggest, sorry if they seem
basic or already discussed.

---

I am still ignorant about Tkinter. This little program, after pressing
the Go eats more and more RAM, is it normal? Can it be avoided? (In
normal programs this is isn't a real problem).

! import Tkinter
! def dogo():
! while 1:
! b.config(command=lambda:None)
! root = Tkinter.Tk()
! b = Tkinter.Button(root, text=Go, command=dogo)
! b.pack()
! root.mainloop()

Note: I have found this problem because in a small program I have a
Start button that becomes a Stop, so the bound command must change each
time. (Maybe there is some other solution, like hiding/unhiding the
buttons, I don't know.)

---

When I quit a Tkinter program (clicking the [X] button of the window)
while it's running, it stops with something like this:

TclError: invalid command name .9970192

There is a way to avoid it, or to intercept that quitting command to
stop the program more gracefully?

---

When I have to convert numbers to binary I use something like this (the
management of negative numbers is removed). It's my faster Python
version (derived by a Hettinger's version):

! from collections import deque
! def binary_conv(n):
! if n == 0:
! return 0
! else:
! absn = abs(n)
! conv = [0, 1]
! result = deque()
! _app = result.appendleft
! while absn:
! _app( conv[absn  1] )
! absn = 1
! return int(.join(result))

But converting to binary is a quite common operation, so I think it can
be added as a binary function to Python, for example adding b to the
the conversion types of the % formatting.

---

Sometimes I need something like the Timer of Java, it generates ticks
and calls a function for each tick. The tick frequency can be set, or
they can be stopped.

In another Newsgroup someone has suggested me that the callLater of
Twisted can solve my problem, but I think it's a quite common thing, so
I think that maybe it can be added to the threading standard module.

This is a rough Python version of mine (without comments), it's not a
true Metronome because it counts the delay time after the end of the
last function call. This class also seems fragile, sometimes it gives
me problems, and I cannot use too much concurrent metronomes, etc. It's
quite

Maybe someone can suggest me how to improve it.


! from threading import Timer
!
! class Metronome(object):
! def __init__(self, interval, fun, *args, **kwargs):
! self.interval = interval # seconds.
! self.fun = fun
! self.args = args
! self.kwargs = kwargs
! self._running = False
! def _go(self):
! # Call the function with the stored values
! self.fun(*self.args, **self.kwargs)
! if self._running:
! self._call = Timer(self.interval, self._go)
! self._call.start()
! def start(self):
! if not self._running:
! self._running = True
! self._go()
! def stop(self):
! if self._running:
! self._call.cancel()
! self._running = False

Thank you,
bearophile

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


Re: global interpreter lock

2005-09-03 Thread Mike Meyer
Dennis Lee Bieber [EMAIL PROTECTED] writes:
 On Wed, 31 Aug 2005 22:44:06 -0400, Mike Meyer [EMAIL PROTECTED] declaimed
 the following in comp.lang.python:
 I don't know what Ada offers. Java gives you pseudo-monitors. I'm

   From the days of mil-std 1815, Ada has supported tasks which
 communicate via rendezvous... The receiving task waits on an accept
 statement (simplified -- there is a means to wait on multiple different
 accepts, and/or time-out). The sending task calls the entry (looks
 like a regular procedure call with in and/or out parameters -- matches
 the signature of the waiting accept). As with accept, there are
 selective entry calls, wherein which ever task is waiting on the
 matching accept will be invoked. During the rendezvous, the sending
 task blocks until the receiving task exits the accept block -- at
 which point both tasks may proceed concurrently.

Thank you for providing the description. That was sufficient context
that Google found the GNAT documentation, which was very detailed.

Based on that, it seems that entry/accept are just a synchronization
construct - with some RPC semantics thrown in.

   As you might notice -- data can go both ways: in at the top of the
 rendezvous, and out at the end.

   Tasks are created by declaring them (there are also task types, so
 one can easily create a slew of identical tasks). 

 procedure xyz is

   a : task;   -- not real Ada, again, simplified
   b : task;

 begin -- the tasks begin execution here
   -- do stuff in the procedure itself, maybe call task entries
 end;

The problem is that this doesn't really provide any extra protection
for the programmer. You get language facilities that will provide the
protection, but the programmer has to remember to use them in every
case. If you forget to declare a method as protected, then nothing
stops two tasks from entering it and screwing up the objects data with
unsynchronized access. This should be compared to SCOOP, where trying
to do something like that is impossible.

   Thanks again,
   mike

-- 
Mike Meyer [EMAIL PROTECTED]  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: Command config, quitting, binary, Timer

2005-09-03 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
 I am still ignorant about Tkinter. This little program, after pressing
 the Go eats more and more RAM, is it normal? Can it be avoided? (In
 normal programs this is isn't a real problem).
 
 ! import Tkinter
 ! def dogo():
 ! while 1:
 ! b.config(command=lambda:None)
 ! root = Tkinter.Tk()
 ! b = Tkinter.Button(root, text=Go, command=dogo)
 ! b.pack()
 ! root.mainloop()

What did you expect to happen with the infinite loop inside dogo()? 
Wouldn't it call b.config() over and over again, never returning?  Is 
that really what you wanted?

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


Re: os.system(rls) prints to screen??

2005-09-03 Thread Steve Holden
Xah Lee wrote:
 does anyone know why the folllowing prints to the screen?
 
 # python
 import os
 os.system(rls)
 
  Xah
  [EMAIL PROTECTED]
 ∑ http://xahlee.org/
 
It only prints to the screen when standard output of the invoking 
process is the screen. The sub-process forked by os.system inherits 
stdin stdout and stderr from the invoking process.

This is all pretty basic stuff. Perhaps you should stop your verbal 
assault on the computer science community and start to learn the 
principles of what you are doing.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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

Re: Submitting doc bug reports without SF registration

2005-09-03 Thread Paul Rubin
Terry Reedy [EMAIL PROTECTED] writes:
 1. A DocImprovement wiki.  People could optionally sign up for update 
 reports on specific wiki pages.
 
 2. A new SF tracker, only for doc bugs, that would accept anonymous 
 submissions.  The other trackers require login because most items need 
 additional feedback from requestors.  But reports like On page x.y.x, 
 'seperate' should be 'separate' do not require feedback unless the 
 requestor wants the 'fixed, thank you' comment emailed.
 
 As an item reviewer, I prefer the second, but we are both curious as
 to the preference of potential no-login reporters.

I think php.net's system works quite well and Python should do
something similar if it's feasible.
-- 
http://mail.python.org/mailman/listinfo/python-list


descriptors for container items

2005-09-03 Thread Brock Filer

  If I do that, the attributes (that was a stupid name for me to 
 choose)
  and children would have to not share any names with each other,

 Since multiple objects can indeed have duplicate attribute names, and 
 such
 duplication is rampant in Python, I am not sure what you mean.

felons['@class'] = 'capital'
felons['class'].do_something()
felons.class - SyntaxError

I thought I had my previous example down to:

countries/'us'/'Colorado'/'Denver'['@population']

, but of course that tries to subscript a string with a string; which 
might be an interesting idiom for substring searching, as long as it 
never returned -1.

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


how to do this?

2005-09-03 Thread Justin Straube
Greetings Pythonistas.
Im looking for a way to write this but not sure where or how to begin.
As the user enters or removes characters into/from sEnt I would like
for set_info() to set infVar with the correct value. The same as how
IDLE shows the line and column in the lower right corner.

 Code Example 
from time import localtime
from Tkinter import *

def set_info():
 x = len(strVar.get())
 infVar.set('Length: %i' % (x))

ROOT = Tk()
strVar = StringVar()
infVar = StringVar()

sLab = Label(ROOT, text='String')
sLab.grid(row=0, column=0)
sEnt = Entry(ROOT, textvariable=strVar, width=15)
sEnt.grid(row=0, column=1, columnspan=2)
qBut = Button(ROOT, text='Quit', command=ROOT.quit)
qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
iLab = Label(ROOT, textvariable=infVar, width=21,
  relief=SUNKEN, anchor=W)
iLab.grid(row=2, column=0, columnspan=3)

set_info() # example to show what will be displayed.
ROOT.mainloop()
 End Example 

Can anyone point me in the right direction for how to do this?

Regards,

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


gmail access

2005-09-03 Thread gerald gillespie
how do I access my new Gmail account [EMAIL PROTECTED]

_
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: how to do this?

2005-09-03 Thread Steve Holden
Justin Straube wrote:
 Greetings Pythonistas.
 Im looking for a way to write this but not sure where or how to begin.
 As the user enters or removes characters into/from sEnt I would like
 for set_info() to set infVar with the correct value. The same as how
 IDLE shows the line and column in the lower right corner.
 
First of all, it might have been better to provide a more meaningful 
title like Update display as text entry changes, but not to worry - 
this is a matter of experience.

  Code Example 
 from time import localtime
 from Tkinter import *
 
 def set_info():
  x = len(strVar.get())
  infVar.set('Length: %i' % (x))
 
 ROOT = Tk()
 strVar = StringVar()
 infVar = StringVar()
 
 sLab = Label(ROOT, text='String')
 sLab.grid(row=0, column=0)
 sEnt = Entry(ROOT, textvariable=strVar, width=15)
 sEnt.grid(row=0, column=1, columnspan=2)
 qBut = Button(ROOT, text='Quit', command=ROOT.quit)
 qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
 iLab = Label(ROOT, textvariable=infVar, width=21,
   relief=SUNKEN, anchor=W)
 iLab.grid(row=2, column=0, columnspan=3)
 
 set_info() # example to show what will be displayed.
 ROOT.mainloop()
  End Example 
 
 Can anyone point me in the right direction for how to do this?
 
The key here is to bind keystroke events to the routine to change the 
display. The following program uses your set_info() function to update 
the display every time a key is released (I chose this event because by 
the time it is raised the keystroke has been processed by the Entry widget.

I don;t guarantee this code will work across several Entry widgets 
without your keeping track of which one has focus when the event is 
raised (it's late, and I'm about to turn in for the night), but at least 
it will give you something to play with.

You'll note that set_info() has acquired an argument - Tkinter provides 
an event as an argument when a callback is called. So the manual call 
gets a bogus event of None just to avoid exceptions. Hope this gets 
you started.

 Code Example 
from time import localtime
from Tkinter import *

def set_info(event):
  x = len(strVar.get())
  infVar.set('Length: %i' % (x))

ROOT = Tk()
strVar = StringVar()
infVar = StringVar()

sLab = Label(ROOT, text='String')
sLab.grid(row=0, column=0)
sEnt = Entry(ROOT, textvariable=strVar, width=15)
sEnt.grid(row=0, column=1, columnspan=2)
sEnt.bind(KeyRelease, set_info)
qBut = Button(ROOT, text='Quit', command=ROOT.quit)
qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
iLab = Label(ROOT, textvariable=infVar, width=21,
   relief=SUNKEN, anchor=W)
iLab.grid(row=2, column=0, columnspan=3)

set_info(None) # example to show what will be displayed.
ROOT.mainloop()
 End Example 

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


[ python-Feature Requests-1281053 ] non-sequence map() arguments for optimization

2005-09-03 Thread SourceForge.net
Feature Requests item #1281053, was opened at 2005-09-03 01:30
Message generated for change (Settings changed) made by birkenfeld
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1281053group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: None
Status: Closed
Resolution: Invalid
Priority: 5
Submitted By: Ecnassianer of the Green Storm (ecnassianer)
Assigned to: Nobody/Anonymous (nobody)
Summary: non-sequence map() arguments for optimization

Initial Comment:
I'm trying to optimize some code thats similiar to this:

anObject = someConstructor() # This isn't a sequence
myList = myListMaker()  # This IS a sequence

for items in myList:
 function(items, anObject)


I'd like to be able to do this:
map(function, myList, anObject)

But the map function takes two lists, so I have to do
somethign like this:

list2 = []
for x in range(len(myList)):
 list2.append(anObject)
map(function, myList, list2)

But intializing list2 kind of defeats the purpose of
optimization. I was looking for some way to convince
anObject that it was really a list containing a lots of
entries of itself, but couldn't find anything in the API.

What I'd love to have is a version of the map function
which takes a function, a sequence, and an object as
arguments and calls the function with the first
argument as an element in the sequence, and the second
element as the object for as many times as their are
items in the sequence. 

(Note: Currently the API says if you pass sequences of
unequal lenghths to map, it uses None to fill up the
rest of the calls)

--

Comment By: Reinhold Birkenfeld (birkenfeld)
Date: 2005-09-03 08:43

Message:
Logged In: YES 
user_id=1188172

Use a list comprehension:

[function(item, anObject) for item in myList]

or, if you must use map,

map(lambda item: function(item, anObject), myList)

And please direct such questions to comp.lang.python in the
future.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1281053group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1281291 ] Erroneous \url command in python.sty

2005-09-03 Thread SourceForge.net
Bugs item #1281291, was opened at 2005-09-03 17:18
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281291group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Rory Yorke (ryorke)
Assigned to: Nobody/Anonymous (nobody)
Summary: Erroneous \url command in python.sty

Initial Comment:
The \url and \ulink commands in texinputs/python.sty
produce erroneous PDF files. This can be fairly easily
tested using GhostScript (see the attached log file for
an example). 

The current Python 2.4.1 PDF docs (as downloadable from
www.python.org) have this error.

Although the error does not prevent correct rendering
in viewers such as gv, xpdf or acroread, the link is
absent.

The attached patch partially addresses this, by
changing the arguments to the \pdfstart command used.
The changes are taken straight from
texmf/tex/latex/hyperref/hpdftex.def; that file has the
following version header:

%% File: hyperref.dtx Copyright 1995-2001 Sebastian Rahtz,
%% RCS: $Id: hyperref.dtx 6.71 2000/10/04 rahtz Exp rahtz $

I don't pretend to understand the TeX code, but it does
fix some of the problem.

Some URLs, like
http://sourceforge.net/bugs/?group_id=5470, are not
linked to correctly. That particular URL becomes

http://sourceforge.net/bugs/[EMAIL PROTECTED]@[EMAIL PROTECTED]@[EMAIL 
PROTECTED]@skip%20id=5470

-- I guess that has something to do with the underscore.

The diff was generated relative to Python CVS head of 3
Sept 2005; the python.sty file had version 1.113.

The python executable used was 2.4.1, not CVS.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281291group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1281408 ] Py_BuildValue k format units don't work with big values

2005-09-03 Thread SourceForge.net
Bugs item #1281408, was opened at 2005-09-04 01:12
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281408group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Adal Chiriliuc (adalx)
Assigned to: Nobody/Anonymous (nobody)
Summary: Py_BuildValue k format units don't work with big values

Initial Comment:
Python 2.4 on Windows XP SP2

Consider this code:

unsigned long x = 0xaabbccdd;
PyObject* v = Py_BuildValue(k, x);
unsigned long y = PyLong_AsUnsignedLong(v);

y will be equal with -1 because PyLong_AsUnsignedLong
will raise an OverflowError since Py_BuildValue doesn't
create a long for the k format unit, but an int which
will be interpreted as a negative number.

The K format seems to have the same error,
PyLong_FromLongLong is used instead of
PyLong_FromUnsignedLongLong.

The do_mkvalue function from mod_support.c must be
fixed to use PyLong_FromUnsignedLong instead of
PyInt_FromLong for k.

Also, the BHLkK  format units for Py_BuildValue should
be documented. In my Python 2.4 manual they do not appear.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281408group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1281383 ] array.arrays are not unpickleable

2005-09-03 Thread SourceForge.net
Bugs item #1281383, was opened at 2005-09-03 15:16
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281383group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Extension Modules
Group: Python 2.4
Status: Closed
Resolution: Invalid
Priority: 6
Submitted By: Reinhold Birkenfeld (birkenfeld)
Assigned to: Raymond Hettinger (rhettinger)
Summary: array.arrays are not unpickleable

Initial Comment:
Credits to John Machin for discovering this.


Googling for pickle array in comp.lang.python yields
old messages that 
show a PickleError -- plus one message where Alex
Martelli writes I am 
but an egg :O)
Looks like arrays are NOW (2.4.1) pickleable but not
unpickleable -- see 
below.
I appreciate that arrays are inherently not pickleable
because of the 
type code.
However:
(1) Anyone know why/when the world changed?
(2) If we had alternative constructors like
array.iarray(contents) in 
parallel to array.array('i', contents), those objects
could be 
pickled/unpickled -- yes/no?

Cheers,
John

Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310
32 bit (Intel)] on 
win32
Type help, copyright, credits or license for
more information.
  import pickle, array
  class Foo(object):
...pass
...
  foo = Foo()
  foo.ia = array.array('i', [3,2,1])
  foo.ia
array('i', [3, 2, 1])
  s = pickle.dumps(foo, -1)
  bar = pickle.loads(s)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File C:\Python24\lib\pickle.py, line 1394, in loads
return Unpickler(file).load()
  File C:\Python24\lib\pickle.py, line 872, in load
dispatch[key](self)
  File C:\Python24\lib\pickle.py, line 1097, in
load_newobj
obj = cls.__new__(cls, *args)
TypeError: array() takes at least 1 argument (0 given)
===


--

Comment By: Raymond Hettinger (rhettinger)
Date: 2005-09-03 18:20

Message:
Logged In: YES 
user_id=80475

In Py2.4, array's became copyable, weak-referencable, and
got support for iterator arguments.  Real pickle support
wasn't added until Py2.5.  The above code fragment is a
by-product of pickle making an incorrect guess at how to
pickle arrays before real pickel support was added.  It is
not really a bug; rather, it begs for a feature that wasn't
added to later.

If it weren't a new feature, I would just backport the 2.5
pickle support. 

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1281383group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-687747 ] _iscommand() in webbrowser module

2005-09-03 Thread SourceForge.net
Bugs item #687747, was opened at 2003-02-17 07:17
Message generated for change (Comment added) made by ekid
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=687747group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Matthew Cowles (mdcowles)
Assigned to: Fred L. Drake, Jr. (fdrake)
Summary: _iscommand() in webbrowser module

Initial Comment:
[From a post to python-help]

Under KDE under Mandrake Linux the BROWSER environment
variable is set to

kfmclient openProfile webbrowsing

The problem is that _iscommand() in the webbrowser
module doesn't realize that only the first thing there
is the name of the executable. It looks for an
executable with that whole thing as its name and
doesn't find one. Since the module doesn't use any
browser it has found if BROWSER is set, it raises an
error rather than opening the page.

The possible fixes that are obvious to me all have
potential disadvantages:

One solution would be to assume that the name of the
executable ran only up to the first space. But
executables can have spaces in their names, especially
on a Macintosh, I think.

Another possibility would be not to call _iscommand()
on anything in BROWSER. That would have the additional
advantage of not requiring that the executable
specified there be in a directory that's in the user's
PATH. The problem with doing things this way is that it
would be impossible to tell which of the browsers
specified in BROWSER should be used until the user
called open().

I'm prepared to work on a fix if given some guidance
about the best way to go.

--

Comment By: Dmitry Vukolov (ekid)
Date: 2005-09-04 04:36

Message:
Logged In: YES 
user_id=1000960

The problem still exists in Python 2.4.1

--

Comment By: Facundo Batista (facundobatista)
Date: 2005-05-30 23:37

Message:
Logged In: YES 
user_id=752496

richard seems to reproduced it on Py2.3, changing the group
to it.

--

Comment By: Richard Jones (richard)
Date: 2005-01-17 01:01

Message:
Logged In: YES 
user_id=6405

This is still an issue. 
 
python -c 'import 
webbrowser;webbrowser.open(http://www.google.com/;)' 
on a system using KDE will exhibit the break. 
 
I posted a patch to fix the behaviour in my last message. I just 
noticed that I invoked diff the wrong way around (though the 
explanation still stands) - a correct invocation: 
 
--- /tmp/webbrowser.py  2005-01-17 08:59:50.697657208 
+1100 
+++ /usr/lib/python2.3/webbrowser.py2005-01-17 
08:59:58.269989095 +1100 
@@ -354,7 +354,7 @@ 
 if BROWSER in os.environ: 
 # It's the user's responsibility to register handlers for any 
unknown 
 # browser referenced by this value, before calling open(). 
-_tryorder = os.environ[BROWSER].split(os.pathsep) 
+_tryorder[0:0] = os.environ[BROWSER].split(os.pathsep) 
 
 for cmd in _tryorder: 
 if not cmd.lower() in _browsers: 
 

--

Comment By: Facundo Batista (facundobatista)
Date: 2005-01-15 15:26

Message:
Logged In: YES 
user_id=752496

Please, could you verify if this problem persists in Python 2.3.4
or 2.4?

If yes, in which version? Can you provide a test case?

If the problem is solved, from which version?

Note that if you fail to answer in one month, I'll close this bug
as Won't fix.

Thank you! 

.Facundo

--

Comment By: Richard Jones (richard)
Date: 2003-08-20 04:29

Message:
Logged In: YES 
user_id=6405

This is still an issue... has there been any movement on it outside of this 
bug report? 
 
I'm seeing the behaviour on Mandrake 9.1, KDE 3.1.3 that the module is 
finding the BROWSER env var as described above, and thus not finding a 
usable browser. 
 
As a fallback, the _tryorder shouldn't be *replaced* by BROWSER, but 
just prepended with its value. Sure, that means that the KDE BROWSER 
value will be ignored, but it'll still find konqueror. This approach works for 
me, and I'm sure it'll work for others who have quot;validquot; BROWSER 
values 
:) 
 
Simple patch against python2.3 (sorry, sf will mangle this, but it's short): 
 
--- webbrowser.py   2003-08-20 10:28:07.0 +1000 
+++ /usr/lib/python2.3/webbrowser.py2003-08-04 
10:18:17.0 +1000 
@@ -354,7 +354,7 @@ 
 if quot;BROWSERquot; in os.environ: 
 # It's the user's responsibility to register handlers for any unknown 
 # browser referenced by this value, before calling open(). 
-_tryorder[0:0] = os.environ[quot;BROWSERquot;].split(os.pathsep) 
+