Re: Next floating point number

2005-12-17 Thread Tim Peters
[Steven D'Aprano]
> I'm looking for some way to get the next floating point number after any
> particular float.
...
> According to the IEEE standard, there should be a routine like next(x,y)
> which returns the next float starting from x in the direction of y.
>
> Unless I have missed something, Python doesn't appear to give an interface
> to the C library's next float function. I assume that most C floating
> point libraries will have such a function.

While the C99 standard defines such a function (several, actually),
the C89 standard does not, so Python can't rely on one being
available.  In general, Python's `math` module exposes only standard
C89 libm functions, plus a few extras it can reliably and portably
build itself on top of those.  It does not expose platform-specific
libm functions.  You can argue with that policy, but not successfully
unless you take over maintenance of mathmodule.c <0.5 wink>.

> So I came up with a pure Python implementation, and hoped that somebody
> who had experience with numerical programming in Python would comment.

If you're happy with what you wrote, who needs comments ;-)  Here's a
careful, "kinda portable" implementation in C:

http://www.netlib.org/toms/722

If you ignore all the end cases (NaNs, infinities, signaling underflow
and overflow, ...), the heart of it is just adding/subtracting 1
to/from the 64-bit double representation, viewing it as an 8-byte
integer.  That works fine for the IEEE-754 float representations (but
does not work for all float representations).

I've used this simple routine based on that observation, which ignores
all endcases, and only works if both input and result are >= 0:

"""
from struct import pack, unpack

def next(x, direction=+1):
bits = unpack(">Q", pack(">d", x))[0]
return unpack(">d", pack(">Q", bits + direction))[0]
"""

For example,

>>> next(0) # smallest denorm > 0
4.9406564584124654e-324
>>> next(_, -1) # should really signal underflow
0.0
>>> next(1)
1.0002
>>> next(1, -1)
0.99989
>>> next(1e100)
1.0002e+100
>>> next(1e100, -1)
9.9982e+099
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread robic0
On 16 Dec 2005 16:52:43 -0800, "Xah Lee" <[EMAIL PROTECTED]> wrote:

>Responsible Software Licensing
>
>Xah Lee, 200307
>
>Software is a interesting invention. Software has this interesting
Soft, like your head
>property, that it can be duplicated without cost, as if like copying
it costs to dup, dup
>money. Never in history are goods duplicable without cost. But with the
wrong, you can dup your bullshit evrywhere for free
>invention of computer, the ephemeral non-physical programs break that
you don't know what a computer is
>precept. In digital form, programs and music and books all become goods
i bid a gigabuck for that gigabyte
>in essentially infinite quantity.
in a for() loop maybe
>
>All is good except, bads in digital form can also multiply equally,
get a calculator, bad is negative and subtracts, not multiply
>just as goods. Well known examples are computer viruses and email
virus and email or virus in email?
>spams. Unknown to the throng of unix morons are software bads. In a
"software bads" is like asian bads, dumber than dog shit
>unix moron's mind, the predominant quip among hackers is “where is
whats on the morons mind anyway Zah?
>your code?”, singnifying the mentality that a hacker's prestige is
when is mentality signified, do a cat scan do any good?
>judged on how much code he has contributed to the community. Therefore,
per line or content? if the dude is dumb does his software get demoted
>every fucking studs and happy-go-lucky morons put their homework on the
right, the 9 inch dicked moron with the genious iq, and very tall..
>net, with a big stamp of FREE, and quite proud of their
free... suck my 9 inch dick, and quite proud
>“contributions” to the world. These digital bads, including
well, a big dick is a gods gift to women (or did u mean digitial dick)
>irresponsible programs, protocols, and languages, spread like viruses
every program i ever met was irresponsible and never wore condoms
(i never fucked with them so "i" don't know)
>until they obtained the touting right of being the STANDARD or MOST
yup, down south we call them the "John Henry", definetly the standard
>POPULAR in industry, as if indicating superior quality. Examplary are
nah, superior "dick size" doesen't mean mind
>C, Perl, RFC, X-Windows, Apache, MySQL, Pretty Home Page (and almost
oh, u name dropper your so intelligent
>anything out of unix). The harm of a virus is temporal. The harm of
a "virus" is a physical ailment, not a mind doodoo 
>irresponsible software (especially with unscrupulous promotion) is the
i never knew a responsible software, can u name one?  they don't 
talk to me, maybe cause i just curse them out.. hahahaaa
>creation of a entire generation of bad thinking and monkey coders. The
i think you mean monkey jakkingoff, which usually leads to bad
thinking, i mean really man step away from the gun and put your hands
in the air...
>scale can be compared as to putting a bullet in a person brain, versus
you mean surgically, i never saw one "put" in there. anybody seen
this happen?
>creating a creed with the Holocaust aftermath.
omg, bring the jews into into it.
>
>Distribution of software is easily like pollution. I thought of a law
so shit flows downhill eh...

>that would ban the distribution of software bads, or like charging for
keep the software bads to yourself (whatever that is)
>garbage collection in modern societies. The problem is the difficulty
nothin wrong with garbage, its a 3 billion dolla industry
>of deciding what is good and what is bad. Like in so many things, i
can we leave good/bad up got god, or at least anybody with a brain?
>think the ultimate help is for people to be aware; so-called education;
i think toilet paper helps alot better, edu is a mind fuk divorced
from reality ... like u
>I believe, if people are made aware of the situation i spoke of, then
awareness comes when you "find" your navel
>irresponsible software will decrease, regardless any individual's
>opinion.
i never knew a "mind" software that considered itself irresponsible
>
>The most important measure to counter the tremendous harm that
is the epa
>irresponsible software has done to the industry is to begin with
can't we all agree "software" is not people ...
>responsible licenses, such that the producer of a software will be
can't we all agree licenses were made for marriages and dog tags ..
>liable for damage incurred thru their software. As we know, today's
your software killed my country, i want 1 trillion in damages 
>software license comes with a disclaimer that essentially says the
i wish marriage license did
>software is sold as is and the producer is not responsible for any
software is sold. i think you should be instead, we know what u can do
>damage, nor guaranteeing the functionality of the software. It is this,
software functions as it was programmed, not as your conception of
its use ... you should find out what "it" doess first
>that ferments all sorts of sloppitudes and fads and myth

Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Gunnar Hjalmarsson
robic0 wrote:
> Xah Lee wrote:
>> 
>> 
> 
> 

So, at last they found one another. :(

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Lexical Scope

2005-12-17 Thread [EMAIL PROTECTED]
>Note that NotImplemented is not the same as NotImplementedError -- and I 
>wasn't suggesting
>raising an exception, just returning a distinguishable "True" value, so that
>a test suite (which I think you said the above was from) can test that the 
>"when"
>guard logic is working vs just passing back a True which can't distinguish 
>whether
>the overall test passed or was inapplicable.


Ahh, sorry about that. I got ya. that's not a bad idea.

>BTW, is this data coming from an actual DBMS system? If so, wouldn't
>there be native facilities to do all this validation? Or is Python
>just too much more fun than SQL? ;-)

Well, the "first usage" is going to come from a RDBMS, yeap. We use
MySQL 4.1.x right now. I know with Oracle/MSSQL, it's easy to put all
kinds of fancy constraints on data. I'm aware of no such facilities in
MySQL though I would love it if there was one to apply these kinds of
flexible validation routines.

Worst case scenario I can use it to do testing of what is pulled out of
the database :)

>Not to distract you, but I'm wondering what your rules would look like 
>represented in simple
>rule-per-line text, if you assume that all names are data base field names
>unless otherwise declared, and just e.g. "name!" would be short for 
>"have(name)",
>then just use some format like (assuming 'rules' is a name for a particular 
>group of rules)

>functions:: "is_ssn" # predeclare user-defined function names
>operators:: "and", "<" # might be implicit

>rules: first_name!; last_name!; ssn! and is_ssn(ssn); birth_date! and 
> hire_date! and (birth_date < hire_date)

>or with identation, and messages after a separating comma a la assert

That's really a great idea!

When I was trying to figure out how to combine these rules and figure
out what kind of flexibility I wanted, I actually did write some
declarative strings. It was a lot more verbose than what you wrote, but
it helped with the concepts. Your approach is good.

My little pseduo-lang was like:

REQUIRE last_name or first_name
WHEN HAVE last_name, surname THEN REQUIRE last_name != surname



Well, I didn't go on and work with the error strings. I decided that
this thing wouldn't be very useful without being able to work with
hierarchical data.

So I abstracted out the idea of referencing the record by key and
implemented a little "data resolution" protocol using PLY. I like the
protocol because I think it will be something that can be reused fairly
often, especially for mini-langs.

def testNestedData(self):
data = {
'first_name' : 'John',
'last_name' : 'Smith',
'surname' : '',
'phone' : '205-442-0841',
'addresses' : {
'home' : {
'street' : '123 Elm St',
'city' : 'Birmingham',
'state' : 'AL',
'postal' : '35434'
},
'work' : {
'street' : '101 Century Square',
'city' : 'Centre',
'state' : 'AL',
'postal' : '35344'
}
},
'aliases' : [
'John Smith',
'Frank Beanz'
]
}

rule = when(have('addresses.work'), all(
have('addresses.work.city'),
have('addresses.work.state'),
have('addresses.work.postal')))

assert repr(rule(data))
data['addresses']['work']['city'] = ''
assert rule(data) == False
data['addresses']['work']['city'] = 'Centre'


It works the same as the rules do:

def match(test, field):
""" match uses a function that takes a single string and returns a
boolean
and converts it into a validation rule.
"""
field = drep(field)
def rule(record):
value = field(record)
if value:
return bool(test(value))
else:
return True
return rule

def check(test, fields):
""" check uses a function that takes a variable arguments and
applies the given
fields to that function for the test.
"""
fields = [drep(field) for field in fields]
def rule(record):
values = [field(record) for field in fields]
return test(*values)
return rule


The data resolution algorithm uses dots and square braces. Dot's
resolve on dicts and square braces resolve on lists. It doesn't support
slicing, but it easily could. There is

Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread robic0
On Sat, 17 Dec 2005 09:55:10 +0100, Gunnar Hjalmarsson
<[EMAIL PROTECTED]> wrote:

>robic0 wrote:
>> Xah Lee wrote:
>>> 
>>> 
>> 
>> 
>
>So, at last they found one another. :(
Thanks for the coaching  Gunnar !!!

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


Re: Problem with Lexical Scope

2005-12-17 Thread [EMAIL PROTECTED]
>>from functional import curry

>I'm not familiar with that module, but I wrote a byte-code-munging curry
>as a decorator that actually modified the decorated function to eliminate
>parameter(s) from the signature and preset the parameter values inside the 
>code.
>I mention this because pure-python currying that I've seen typically creates a 
>wrapper
>function that calls the original function, and slows things down with the 
>extra calling
>instead of speeding things up, at least until some future version of python.
>Looks nice on the surface though.

Sounds very useful. Is this open source? All of the curry functions
I've seen in the wild use a wrapper as well. I don't care for this
either mainly because it hides away the function attributes and when I
use decorators on functions that mudge attributes, it doesn't work.

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


doctest fails to NORMALIZE_WHITESPACE ?

2005-12-17 Thread David MacKay
Hello, I'm a python-list newbie. I've got a question about doctest; perhaps 
a bug report.

I really like doctest, but sometimes doctest gives a failure when the output 
looks absolutely fine to me -- indeed, even after I have gone to considerable 
effort to make my documentation match the output perfectly.

http://www.aims.ac.za/~mackay/python/compression/huffman/Huffman3.py

The above file is an example.

It's self-contained, so you can plop it into emacs and hit C-cC-c to run the 
doctests. One of them fails. 
The piece of source code concerned is here: 

>>> c = []; \
c.append(node(0.5,1,'a')); \
c.append(node(0.25,2,'b')); \
c.append(node(0.125,3,'c')); \
c.append(node(0.125,4,'d')); \
iterate(c) ; reportcode(c)   # doctest: 
+NORMALIZE_WHITESPACE, +ELLIPSIS
#Symbol Count   Codeword
a (0.5) 1
b (0.25)01
c (0.12)000
d (0.12)001
"""

And the output is: 

Failed example:
c = []; c.append(node(0.5,1,'a')); 
c.append(node(0.25,2,'b')); c.append(node(0.125,3,'c')); 
c.append(node(0.125,4,'d')); iterate(c) ; reportcode(c)   # 
doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
Expected:
#Symbol Count   Codeword
a (0.5) 1
b (0.25)01
c (0.12)000
d (0.12)001
Got:
<__main__.internalnode instance at 0xb7aee76c>
#Symbol Count   Codeword
a   (0.5)   1
b   (0.25)  01
c   (0.12)  000
d   (0.12)  001

===

I have tried numerous tweaks, and am at a loss. I am wondering whether there
is some big in doctest involving the "#" character in the output.
Or maybe I made some silly mistake.

Any advice appreciated!

Many thanks again to the authors of doctest, it gives a great feeling 
to write code in the way that doctest encourages. :-)

David

--
David J.C. MacKay [EMAIL PROTECTED] 787 9336
  http://www.aims.ac.za/~mackay/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next floating point number

2005-12-17 Thread Bengt Richter
On Sat, 17 Dec 2005 14:23:38 +1100, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>I'm looking for some way to get the next floating point number after any
>particular float.
>
>(Any mathematicians out there: I am aware that there is no "next real
>number". But floats are not real numbers, they only have a finite
>precision.)
>
>According to the IEEE standard, there should be a routine like next(x,y)
>which returns the next float starting from x in the direction of y.
>
>Unless I have missed something, Python doesn't appear to give an interface
>to the C library's next float function. I assume that most C floating
>point libraries will have such a function.
>
>So I came up with a pure Python implementation, and hoped that somebody
>who had experience with numerical programming in Python would comment.
>
>
>
>def nextfloat(x, y=None):
>"""Return the next floating point number starting at x in the
>direction of y. If y is not given, the direction is away from zero.
>"""
>from operator import add, sub
>from math import frexp # Returns a tuple (mantissa, exponent)
>x = float(x)
>if y is None:
>if x < 0.0:
>op = sub
>else:
>op = add
>elif y > x:
>op = add
>elif y < x:
>op = sub
>else:
>raise ValueError("direction float is equal to starting float")
># We find the next float by finding the smallest float epsilon which 
># is distinguishable from x. We know epsilon will be a power of two, 
># because floats are implemented internally in binary.
># We get our initial estimate for epsilon from the floating point 
># exponent of x.
>epsilon = 2.0**(frexp(x)[1]) # epsilon > abs(x)
>lasteps = epsilon # Save a copy of our last epsilon for later use.
>while op(x, epsilon) != x:
>lasteps = epsilon
>epsilon /= 2.0
># When we get here, we've halved epsilon one time too many.
># We can't just double it, because that fails for the case where x is
># zero - epsilon will underflow to zero. So we need to save and use
># the previous iteration of epsilon.
>return op(x, lasteps)
>
I wonder if this won't work (for IEEE 754 double that is)

from math import frexp
def nextf(x, y):
f,e = frexp(x)
if (f==0.5 or f==-0.5) and x>=y: eps = 2.0**-54
else: eps = 2.0**-53
if xhttp://mail.python.org/mailman/listinfo/python-list


Re: doctest fails to NORMALIZE_WHITESPACE ?

2005-12-17 Thread Tim Peters
[David MacKay]
> Hello, I'm a python-list newbie. I've got a question about doctest; perhaps
> a bug report.

As things will turn out, it's just a question.  That's common for newbies :-)

> I really like doctest, but sometimes doctest gives a failure when the output
> looks absolutely fine to me -- indeed, even after I have gone to considerable
> effort to make my documentation match the output perfectly.
>
> http://www.aims.ac.za/~mackay/python/compression/huffman/Huffman3.py
>
> The above file is an example.
>
> It's self-contained, so you can plop it into emacs and hit C-cC-c to run the
> doctests. One of them fails.
> The piece of source code concerned is here:
>
> >>> c = []; \
> c.append(node(0.5,1,'a')); \
> c.append(node(0.25,2,'b')); \
> c.append(node(0.125,3,'c')); \
> c.append(node(0.125,4,'d')); \
> iterate(c) ; reportcode(c)   # doctest: 
> +NORMALIZE_WHITESPACE, +ELLIPSIS

I'd probably write that more like so:

>>> c = [node(0.5,1,'a'), node(0.25,2,'b'), node(0.125,3,'c'),
node(0.125,4,'d')]
>>> iterate(c)
>>> reportcode(c)  # doctest [etc]

When Python doesn't "look clean", it's not Python -- and backslash
continuation & semicolons often look like dirt to the experienced
Python's eye.

> #Symbol Count   Codeword
> a (0.5) 1
> b (0.25)01
> c (0.12)000
> d (0.12)001
> """
>
> And the output is:
>
> Failed example:
> c = []; c.append(node(0.5,1,'a')); 
> c.append(node(0.25,2,'b')); c.append(node(0.125,3,'c')); 
> c.append(node(0.125,4,'d')); iterate(c) ; reportcode(c)   
> # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
> Expected:
> #Symbol Count   Codeword
> a (0.5) 1
> b (0.25)01
> c (0.12)000
> d (0.12)001
> Got:
> <__main__.internalnode instance at 0xb7aee76c>

Well, there you go, right?  There was certainly no

<__main__.internalnode instance at 0xb7aee76c>

line in the expected output.  I don't know whether you _want_ to see
that line or not, but the doctest said you don't.  That's why the test
fails.  If you do want to see it, add, e.g.,

<__main__.internalnode instance at 0x...>

as the first line of the expected output.

> #Symbol Count   Codeword
> a   (0.5)   1
> b   (0.25)  01
> c   (0.12)  000
> d   (0.12)  001

You have another problem here, alas:  whether a "%2.2g" format rounds
0.125 to "0.12" or "0.13" varies across platforms.  For example, if
you had run this on Windows, you would have seen:

 c   (0.13)  000
 d   (0.14)  001

for the last two lines.

> I have tried numerous tweaks, and am at a loss. I am wondering whether there
> is some big in doctest involving the "#" character in the output.
> Or maybe I made some silly mistake.

I think we're ready to vote on that now ;-)

> Any advice appreciated!
>
> Many thanks again to the authors of doctest, it gives a great feeling
> to write code in the way that doctest encourages. :-)

You're welcome!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest fails to NORMALIZE_WHITESPACE ?

2005-12-17 Thread Peter Otten
David MacKay wrote:

> I really like doctest, but sometimes doctest gives a failure when the
> output looks absolutely fine to me -- indeed, even after I have gone to
> considerable effort to make my documentation match the output perfectly.

> The piece of source code concerned is here:
> 
> >>> c = []; \
> c.append(node(0.5,1,'a')); \
> c.append(node(0.25,2,'b')); \
> c.append(node(0.125,3,'c')); \
> c.append(node(0.125,4,'d')); \
> iterate(c) ; reportcode(c)   # doctest:

You have to suppress the return value of iterate()

  dummy = iterate(c); reportcode(c)

> +NORMALIZE_WHITESPACE, +ELLIPSIS
> #Symbol   Count   Codeword
> a (0.5)   1
> b (0.25)  01
> c (0.12)  000
> d (0.12)  001
> """
> 

> And the output is:
> 
> Expected:
> #Symbol Count   Codeword
> a (0.5) 1

> Got:
> <__main__.internalnode instance at 0xb7aee76c>

This is the result of iterate(c).  The interactive interpreter ignores None
return values but prints the repr() of everything else. doctest emulates
that behaviour.

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


Re: Python on GP2X (Linux Based Handheld Console)

2005-12-17 Thread Jérôme Laheurte
On Sat, 17 Dec 2005 02:50:29 +, Michael wrote:

> I must admit personally I wouldn't be interested in python on a PSP because
> you never know when homebrew code on a PSP is going to be locked out...

Yes, but it only concerns new buyers and people who upgrade their
firmware. Upgrading the firmware brings new functionnalities, but these
are often already implemented in some homebrew app, so I'm staying at 1.50...

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-17 Thread Mike Meyer
[EMAIL PROTECTED] writes:
> Mike Meyer wrote:
>> It's conceivable that a change might make Python more popular and also
>> detract from the language in some way. For a ridiculous example,
>> making Python interpret Perl 6 would certainly make it more popular,
>> but I would argue that would seiously detract from the language.
> why would one want python to interpret Perl 6 ?

So you could have a perl 6 interpreter, of course. Assuming you
wanted one, of course.

 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: doctest fails to NORMALIZE_WHITESPACE ?

2005-12-17 Thread David MacKay
Thanks everyone! Silly me  :-)

* Tim Peters <[EMAIL PROTECTED]> [2005-12-17 12:01]:
> [David MacKay]
> > Hello, I'm a python-list newbie. I've got a question about doctest; perhaps
> > a bug report.
> 
> As things will turn out, it's just a question.  That's common for newbies :-)

I've got a follow-up question motivated by my ugly backslash continuations.

> When Python doesn't "look clean", it's not Python -- and backslash
> continuation & semicolons often look like dirt to the experienced
> Python's eye.

The reason I was making those ugly single-line monsters was 
I had somehow got the impression that each fresh line starting ">>>" was tested 
_completely_separately_ by doctest; so, to preserve state I thought I had to 
write 

>>> a=[2, 5, 1];  a.sort();  print a
[1, 2, 5]

rather than 

>>> a=[2, 5, 1]
>>> a.sort()
>>> print a
[1, 2, 5]

But I see now I was wrong.  Question: 
Does doctest always preserve 
   state throughout the entire sequence of tests enclosed by `"""`, as if the 
tests were 
   entered in a single interactive session? 
Or is there a way to instruct doctest to forget its state, and start 
   the next `>>>` with a clean slate? 

Thanks very much!
David

-- 
--
David J.C. MacKay [EMAIL PROTECTED] 787 9336
  http://www.aims.ac.za/~mackay/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python write foreign characters to the console?

2005-12-17 Thread Martin v. Löwis
Do Re Mi chel La Si Do wrote:
> That depends on what we call "console".
> 
> Python console?
> or
> Windows console?

AFAICT, it works in both: if I start Python 2.4 (command line)
from the start menu, and have it import a module that prints

# -*- coding: iso-8859-1 -*-
print u"Martin v. Löwis"

it will print the umlaut, and the same happends if I start
cmd.exe, run python, and then run the code that makes that
print statement. In either case, the font selected was
"Raster Fonts", and in cmd.exe, the Active code page was
850.

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


Re: Problem with Lexical Scope

2005-12-17 Thread Bengt Richter
On 17 Dec 2005 01:16:31 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>>>from functional import curry
>
>>I'm not familiar with that module, but I wrote a byte-code-munging curry
>>as a decorator that actually modified the decorated function to eliminate
>>parameter(s) from the signature and preset the parameter values inside the 
>>code.
>>I mention this because pure-python currying that I've seen typically creates 
>>a wrapper
>>function that calls the original function, and slows things down with the 
>>extra calling
>>instead of speeding things up, at least until some future version of python.
>>Looks nice on the surface though.
>
>Sounds very useful. Is this open source? All of the curry functions
>I've seen in the wild use a wrapper as well. I don't care for this
>either mainly because it hides away the function attributes and when I
>use decorators on functions that mudge attributes, it doesn't work.
>
The curry part works like:
(first unmodified)

 >>> import inspect
 >>> def foo(x, y): return x*y
 ...
 >>> import dis
 >>> dis.dis(foo)
   1   0 LOAD_FAST0 (x)
   3 LOAD_FAST1 (y)
   6 BINARY_MULTIPLY
   7 RETURN_VALUE
 >>> inspect.getargspec(foo)
 (['x', 'y'], None, None, None)

(modified)
 >>> from ut.presets import presets, curry
 >>> @curry(y=111)
 ... def foo(x, y): return x*y
 ...
 >>> dis.dis(foo)
   1   0 LOAD_CONST   1 (111)
   3 STORE_FAST   1 (y)

   3   6 LOAD_FAST0 (x)
   9 LOAD_FAST1 (y)
  12 BINARY_MULTIPLY
  13 RETURN_VALUE
 >>> inspect.getargspec(foo)
 (['x'], None, None, None)

The presets decorator does the same except doesn't modify the signature
(it came first ;-)

 >>> def foo():
 ... return now()
 ...
 >>> dis.dis(foo)
   2   0 LOAD_GLOBAL  0 (now)
   3 CALL_FUNCTION0
   6 RETURN_VALUE
 >>> import time
 >>> @presets(now=time.ctime)
 ... def foo():
 ... return now()
 ...
 >>> dis.dis(foo)
   1   0 LOAD_CONST   1 ()
   3 STORE_FAST   0 (now)

   3   6 LOAD_FAST0 (now)
   9 CALL_FUNCTION0
  12 RETURN_VALUE
 >>> foo()
 'Sat Dec 17 02:49:06 2005'

Humph. Good night ;-/

I googled and found a post of mine, which I think may be my last version, at 

http://groups.google.com/group/comp.lang.python/msg/7d27a53385e89924

where you can look to see if it's interesting. I think it's probably more 
fruitful
to put work into doing it by way of rewriting the AST, which would potentially
allow folding constant expressions that may be formed when parameters
become constants, etc. So I haven't pursued byte code munging much further.
The version above only had minor testing, and only on python 2.4. IOW, basically
a proof of concept.

I based my presets/curry decorator on the pattern of a decorator Raymond 
Hettinger wrote,
which optimizes global accesses and other stuff. No warranties, mind! ;-)

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


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Mark Carter
robic0 wrote:

> Xah, please admit to me that your under the influence of 
> physocopic drugs!  

He could be schizophrenic.

Seekers of all things wierd on the internet can do no better than Gene 
Ray's Timecube:
http://www.timecube.com/

His outpourings are so well known that he even gets a mention in the 
wikipedia:
http://en.wikipedia.org/wiki/Gene_Ray

And once you've fully absorbed the fact that "You are educated as a 
stupid android slave to the evil Word Animal Singularity Brotherhood", 
why not play the game of the theory over at:
http://atrocities.primaryerror.net/timecube.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter interactive

2005-12-17 Thread cm012b5105
Hello i am fairly new to python,
I have written an interactive programme a small example of it is here.
s = raw_input ("Do you have any children? ")
if s== 'yes':
   print "Thats great"
elif s=='no':
   print "Well my boss has 2"


Now i have also been looking at Tkinter if we take the basic "hello, world" 
programme which is like this.

# File: hello1.py

from Tkinter import *

root = Tk()

w = Label(root, text="Hello,!")
w.pack()

root.mainloop()

What i want is to incorporate this in to my programme so when i start my 
programme a little box appears saying hello then my interactive programme 
runs within the box
This it what it looks like

from Tkinter import *

root = Tk()

w = Label(root, text="Hello,!")
w.pack()
s = raw_input ("Do you have any children? ")
if s== 'yes':
   print "Thats great"
elif s=='no':
   print "Well my boss has 2"

The result of that is i just get another box open and start to run my 
interactive programme as though it ignores the Tk box which says hello hope 
this makes sense any advise on this please.
thanks nige
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE (was: PythonWin troubleshooting)

2005-12-17 Thread chuck
Yeah but is it 'fast'.  What is Komodo written in?

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


Re: PythonWin troubleshooting

2005-12-17 Thread Greg Chapman
On 13 Dec 2005 14:27:48 -0800, "chuck" <[EMAIL PROTECTED]> wrote:

>
>After some use the problems have re-appeared with the "ActivePython
>2.3.5.236" distro.  I think the problem is related to some sort of
>shell hook as it goofs up not only PythonWin, but other windows
>applications and windows itself.  Can't get the context menu to work in
>explorer, the task manager from the task bar, etc.  Something is really
>goofed up!  The problem only appears when PythonWin is running or was
>running and is hung in memory from a non-clean PythonWin shutdown.

This sounds like you may have a corrupted registry.  See this bug
report for a description:

http://sourceforge.net/tracker/?group_id=78018&atid=551954&func=detail&aid=1017504

There was a fix added for this in one of the recent builds, and I
haven't run into it lately, but it appears from one follow-up in the
above that the problem can still occur.  Anyway, to get rid of the
symptoms you need to clean up the "HKCU\Software\Python2.4\Python for
Win32" key by getting rid of all the extra toolbar keys (or if you
don't have any customizations, you can just delete the above key, and
PythonWin will recreate it the next time it is run).  I guess there is
no guarantee that you will not run into this again, but, as I said, I
have not seen it recur with the latest builds of PythonWin.

---
Greg Chapman

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


Re: Tkinter interactive

2005-12-17 Thread Murtog (sent by Nabble.com)

nige,

as you are a begginer is better to you to use the: http://www.ferg.org/easygui/ 
module. it is a very easy module to make guis.

the use of tkinter envolves some more advanceds topics, as Classes, Event-Handlers, it is better you learn the basic of Python and so you go to Tkinter.

cheers! =]

Sent from the Python - python-list forum at Nabble.com:
Re: Tkinter interactive
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python IDE

2005-12-17 Thread Colin J. Williams
David wrote:
> linuxfreak wrote:
> 
>> Which is a better python IDE SPE or WingIDE in terms of features
>>
> 
> You might want to look at a review of Python IDEs at
> http://spyced.blogspot.com/2005/09/review-of-6-python-ides.html
> 
> david lees
Thanks, this is an excellent review.  It mentions but does not review  SPE.

I've found PythonWin a good tool, it handles code completion.  Although 
I've had some recent problems with it.

There is PyScripter which looks as though it's close to ready for use - 
I ran into one bug.

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


Re: Invoking Unix commands from a Python app

2005-12-17 Thread Will McDonald
On 16 Dec 2005 08:45:01 -0800, Rob Cowie <[EMAIL PROTECTED]> wrote:
> Excellent... just the thing I was looking for. Thanks.
>
> Does anyone know of a unix app that could be used to monitor the
> duration of processes etc.?

If you have control over starting the program then "time" will probaby suffice.

time - time a simple command or give resource usage

DESCRIPTION
   The  time  command  runs  the specified program command with the given
   arguments.  When command finishes, time writes a message  to  standard
   output giving timing statistics about this program run.  These statis-
   tics consist of (i) the elapsed real time between invocation and  ter-
   mination,  (ii)  the  user  CPU  time  (the  sum  of the tms_utime and
   tms_cutime values in a struct tms as returned by times(2)), and  (iii)
   the system CPU time (the sum of the tms_stime and tms_cstime values in
   a struct tms as returned by times(2)).

[EMAIL PROTECTED] ~]$ time find . > /dev/null 2>&1

real0m0.010s
user0m0.001s
sys 0m0.009s
[EMAIL PROTECTED] ~]$


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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-17 Thread floydophone
I'm the founder and lead developer of Subway.

I am all for it. TG would have to change a couple of things IMHO, but I
think it would be a great idea.

If we were to merge projects, we would have to get a serious
TurbowaySubgears blogging hype train going.

- Peter Hunt

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


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Matt Garrish

 wrote in message news:[EMAIL PROTECTED]
> On 16 Dec 2005 16:52:43 -0800, "Xah Lee" <[EMAIL PROTECTED]> wrote:
>
> physocopic drugs!
>

Please do us all the favour of taking a basic literacy course. You aren't 
even close half the time, which just confirms you're a halfwit.

Matt 


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


Re: Robotics and parallel ports

2005-12-17 Thread c d saunter
Isaac T Alston ([EMAIL PROTECTED]) wrote:
: Thanks for everyone's tips and hints. I WILL MAKE THIS WORK! I think I'll
: take your advice and use the serial port instead of the parallel port - I
: won't have that much data to send (in comparison with, for example,
: industrial level applications). As for on-board chips though, does this
: require low level programming!? Or can I have an embedded python
: interpreter for the chip? 

Hi Isaac,
You might be interested in PyMite - 
http://python.fyxm.net/pycon/papers/pymite/ 
although I don't know much (anythin? :-) about it.

For on board control there are some tiny embedded computers out there that can 
run 
Linux etc. (and hence Python) these days - e.g. see 
http://www.linuxdevices.com/articles/AT8498487406.html or you could use a much 
simpler 
processor such as a PIC to implement a simple serial port to dgital and 
analogue IO 
module.

Either way, plent to do :-)

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


Your message to theseptemberproject awaits moderator approval

2005-12-17 Thread theseptemberproject-bounces
Your mail to 'theseptemberproject' with the subject

hi, ive a new mail address

Is being held until the list moderator can review it for approval.

The reason it is being held:

Post by non-member to a members-only list

Either the message will get posted to the list, or you will receive
notification of the moderator's decision.  If you would like to cancel
this posting, please visit the following URL:


http://lists.drizzle.com/mailman/confirm/theseptemberproject/76558cd7423e93bf672dcdf421ad8512e8b13ed1

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


Re: SMP, GIL and Threads

2005-12-17 Thread catsup
It was actually quite a minor adjustment in the application to follow
the oft repeated advice here on this subject to share only the Queue
object between threads.  Making the update of the dictionary just
another queued command request caused both the dictionary read and
write to be performed by the same thread.  This seems to have
eliminated the problem.

Thank you all for your thoughtful comments.

Randy

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


Wingide is a beautiful application

2005-12-17 Thread vinjvinj
I haven't used an IDE in a long time but gave wing ide a try because
I wanted the same development platform on Linux and Windows.

I'm currently using Ultraedit and it works fine but needed something
more portable as I'm moving my main platform over to Ubuntu. I first
tried jedit and was reasonably happy with it but it felt slow and it
did not have a native look and feel to it. It was really hard on the
eyes.

I was impressed! The UI has completely changed since the last time I
gave it a spin. It's much more useable and beautiful on the eyes. My
productivity has gone up for sure and would highly recomend it to
anyone else. not to mention you'll be supporting python as well.

Things I like about wingide:
- Ability to double click on the project plan and it hides and you
double click on it and it becomes visable again.
- Ability to double click on the debug/python shell plan and it hides
and you double click on it and it becomes visable again.
- Auto completion is very powerful and well implemented.
- Open the file that a function was defined through the context menu
- Keyboard mapping for vi and emacs
- Always having a python shell available
- An integrated debugger.
- Running in debug mode was significantly faster than any other
debugger I have used.
- Auto indent mode is vary useful.
- The space manager. Notifies you if a file contains spaces and tabs
and then converts all tabs into spaces.
- Ability to debug my cherrypy and turbogears application

Things that could use improvement:
- The block mode Ability to work with text files in block mode where
you can highlight any block in the file. Wingide implementation is
reasonable but not like Ultraedit's or jedit's

Does anyone know what gui toolkit wingide uses? it really is one of the
best applications I've seen for some time and it's a great way to
support python.

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


Re: SMP, GIL and Threads

2005-12-17 Thread Aahz
In article <[EMAIL PROTECTED]>,
catsup <[EMAIL PROTECTED]> wrote:
>
>It was actually quite a minor adjustment in the application to follow
>the oft repeated advice here on this subject to share only the
>Queue object between threads.  Making the update of the dictionary
>just another queued command request caused both the dictionary read
>and write to be performed by the same thread.  This seems to have
>eliminated the problem.

Great!
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Don't listen to schmucks on USENET when making legal decisions.  Hire
yourself a competent schmuck."  --USENET schmuck (aka Robert Kern)
-- 
http://mail.python.org/mailman/listinfo/python-list


Faster copying of composite new-class objects

2005-12-17 Thread Alex
Hi,

My program requires copying thousands of composite new-class objects. I
found that the following: objCopy=cPickle.loads(cPickle.dumps(obj,
protocol=2)) works about 4 times faster than
copyObj=copy.deepcopy(obj). Is there any way to do it even faster?

All objects have slots, __getstate__ and __setstate__.

TIA,

Alex

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


Re: Python IDE

2005-12-17 Thread SPE - Stani's Python Editor
SPE will be reviewed by the same person for the next PyCon against
WingIDE, Komodo and Pydev. Maybe you say which features you want to
give a better answer. I don't know about WingIDE but I do know about
SPE ;-)

Things which we want to have ready for the review:
- integrated debugger (now WinPdb runs external)
- configurable keyboard shortcuts
- configurable color schemes
- realtime syntax error underling (already implemented, wait for
0.8.1.c)
- ...

Well, much more features are implemented almost daily as more people
start also contributing.

Stani
--
http://pythonide.stani.be

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


Re: Wingide is a beautiful application

2005-12-17 Thread Sybren Stuvel
vinjvinj enlightened us with:
> I haven't used an IDE in a long time but gave wing ide a try because
> I wanted the same development platform on Linux and Windows.

I use gvim for that :)

> - Ability to double click on the project plan and it hides and you
> double click on it and it becomes visable again.

How do you double-click on something that's hidden?

> - Keyboard mapping for vi and emacs

VI keyboard mapping! I like :)

> - Always having a python shell available

I have a Python shell on my PDA, always available :))

> - The space manager. Notifies you if a file contains spaces and tabs
> and then converts all tabs into spaces.

And what if you want to use tabs?

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Cp1251-symbols in SOAP request

2005-12-17 Thread Pelmen
in short
>>> doc = SOAPpy.SOAPProxy('localhost:8000', 'urn:Server', encoding='cp1251')
>>> doc.invoke('НомерДок'.decode('cp1251'), ())
*** Outgoing SOAP
**

http://schemas.xmlsoap.org/soap/encoding/";
  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/";
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/";
>






Traceback (most recent call last):
  File "", line 1, in -toplevel-
doc.invoke('НомерДок'.decode('cp1251'), ())
  File "C:\Python24\lib\site-packages\SOAPpy\Client.py", line 322, in
invoke
return self.__call(method, args, {})
  File "C:\Python24\lib\site-packages\SOAPpy\Client.py", line 364, in
__call
config = self.config)
  File "C:\Python24\lib\site-packages\SOAPpy\Client.py", line 196, in
call
r.endheaders()
  File "C:\Python24\lib\httplib.py", line 795, in endheaders
self._send_output()
  File "C:\Python24\lib\httplib.py", line 676, in _send_output
self.send(msg)
  File "C:\Python24\lib\httplib.py", line 655, in send
self.sock.sendall(str)
  File "", line 1, in sendall
UnicodeEncodeError: 'ascii' codec can't encode characters in position
161-168: ordinal not in range(128)

How can i force this problem.
Thanks.

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

Re: Wingide is a beautiful application

2005-12-17 Thread Steve Holden
Sybren Stuvel wrote:
> vinjvinj enlightened us with:
> 
>>I haven't used an IDE in a long time but gave wing ide a try because
>>I wanted the same development platform on Linux and Windows.
> 
> 
> I use gvim for that :)
> 
> 
>>- Ability to double click on the project plan and it hides and you
>>double click on it and it becomes visable again.
> 
> 
> How do you double-click on something that's hidden?
> 
> 
>>- Keyboard mapping for vi and emacs
> 
> 
> VI keyboard mapping! I like :)
> 
> 
>>- Always having a python shell available
> 
> 
> I have a Python shell on my PDA, always available :))
> 
> 
>>- The space manager. Notifies you if a file contains spaces and tabs
>>and then converts all tabs into spaces.
> 
> 
> And what if you want to use tabs?
> 

Then you configure it to use tabs. It's a user setting.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Erik Max Francis
Pelmen wrote:

> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 161-168: ordinal not in range(128)
> 
> How can i force this problem.

The problem is that you're trying to write a Unicode string to a socket. 
  In order to do that properly, you have to encode it to a string properly.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Could it be / That we need loving to survive
   -- Neneh Cherry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Pelmen
what to do, to encode it properly? UTF-8?

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Erik Max Francis
Pelmen wrote:

> what to do, to encode it properly? UTF-8?

You're the one sending it through a socket; only you know what the other 
side expects.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Could it be / That we need loving to survive
   -- Neneh Cherry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: locawapp-001.zip

2005-12-17 Thread LocaWapp
"class Server" has a big error: what is?

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


Re: Wingide is a beautiful application

2005-12-17 Thread James
>> I haven't used an IDE in a long time but gave wing ide a try because
>> I wanted the same development platform on Linux and Windows.

>> I'm currently using Ultraedit and it works fine but needed something
>> more portable as I'm moving my main platform over to Ubuntu. I first
>> tried jedit and was reasonably happy with it but it felt slow and it
>> did not have a native look and feel to it. It was really hard on the
>> eyes.

Then you owe it to yourself to also try SPE, PyDev and Boa Constructor
(got off to a slow start, but it looks promising now). All are free,
open source, cross platform, native look and feel and support more or
less the features you list.

>> Does anyone know what gui toolkit wingide uses? it really is one of the
>> best applications I've seen for some time and it's a great way to
>> support python.

GTK.

Two minor peeves about WingIDE.
1.) Not native look and feel.
2.) Auto List members implementation is great. But what about call
tips? Just as important and every other Python IDE has it.

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Pelmen
as i understood, better way is base64 encoding on my side, and decoding
on server side?

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


Join CodingCache.com

2005-12-17 Thread j883376
CodingCache is an new and upcoming forum dedciated to all sorts of
programming. From HTML to C/C++ to Perl and PHP.

As of this post, CodingCache doesn't have very many members or posts
because its just beginning. Don't let that discourage you from
registering and posting though. There will eventually be more sources
of new registrations. Once there is a decent amount of content,
visitors will naturally register.

http://www.codingcache.com

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


"class Server" has a big error: what is?

2005-12-17 Thread LocaWapp
"class Server" has a big error: what is?

http://groups.google.it/group/comp.lang.python/browse_thread/thread/de458cb7675ff4b6/f333453b0dc1aab6?q=locawapp&rnum=1#f333453b0dc1aab6

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Pelmen
thanks ... it seems to me best way will be b16encode, to prevent sax
parser errors

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Jarek Zgoda
Pelmen napisał(a):

> as i understood, better way is base64 encoding on my side, and decoding
> on server side?

No, just encode the texts in what encoding the other side expects. If
this should be CP1251, not decoding would be enough.

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


urllib.urlopen

2005-12-17 Thread JabaPyth
Hello,
I'm trying to use the urllib module, but when i try urllib.urlopen, it
gives me a socket error:

>>import urllib
>>print urllib.urlopen('http://www.google.com/').read()
Traceback (most recent call last):
File "", line 1, in ?
File "C:\Python24\lib\urllib.py", line 77, in urlopen
  return opener.open(url)
File "C:\Python24\lib\urllib.py", line 180, in open
  return getattr(self, name)(url)
File "C:\Python24\lib\urllib.py", line 296, in open_http
  h.endheaders()
File "C:\Python24\lib\httplib.py", line 794, in endheaders
  self._send_output()
File "C:\Python24\lib\httplib.py", line 675, in _send_output
  self.send(msg)
File "C:\Python24\lib\httplib.py", line 642, in send
  self.connect()
File "C:\Python24\lib\httplib.py", line 610, in connect
  socket.SOCK_STREAM):
 IOError: [Errno socket error] (11001, 'getaddrinfo failed')

Any ideas on what i did wrong?

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


Re: Cp1251-symbols in SOAP request

2005-12-17 Thread Pelmen
but socket will raise an exception if it'll be in cp1251

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


Re: Tkinter interactive

2005-12-17 Thread James Stroud
cm012b5105 wrote:
> Hello i am fairly new to python,
> I have written an interactive programme a small example of it is here.
> s = raw_input ("Do you have any children? ")
> if s== 'yes':
>print "Thats great"
> elif s=='no':
>print "Well my boss has 2"
> 
> 
> Now i have also been looking at Tkinter if we take the basic "hello, world" 
> programme which is like this.
> 
> # File: hello1.py
> 
> from Tkinter import *
> 
> root = Tk()
> 
> w = Label(root, text="Hello,!")
> w.pack()
> 
> root.mainloop()
> 
> What i want is to incorporate this in to my programme so when i start my 
> programme a little box appears saying hello then my interactive programme 
> runs within the box
> This it what it looks like
> 
> from Tkinter import *
> 
> root = Tk()
> 
> w = Label(root, text="Hello,!")
> w.pack()
> s = raw_input ("Do you have any children? ")
> if s== 'yes':
>print "Thats great"
> elif s=='no':
>print "Well my boss has 2"
> 
> The result of that is i just get another box open and start to run my 
> interactive programme as though it ignores the Tk box which says hello hope 
> this makes sense any advise on this please.
> thanks nige

GUI programming is kind of advanced. It is tough to make a leap from the 
hello world program of a new language to an interactive gui interface. I 
think you can save yourself a lot of frustration and confusion by first 
working throught the python tutorial:

   http://docs.python.org/tut/tut.html

Then working throught the "Tkinter tutorial":

   http://www.python.org/doc/life-preserver/

Pound these out over the course of a few weekends and you will be leaps 
and bounds further in your understanding than if you attempted to learn 
through unguided exploration (though the latter may be more fun sometimes).

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


object oriented programming question

2005-12-17 Thread Daniel Nogradi
I have class 'x' with member 'content' and another member  'a'  which is an instance of class '_a'. The class '_a' is callable and has a method 'func' which I would like to use to modify 'content' but I don't know how to address 'content' from the class '_a'. Is it possible?
 Here is the code that I've described above:class _a:    def __call__(self, v):    print v    def func():    """I would like to do something    with ´content´ here"""
class x:    def __init__(self):    self.content = [ ]    a = _a()Now I would like to be able to say

inst = x()
x.a(5)
x.a.func()

where the second line prints '5' as expected, but I don't know how to make the third line change 'x.content'. I guess I'm missing some basic concepts in object oriented programming...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: doctest fails to NORMALIZE_WHITESPACE ?

2005-12-17 Thread Tim Peters
[David MacKay, having fun with doctest]
 ...
> I've got a follow-up question motivated by my ugly backslash continuations.

[Tim]
>> When Python doesn't "look clean", it's not Python -- and backslash
>> continuation & semicolons often look like dirt to the experienced
>> Python's eye.

> The reason I was making those ugly single-line monsters was I had somehow got
> the impression that each fresh line starting ">>>" was tested
> _completely_separately_ by doctest; so, to preserve state I thought I had to 
> write
>
> >>> a=[2, 5, 1];  a.sort();  print a
> [1, 2, 5]
>
> rather than
>
> >>> a=[2, 5, 1]
> >>> a.sort()
> >>> print a
> [1, 2, 5]
>
> But I see now I was wrong.

Yup, that would be pretty unusable ;-)

> Question:
> Does doctest always preserve state throughout the entire sequence of tests
> enclosed by `"""`, as if the tests were entered in a single interactive 
> session?

Pretty much.  doctest can take inputs from several places, like (as
you're doing) docstrings, but also from files, or from the values in a
__test__ dictionary.  I'll note parenthetically that doctests are
heavily used in Zope3 and ZODB development, and "tutorial doctests" in
files have proved to be pleasant & very effective.  For example,



That entire file is "a doctest", and contains as much expository prose
as code.  It's written in ReST format, and tools in Zope3 can present
such doctest files as nicely formatted documentation too.  Unlike most
docs, though, each time we run ZODB's or Zope3's test suite, we
automatically verify that the examples in _this_ documentation are
100% accurate.  Standard practice now is to write a tutorial doctest
for a new feature first, before writing any implementation code; this
folds in some aspects of test-driven development, but  with some care
leaves you with _readable_ testing code and a tutorial intro to the
feature too.  That doctest makes it a little easier to write prose
than to write code is a bias that's amazingly effective in getting
people to write down what they _think_ they're doing ;-)

Anyway, running any piece of Python code requires a global namespace,
and doctest uses a single (but mutable!) global namespace for each
_batch_ of tests it runs.  In the case of a doctest file, a single
global namespace is used across the entire file.  In your case,
letting doctest extract tests from module docstrings, one global
namespace is created per docstring.  In that case, the globals the
tests in a docstring use are initially a shallow copy of the module's
__dict__.  That way the tests can "see" all the top-level functions
and classes and imports (etc) defined in the module, but can't mutate
the module's __dict__ directly.  Assignments within a doctest alter
bindings in the same namespace object, so these bindings are also
visible to subsequent code in the same docstring.  That's a
long-winded way of expanding on section 5.2.3.3 ("What's the Execution
Context?") in the docs.

> Or is there a way to instruct doctest to forget its state, and start
>  the next `>>>` with a clean slate?

Goodness no -- and nobody would want that.  You would lose _all_
globals then, including losing the ability to refer to functions and
classes (etc) defined in the module.

If, for some reason, you want to destroy some particular binding
within a doctest, then you do that the same way you destroy a global
binding outside of doctest, with `del`; e.g.,

"""
>>> x = range(100)
>>> len(x)
100
>>> del x  # free the memory for the giant list
>>> x
Traceback (most recent call last):
   ...
NameError: name 'x' is not defined
"""

works fine as a doctest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlopen

2005-12-17 Thread Xavier Morel
JabaPyth wrote:
> Hello,
> I'm trying to use the urllib module, but when i try urllib.urlopen, it
> gives me a socket error:
> 
> >>import urllib
> >>print urllib.urlopen('http://www.google.com/').read()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\lib\urllib.py", line 77, in urlopen
> return opener.open(url)
>   File "C:\Python24\lib\urllib.py", line 180, in open
> return getattr(self, name)(url)
>   File "C:\Python24\lib\urllib.py", line 296, in open_http
> h.endheaders()
>   File "C:\Python24\lib\httplib.py", line 794, in endheaders
> self._send_output()
>   File "C:\Python24\lib\httplib.py", line 675, in _send_output
> self.send(msg)
>   File "C:\Python24\lib\httplib.py", line 642, in send
> self.connect()
>   File "C:\Python24\lib\httplib.py", line 610, in connect
> socket.SOCK_STREAM):
>  IOError: [Errno socket error] (11001, 'getaddrinfo failed')
> 
> Any ideas on what i did wrong?
> 
Works for me, do you have a proxy or some strange setup for accessing to 
the web?

Try using the urllib2 module, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object oriented programming question

2005-12-17 Thread Michael Spencer
Daniel Nogradi wrote:
> I have class 'x' with member 'content' and another member  'a'  which is an
> instance of class '_a'. The class '_a' is callable and has a method 'func'
> which I would like to use to modify 'content' but I don't know how to
> address 'content' from the class '_a'. Is it possible?
> 
> Here is the code that I've described above:
> 
> class _a:
> def __call__(self, v):
> print v
> 
> def func():
> """I would like to do something
> with ´content´ here"""
> 
> class x:
> def __init__(self):
> self.content = [ ]
> 
> a = _a()
> 
> 
> Now I would like to be able to say
> 
> inst = x()
> x.a(5)
> x.a.func()
> 
> where the second line prints '5' as expected, but I don't know how to make
> the third line change 'x.content'.
> 

Hello Daniel

You've certainly got a lot going on here.

The heart of your question seems to be how a nested (inner) class _a can access 
its parent, x.  The short answer is that, in Python, it can't without some 
help. 
  _a and its instances are unaware of the context in which they are defined, so 
they hold no references to x or instance of x.  (Technically this is because 
the 
class is not created until after the statements in the class suite are executed)

Before we get to that, though, note that you've made content an attribute of 
x's 
instances, not the x class.  So there is no x.content, only inst.content.  I'll 
assume this was a typo, and you intended inst.content.  If this distinction is 
mysterious you may want to check: http://docs.python.org/tut/node11.html

Now, back to the question of how instance a could get a reference to inst.  The 
simplest way to program this is to give it the reference explicitly:


class _a:

 def func(self):
 """I would like to do something
 with ´content´ here.
 """
 print self.__parent__.content


class x:
 def __init__(self):
 self.content = ["I'm", "self.", "content"]

 a = _a()

  >>> inst = x()
  >>> inst.a.__parent__ = inst # give inst.a a reference to its parent
  >>> inst.a.func()
  ["I'm", 'self.', 'content']
  >>>



There is a way to automate "inst.a.__parent__ = inst", although it's not ideal 
"getting starting with Python objects" material.  The solution is to have _a 
implement the descriptor protocol (see: 
http://users.rcn.com/python/download/Descriptor.htm), and make the classes 
"new-style", i.e., derived from 'object':

class _a(object):

##def __call__(self, v):  Method is irrelevant to this discussion
##print v

 def func(self):
 """I would like to do something
 with ´content´ here.
 """
 print self.__parent__.content


 def __get__(self, obj, cls):
 """Store a reference to the referring obj"""
 if isinstance(obj, cls):
 self.__parent__ = obj
 return self

class x(object):
 def __init__(self):
 self.content = ["I'm", "self.", "content"]

 a = _a()


  >>> inst = x()
  >>> inst.a.func() #no need to set inst.a.__parent__ = inst manually now
  ["I'm", 'self.', 'content']
  >>>

HTH

Michael








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


Re: Next floating point number

2005-12-17 Thread Steven D'Aprano
On Sat, 17 Dec 2005 09:26:39 +, Bengt Richter wrote:


> I wonder if this won't work (for IEEE 754 double that is)
> 
> from math import frexp
> def nextf(x, y):
> f,e = frexp(x)
> if (f==0.5 or f==-0.5) and x>=y: eps = 2.0**-54
> else: eps = 2.0**-53
> if x else: return (f-eps)*2.0**e

Doesn't that assume floats are 64 bits? Is it possible that they might
not be on some platform or another?



-- 
Steven.

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


Re: Next floating point number

2005-12-17 Thread Steven D'Aprano
On Sat, 17 Dec 2005 03:27:11 -0500, Tim Peters wrote:

> While the C99 standard defines such a function (several, actually),
> the C89 standard does not, so Python can't rely on one being
> available.  In general, Python's `math` module exposes only standard
> C89 libm functions, plus a few extras it can reliably and portably
> build itself on top of those.  It does not expose platform-specific
> libm functions.  You can argue with that policy, but not successfully
> unless you take over maintenance of mathmodule.c <0.5 wink>.

*rueful smile*


>> So I came up with a pure Python implementation, and hoped that somebody
>> who had experience with numerical programming in Python would comment.
> 
> If you're happy with what you wrote, who needs comments ;-)  

Because I don't know _quite_ enough numeric programming to tell whether my
happiness is justified or just the happiness of somebody who hasn't
noticed the great big enormous bug staring him right in the face :-)


> Here's a
> careful, "kinda portable" implementation in C:
> 
> http://www.netlib.org/toms/722
> 
> If you ignore all the end cases (NaNs, infinities, signaling underflow
> and overflow, ...), the heart of it is just adding/subtracting 1 to/from
> the 64-bit double representation, viewing it as an 8-byte integer.  That
> works fine for the IEEE-754 float representations (but does not work for
> all float representations).

Will Python always use 64-bit floats?

> I've used this simple routine based on that observation, which ignores
> all endcases, and only works if both input and result are >= 0:
> 
> """
> from struct import pack, unpack
> 
> def next(x, direction=+1):
> bits = unpack(">Q", pack(">d", x))[0] return unpack(">d", pack(">Q",
> bits + direction))[0]
> """

Nice! I played around with struct.pack and unpack using a format string of
"f", but didn't get anywhere, so thanks for this.



-- 
Steven.

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


Re: "class Server" has a big error: what is?

2005-12-17 Thread Steven D'Aprano
On Sat, 17 Dec 2005 12:38:00 -0800, LocaWapp wrote:

> "class Server" has a big error: what is?
> 
> http://groups.google.it/group/comp.lang.python/browse_thread/thread/de458cb7675ff4b6/f333453b0dc1aab6?q=locawapp&rnum=1#f333453b0dc1aab6


Is this a game of Twenty Questions? We guess what the error is, and you
tell us if we are getting colder or hotter?

You might find a little bit more interest in helping you if you post the
traceback and the relevant bits of code. 


-- 
Steven.

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


Re: Wingide is a beautiful application

2005-12-17 Thread Claudio Grondi
vinjvinj wrote:
> I haven't used an IDE in a long time but gave wing ide a try because
> I wanted the same development platform on Linux and Windows.
> 
> I'm currently using Ultraedit and it works fine but needed something
> more portable as I'm moving my main platform over to Ubuntu.
This is also where I intend to go, except going for Wing, which is in my 
eyes currently no alternative to Ultra Edit as an overall text editor on 
Windows ( I am tired of using two or more editors at the same time as I 
do when working with Microsoft Visual C++ and want the features of both 
Ultra Edit and the Visual Studio IDE ).

- Wing does not have a ruler showing the current column
- Wing has a slow graphics output on Windows (also on Linux?)
- Wing GUI needs adaptation to its logic (e.g. there is no view menue 
item). I have to admit, that Ultra Edit GUI is also not good, so both 
need some adaptation efforts from the user.
- Wing does not support column mode (as you already said)
- Wing text editing is based on Scintilla and there are many other 
powerful and free editors built upon Scintilla available.
- Wing does not support HTML editing by providing separate HTML toolbar 
as the last versions of UltraEdit do.

The only thing what makes a difference to me is, that Wing 'understands' 
Python code what results in features not available elsewhere (e.g. go to 
definition). I don't know if UltraEdit in its Studio version does 
similar things - I suppose it does, but I will be surprized if also for 
Python - is there anyone who works with it?

The problem with deciding to use Wing on Linux is, that I am switching 
to Linux because of its Open Source at no cost feature, so I don't 
actually want to spend any money on proprietary software using Linux. 
But because there is no Ultra Edit on Linux it can happen, that I have 
to reconsider my attitude when actually fully on Linux. But this will 
maybe be never the case, as Windows appears to me as a much more 
powerful system and Linux comes in only in order to save money (when it 
is possible to use Python/Linux for running ready developed Python 
applications) on on multiple Windows licenses in case of using more than 
one PC.

Why do you go for Ubuntu, not for Mandriva if you are ready to pay money 
beeing on Linux?

  I first
> tried jedit and was reasonably happy with it but it felt slow and it
> did not have a native look and feel to it. It was really hard on the
> eyes.
> 
> I was impressed! The UI has completely changed since the last time I
> gave it a spin. It's much more useable and beautiful on the eyes. My
> productivity has gone up for sure and would highly recomend it to
> anyone else. not to mention you'll be supporting python as well.
> 
> Things I like about wingide:
> - Ability to double click on the project plan and it hides and you
> double click on it and it becomes visable again.
> - Ability to double click on the debug/python shell plan and it hides
> and you double click on it and it becomes visable again.
> - Auto completion is very powerful and well implemented.
> - Open the file that a function was defined through the context menu
> - Keyboard mapping for vi and emacs
> - Always having a python shell available
> - An integrated debugger.
> - Running in debug mode was significantly faster than any other
> debugger I have used.
> - Auto indent mode is vary useful.
> - The space manager. Notifies you if a file contains spaces and tabs
> and then converts all tabs into spaces.
> - Ability to debug my cherrypy and turbogears application
> 
> Things that could use improvement:
> - The block mode Ability to work with text files in block mode where
> you can highlight any block in the file. Wingide implementation is
> reasonable but not like Ultraedit's or jedit's
As Wing uses Scintilla I don't expect it to support column mode before 
Scintilla does.
What about editing large (100 MByte and more) text files? I have 
uninstalled Wing already, but I suppose, that it will run into problems 
when loading large files what I have experienced longer time ago using 
Scintilla.

Claudio
> 
> Does anyone know what gui toolkit wingide uses? it really is one of the
> best applications I've seen for some time and it's a great way to
> support python.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


effbot ExeMaker: custom icon?

2005-12-17 Thread Michael Spencer

What is the recommended way to change the icon of the exe ExeMaker* produces?

(I tried replacing the exemaker.ico file, and indeed removing it; but that had 
no effect.)

Thanks

Michael

*http://effbot.org/zone/exemaker.htm



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


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Roedy Green
On Sat, 17 Dec 2005 10:34:21 -0500, "Matt Garrish"
<[EMAIL PROTECTED]> wrote, quoted or indirectly quoted
someone who said :

>Please do us all the favour of taking a basic literacy course. You aren't 
>even close half the time, which just confirms you're a halfwit.
 are you bawling out robico or Xah?

Attributions are necessary for personal attacks.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Gunnar Hjalmarsson
Roedy Green wrote:
> On Sat, 17 Dec 2005 10:34:21 -0500, "Matt Garrish"
> <[EMAIL PROTECTED]> wrote, quoted or indirectly quoted
> someone who said :
> 
>>Please do us all the favour of taking a basic literacy course. You aren't 
>>even close half the time, which just confirms you're a halfwit.
> 
>  are you bawling out robico or Xah?

Does it really matter?

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Responsible Software Licensing

2005-12-17 Thread Eric J. Roode
robic0 wrote in news:[EMAIL PROTECTED]:

> On 16 Dec 2005 16:52:43 -0800, "Xah Lee" <[EMAIL PROTECTED]> wrote:
> 
>>Responsible Software Licensing
>>

I worship you, Xah.

-- 
Eric
`$=`;$_=\%!;($_)=/(.)/;$==++$|;($.,$/,$,,$\,$",$;,$^,$#,$~,$*,$:,@%)=(
$!=~/(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)..(.)/,$"),$=++;$.++;$.++;
$_++;$_++;($_,$\,$,)=($~.$"."$;$/$%[$?]$_$\$,$:$%[$?]",$"&$~,$#,);$,++
;$,++;$^|=$";`$_$\$,$/$:$;$~$*$%[$?]$.$~$*${#}$%[$?]$;$\$"$^$~$*.>&$=`
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Join CodingCache.com

2005-12-17 Thread skip

j883376> As of this post, CodingCache doesn't have very many members or
j883376> posts because its just beginning. Don't let that discourage you
j883376> from registering and posting though. There will eventually be
j883376> more sources of new registrations. Once there is a decent
j883376> amount of content, visitors will naturally register.

You wish. <0.5 wink>

It's not a case of "build it and they will come".  If there is unmet demand,
sure, build a site that satisfies the demand.  It's not clear that the
programming language community as a whole (or Python in particular) has any
unmet needs in the communication area.

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


Re: Xah's Edu Corner: Examples of Quality Technical Writing

2005-12-17 Thread Lars Rune Nøstdal
hi,
everyone thinks youreoay faggot and that youreh stupid .. now go
fugkght yourselfes

peasse out .. yo!

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


unsubscrib

2005-12-17 Thread YongYong Li
I would like to unsubsrib python list, how do I do it? __Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: ?: in Python

2005-12-17 Thread Andy Leszczynski
Steven D'Aprano wrote:
> On Wed, 14 Dec 2005 20:17:28 -0500, Andy Leszczynski wrote:
> 
> 
>>I can tell you what is not elegant in the if else: approach. It is 
>>logically a one operation while you are forced to use varaible "a" 
>>twice. Fundamental flaw IMO.
> 
> 
> "Logically" one operation?
> 
> def twenty_countries_in_seven_days_bus_tour():
> ...
> if today() == Monday:
> write_postcode_to_mother("We must be in Belgium.")
> else:
> get_back_on_the_bus("Not again!")
> ...
> 
> 
> if...else expressions with a single operation are just a special case.
> Perhaps a common special case, but still a special case.
> 
> 

First:
"Special cases aren't special enough to break the rules.
Although practicality beats purity."


Second, let's look at again:
 >if condition:
 >   a=1
 >else:
 >   a=2

The primer meaning behind that is that I want to assign something to a. 
  What I want to assign is secondary issue. I do not like C syntax of ?: 
either but I think it is just practical and self-explanatory.

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


Re: IsString

2005-12-17 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> If you think about Python
> as if it were C or Java, you will forever be confused about its behaviour.

Thinking of it as Java actually works great here.

> Understand Python's call by object behaviour, and it will all make sense.

Java's behavior is identical, excepting only Java's "primitives" (e.g.
floats), but definitely identical e.g. for strings (also immutable) and
class instances (normally mutable).


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


Re: unsubscrib

2005-12-17 Thread Robert Kern
YongYong Li wrote:
> I would like to unsubsrib python list, how do I do it?

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

Scroll to the bottom to see where you can unsubscribe.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Wingide is a beautiful application

2005-12-17 Thread Jonathan Ellis
James wrote:
> >> I haven't used an IDE in a long time but gave wing ide a try because
> >> I wanted the same development platform on Linux and Windows.

> Then you owe it to yourself to also try SPE, PyDev and Boa Constructor
> (got off to a slow start, but it looks promising now). All are free,
> open source, cross platform, native look and feel and support more or
> less the features you list.

In my experience Boa Constructor isn't worth bothering with.  It's far
too bugy for practical use.

> Two minor peeves about WingIDE.
> 1.) Not native look and feel.

Well...  GTK is as native as anything else, on Linux.  Even on Windows
GTK apps seem to be spreading; I've been using GIMP and GAIM long
enough that I guess "not quite native" doesn't bug me anymore.

> 2.) Auto List members implementation is great. But what about call
> tips? Just as important and every other Python IDE has it.

Wing shows calltip info in the Source Assistant panel.  (Pro version
only, IIRC.)

-Jonathan

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


Re: Xah's Edu Corner: Examples of Quality Technical Writing

2005-12-17 Thread Roedy Green
On 17 Dec 2005 19:34:36 -0800, "Lars Rune Nøstdal"
<[EMAIL PROTECTED]> wrote, quoted or indirectly quoted someone who
said :

>hi,
>everyone thinks youreoay faggot and that youreh stupid .. now go
>fugkght yourselfes

If you want to insult someone, please spell it correctly and be
accurate.  Your anger has nothing to do with his sexual preference. 

In the process you got me thinking about plonking you to avoid ever
helping a bigot with his Darwinian quest.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wingide is a beautiful application

2005-12-17 Thread Shalabh Chaturvedi
> James wrote:
>> 2.) Auto List members implementation is great. But what about call
>> tips? Just as important and every other Python IDE has it.

Jonathan Ellis wrote:

> Wing shows calltip info in the Source Assistant panel.  (Pro version
> only, IIRC.)

However it's not as useful as call tips. You have to switch to that tab. 
I tend to switch fairly often to another tab like Search or the Python 
Shell. Every time I need the assistant, I have to switch the tab again.

It does step through Quixote PTL in debug mode, which is pretty cool.

Shalabh

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


Re: urllib.urlopen

2005-12-17 Thread JabaPyth
I tried using urllib2 and this is what i got:
>>import urllib2
>>the_url = 'http://www.google.com'
>>req = urllib2.Request(the_url)
>>handle = urllib2.urlopen(req)
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
  File "C:\Python24\lib\urllib2.py", line 358, in open
response = self._open(req, data)
  File "C:\Python24\lib\urllib2.py", line 376, in _open
'_open', req)
  File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
result = func(*args)
  File "C:\Python24\lib\urllib2.py", line 1021, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python24\lib\urllib2.py", line 996, in do_open
raise URLError(err)
URLError: 

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


Wed Development - Dynamically Generated News Index

2005-12-17 Thread infidel02
Hi to all,

I am somewhat somewhat new to Python, but apart from this I am just not
seeing lots of resources on what I am trying to do.  I have seen them
in other languages like PHP and ASP.

I am building a simple MySQL news database,  which would contain, a
headline, a date, main story(body) and a graphic associated with each
story.  I would like to generate an index of the pages in this database
( ie a news index with links to the articles) an to have a news
administrator upload and delete stories graphic etc.

I have read many articles on Python CGI programming and I have Googled
extensively, but have not seen any kind of examples of how this can be
done in Python.

I would be grateful for any assistance or pointers.

Sincerely,

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


Re: Wed Development - Dynamically Generated News Index

2005-12-17 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I am building a simple MySQL news database,  which would contain, a
> headline, a date, main story(body) and a graphic associated with each
> story.  I would like to generate an index of the pages in this database
> ( ie a news index with links to the articles) an to have a news
> administrator upload and delete stories graphic etc.

Why don't you look at Django, which was built for that purpose.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlopen

2005-12-17 Thread Jay
Easy Fix...

import urllib
the_url = "http://www.google.com";
req = urllib.urlopen(the_url)

Does this work for you??

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


Re: Wed Development - Dynamically Generated News Index

2005-12-17 Thread Jean-Paul Calderone
On 17 Dec 2005 23:14:33 -0800, [EMAIL PROTECTED] wrote:
>Hi to all,
>
>I am somewhat somewhat new to Python, but apart from this I am just not
>seeing lots of resources on what I am trying to do.  I have seen them
>in other languages like PHP and ASP.
>
>I am building a simple MySQL news database,  which would contain, a
>headline, a date, main story(body) and a graphic associated with each
>story.  I would like to generate an index of the pages in this database
>( ie a news index with links to the articles) an to have a news
>administrator upload and delete stories graphic etc.
>
>I have read many articles on Python CGI programming and I have Googled
>extensively, but have not seen any kind of examples of how this can be
>done in Python.
>
>I would be grateful for any assistance or pointers.

Using Nevow and Twisted Web, this might look something like (untested)...

  from nevow import rend, loaders, tags

  class NewsIndex(rend.Page):
  docFactory = loaders.stan(tags.html[
  tags.body(render=tags.directive('index'))])

  def __init__(self, connpool):
  super(NewsIndex, self).__init__()
  self.connpool = connpool

  def _retrieveIndex(self):
  return self.connpool.runQuery(
  "SELECT articleId, articleTitle, articleImage FROM articles")

  def _retrieveArticle(self, articleId):
  return self.connpool.runQuery(
  "SELECT articleBody FROM articles WHERE articleId = ?",
  (articleId,))

  def render_index(self, ctx, data):
  return self._retrieveIndex().addCallback(lambda index: [
  tags.div[
  tags.a(href=articleID)[
  tags.img(src=articleImage),
  articleTitle]]
  for (articleID, articleTitle, articleImage)
  in index])

  def childFactory(self, ctx, name):
  return self._retrieveArticle(name).addCallback(lambda articleBody:
  ArticlePage(articleBody))


  class ArticlePage(rend.Page):
  docFactory = loaders.stan(tags.html[
  tags.body(render=tags.directive('article'))])

  def __init__(self, articleBody):
  super(ArticlePage, self).__init__()
  self.articleBody = articleBody

  def render_article(self, ctx, data):
  return self.articleBody

  from twisted.enterprise import adbapi

  # Whatever DB-API 2.0 stuff you want
  cp = adbapi.ConnectionPool('pypgsql', ...)

  from twisted.application import service, internet
  from nevow import appserver

  application = service.Application("News Site")
  webserver = appserver.NevowSite(NewsIndex(cp))
  internet.TCPServer(80, webserver).setServiceParent(application)

  # Run with twistd -noy 

For more information about Nevow, checkout the Wiki - 
 - or the mailing list - 
 - or the IRC 
channel - #twisted.web on freenode.

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