Re: gmpy floating point exception

2007-03-29 Thread Alex Martelli
Martin Manns <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I am experiencing some trouble with gmpy v1.01.
> Multiplying an mpq with inf results in a floating point exception that
> exits python. Has this already been fixed in newer gmpy versions? 

No, I can reproduce the problem (on a Mac with an Intel CPU) with the
current version, 1.02.  I will have no time to work for a fix until (I
hope) next week, though (spending a long weekend hitch-hiking).

> BTW.
> 1) What is the best way to test for inf regardless of type?

No, 'inf' is in fact not portable among different builds of Python for
different CPUs, in general.

> 2) Is there any inf type around with
> a + inf == inf
> inf > a (as long as a != inf)
> etc.
> that works with any other type?

You mean something like:

class inf(object):
def __radd__(self, other): return self
def __gt__(self, other): return self is not other
# etc
inf = inf()

...?


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


Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread Duncan Booth
John Nagle <[EMAIL PROTECTED]> wrote:

> Strictly speaking, it's Microsoft's fault.
> 
>  title="".  So all that following stuff is from what
> follows the next "-->" which terminates a comment.

It is an attribute value, and unescaped angle brackets are valid in 
attributes. It looks to me like a bug in BeautifulSoup.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hpw make lists that are easy to sort.

2007-03-29 Thread Anton Vredegoor
Terry Reedy wrote:

> If I understand correctly, you want to multiiply each of m numbers by each 
> of n numbers, giving m*n products.  That is O(m*n) work.  Inserting (and 
> extracting) each of these is a constant size m priority cue takes, I 
> believe, O(log(m)) work, for a total of m*n*log(m).  That is faster than 
> O(m*n*log(m*n)) for sorting m*n random numbers.

Probably, I'm not very good with big O computations. Please forget my 
earlier post and please also ignore the unfortunate subject line. I want 
the cartesian product of the lists but I want the sums of the items. 
Suppose the function to combine the items is

 def f(i,j):
 return i+j

And the list we want to sort would be made like this:

LR = [f(i,j) for i in L for j in R]

That would be like in my original post. However if the function would 
have been:

 def g(i,j):
 return n*i+j

The resulting cartesian product of the list would be sorted a lot 
quicker, especially if the two lists -L and R- we start with are sorted. 
(n is the length of both lists here)

So if changing the way the items are combined influences sorting time, 
is there also a way to optimize the order of generating the items for 
later sorting.

I mean optimized for a specific combining function, in this case 
function f.

> I don't know how you would sort by hashing.

Me too. I also learned that hashing is O(1) for non-mathematicians.

Probably I'm suffering from a mild outbreak of spring. I'm currently 
trying to stop myself from starting to smoke again or writing critical 
posts about PyPy, if it explains anything.

A.

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


Re: with timeout(...):

2007-03-29 Thread Hendrik van Rooyen
 "Nick Craig-Wood" <[EMAIL PROTECTED]> wrote:

> Well, yes there are different levels of potential reliability with
> different implementation strategies for each!

Gadzooks!  Foiled again by the horses for courses argument.

; - )

- Hendrik

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


Re: with timeout(...):

2007-03-29 Thread Diez B. Roggisch
> 
> I beleive the convention is when calling an OS function which might
> block the global interpreter lock is dropped, thus allowing other
> python bytecode to run.


So what? That doesn't help you, as you are single-threaded here. The 
released lock won't prevent the called C-code from taking as long as it 
wants. |And there is nothing you can do about that.

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


Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread Justin Ezequiel
On Mar 29, 4:08 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> John Nagle <[EMAIL PROTECTED]> wrote:
> >  title="

Re: which methods to use?

2007-03-29 Thread Florian Leitner
* Alex Martelli wrote, On 3/29/07 9:46 AM:
> <[EMAIL PROTECTED]> wrote:
>> another query, in the docs, list(a) and a[:] does the same thing (a =
>> [1,2,3] for example), but besides the speed of slicing is faster than
>> list(), what advantage is there for using list(a) in this case ?
> 
> Readability (a word is more readable than idiomatic punctuation), and
> conceptual uniformity with making shallow copies of other containers of
> known types such as sets and dicts.

I just want to summarizes what Alex is saying (correct me if I'm 
wrong!): usually, you do not want to use copy.copy, and copy.deepcopy 
only when you really need it (which is, if I search for it in my 
library, very seldom). As to whether use list(lst), [x for x in lst], 
list(x for x in lst), or just lst[:], I'd summarize it to this:

list(lst):
most expressive; use if you want to explicitly create a copy of a list 
and only a list or if you want to ensure that whatever sequence you 
received gets transformed to a list.

[list comprehension] and gen(erators):
usually to create a copy of a list, generator function or sequence with 
some modification; using list comprehension always creates list, with a 
generator setup you could do (for example):
tup = tuple(x + 1 for x in int_lst)
Some people also argue generators are faster, but I'd advise you to use 
what is more understandable first - you are asking what methods are 
faster, but keep in mind: "premature [code] optimization is the root of 
all evil", or so... (from T. Hoare/D. Knuth). And believe me, this 
statement holds always, as I had to learn the bloody hard way!

using slices[:]:
preserves the sequence you are using, so you could create a function 
that accepts list, tuples, strings or any other sequence as input and 
makes a copy of the sequence regardless of its type and returns that 
type. A very nice example of this is can be found in the 
Permutations/Combinations/Selections recipe from the Python Cookbook (R 
19.15):

def _combinators(_handle, items, n):
 # factored-out common structure for:
 # combinations, selections and permutations
 if n == 0:
 yield items[:0]
 return
 for i in range(len(items)):
 this_one = items[i:i + 1]
 for cc in _combinators(_handle, _handle(items, i), n - 1):
 yield this_one + cc

def combinations(items, n):
 """ take n distinct items, order matters """
 def skipIthItem(items, i):
 return items[:i] + items[i+1:]
 return _combinators(skipIthItem, items, n)

def uniqueCombinations(items, n):
 """ take n distinct items, order is irrelevant """
 def afterIthItem(items, i):
 return items[i+1:]
 return _combinators(afterIthItem, items, n)

def selections(items, n):
 """ take n (not necessarily distinct) items, order matters """
 def keepAllItems(items, i):
 return items
 return _combinators(keepAllItems, items, n)

def permutations(items):
 """ take all items, order matters """
 return combinations(items, len(items))

Because _combinators() returns "yield items[:0]" (i.e. the empty input 
sequence) instead of, say, an empty list ("yield list()"), and because 
the assignment to this_one in _combinators() is not "this_one = 
[items[i]]", but "this_one = items[i:i+1]", you can use any sequence as 
input to these functions, not just lists. Yet, it arguably might not be 
the most efficient solution because of the recurring sequence 
concatenations in the inner functions and the yield statement...

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


Re: PyPy 1.0: JIT compilers for free and more

2007-03-29 Thread Robin Becker
Christian Tismer wrote:
...
>> something
>> special, I am unable to dream of? Or is it purely academic project to
>> create Python VM in Python?
> 
> It will eventually give you a GIL-free VM, and it already gives you
> a lot more than you have dreamt of.
> 
> There is one feature missing that is probably hard to add.
> Handling the 'posters who are not willing to read before they post'  
> syndrome.
...

I come from an academic background (sadly not in computer science) so I 
understand the need to promote the abstract advances that are being made here.

However, I am a bit confused about the applicability of pypy. All the talk of 
backends, annotation object spaces etc etc may make some sense to really 
interested parties, but I would like to know what I can do in real terms with 
the new interpreters?

The demo javascript stuff seems a bit fake since others have already done some 
work in that direction already using ordinary python. RPython may be larger or 
smaller than those subsets, but that's not clear.

I would be interested to know if it's possible to point a tool at an existing 
python-2.4 module and wrap it into a much faster extension that can be used by 
my CPython stuff. I know there is preliminary work in that direction.

I am hugely encouraged by this

C:\Python\devel\pypy-1.0.0>\python24\python \python\lib\test\pystone.py
Pystone(1.1) time for 5 passes = 1.49586
This machine benchmarks at 33425.6 pystones/second

C:\Python\devel\pypy-1.0.0>.\pypy-c.exe \python\lib\test\pystone.py
Pystone(1.1) time for 5 passes = 2.16123e-005
This machine benchmarks at 2.3135e+009 pystones/second


:) not


-- 
Robin Becker

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


Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread Justin Ezequiel
On Mar 29, 6:11 pm, "Justin Ezequiel" <[EMAIL PROTECTED]>
wrote:
>
> FWIW, seehttp://tinyurl.com/yjtzjz
>

hmm. not quite right.

http://tinyurl.com/ynv4ct

or

http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser

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


YouTube showing repr() of a tuple

2007-03-29 Thread Leif K-Brooks
Thought this might amuse some of you:



I'd heard that YouTube uses Python, but it's fun to see proof of that, 
even if it comes in the form of a minor bug.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about extending tuple

2007-03-29 Thread abcd
>
> I hope you see now why it is consistent.
>
> Georg

yea that clears it up.  thanks.

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


Re: with timeout(...):

2007-03-29 Thread Nick Craig-Wood
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>   "Nick Craig-Wood" <[EMAIL PROTECTED]> wrote:
> 
> > Well, yes there are different levels of potential reliability with
> > different implementation strategies for each!
> 
>  Gadzooks!  Foiled again by the horses for courses argument.
> 
>  ; - )

;-)

I'd like there to be something which works well enough for day to day
use.  Ie doesn't ever wreck the internals of python.  It could have
some caveats like "may not timeout during C functions which haven't
released the GIL" and that would still make it very useable.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbi question on python rpc server, how it works?

2007-03-29 Thread Jean-Paul Calderone


On Thu, 29 Mar 2007 11:25:38 +0530, krishnakant Mane <[EMAIL PROTECTED]> wrote:
>hello all,
>I have downloaded the entire twisted library.
>I am also trying to read the documentation but I have a couple of
>problems right now.
>firstly, I did not find any thing in twisted documentation that
>specifically talks about xml rpc.  am I missing some thing?
>secondly, if I am writing an entire application with its logic in an
>xml rpc server, do I have to create all my classes as instences of xml
>rpc server (just like I create a java servlet or a php script)?  or is
>it that I just create one xml rpc server class which is like the entri
>point for all other classes in the package?
>can you provide a couple of links to howtos or tutorials on creating
>xml rpc servers and clients  with twisted python?  I am also confused
>as to how will I mix the functionality of MySQLDB with twisted python?
>I am asking this because I felt twisted much cleaner to use than the
>modules coming with python itself.  again I may be wrong and some one
>might point me to the possible problems with this aproach in the long
>run.
>regards.
>Krishnakant.

Here's an example Twisted-based XML-RPC server:

  http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py

When using MySQLdb with Twisted, twisted.enterprise.adbapi is useful.
This document explains it and gives some examples of its usage:


  http://twistedmatrix.com/projects/core/documentation/howto/enterprise.html

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


Re: socket read timeout

2007-03-29 Thread Jean-Paul Calderone
On Thu, 29 Mar 2007 07:29:35 +0200, Hendrik van Rooyen <[EMAIL PROTECTED]> 
wrote:
> <[EMAIL PROTECTED]> wrote:
>
>
>>
>> hg> My issue with that is the effect on write: I only want a timeout on
>> hg> read ...  but anyway ...
>>
>> So set a long timeout when you want to write and short timeout when you want
>> to read.
>>
>
>Are sockets full duplex?

Uh, yes.

>
>I know Ethernet isn't.

Not that this is relevant, but unless you're using a hub, ethernet _is_
full duplex.

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


Weird behavior in search in a list

2007-03-29 Thread Su Y
hi all,
I can't understand how this code work, its behavior is really weird
for me...

I want find the first number in extend[] which is larger than num, so
I wrote:
def find(num):
count=0
for elem in extend:
if elem-- 
http://mail.python.org/mailman/listinfo/python-list

Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread Duncan Booth
"Justin Ezequiel" <[EMAIL PROTECTED]> wrote:

> On Mar 29, 4:08 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
>> John Nagle <[EMAIL PROTECTED]> wrote:
>> >  title="

Re: Weird behavior in search in a list

2007-03-29 Thread Su Y
On 3月29日, 下午7时51分, "Su Y" <[EMAIL PROTECTED]> wrote:
> hi all,
> I can't understand how this code work, its behavior is really weird
> for me...
>
> I want find the first number in extend[] which is larger than num, soI wrote:
>
> def find(num):
> count=0
> for elem in extend:
> if elem count+=1
> return count
>
> I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> 5.6],
> it works fine: find(4) returns 3, extend[3] is 4.5.
> But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> 4.6, 3.4, 2.1, 0.3],
> find(4) returns 6, extend[6] is 3.4!
>
> what's going on here? I really can't understand

and I am using Python 2.5 on WinXP.

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

Re: PyPy 1.0: JIT compilers for free and more

2007-03-29 Thread Duncan Booth
Robin Becker <[EMAIL PROTECTED]> wrote:

> I am hugely encouraged by this
> 
> C:\Python\devel\pypy-1.0.0>\python24\python \python\lib\test
\pystone.py
> Pystone(1.1) time for 5 passes = 1.49586
> This machine benchmarks at 33425.6 pystones/second
> 
> C:\Python\devel\pypy-1.0.0>.\pypy-c.exe \python\lib\test\pystone.py
> Pystone(1.1) time for 5 passes = 2.16123e-005
> This machine benchmarks at 2.3135e+009 pystones/second
> 
> 
>:) not

It looks like time.clock() is completely borked.

C:\work\pypy-1.0.0>\python25\python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit 
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import clock, sleep
>>> clock(); sleep(3); clock()
1.6203176660720846e-005
3.000427987355935
>>> clock(); sleep(3); clock()
8.2580051375244619
11.258311321690327
>>> clock(); sleep(3); clock()
16.283118664523005
19.283642753478446
>>> ^Z


C:\work\pypy-1.0.0>pypy-c
Python 2.4.1 (pypy 1.0.0 build 41438) on win32
Type "help", "copyright", "credits" or "license" for more information.
 from time import clock, sleep
 clock(); sleep(3); clock()
1.00337512
1.050338639583
 clock(); sleep(3); clock()
1.103837992871
1.154196831568


Or perhaps it is simply telling you the sort of speeds it hopes to reach 
some day (I wouldn't say no to  9.16021e+009 pystones/second if that was 
what it actually did).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird behavior in search in a list

2007-03-29 Thread Amit Khemka
On 29 Mar 2007 04:51:00 -0700, Su Y <[EMAIL PROTECTED]> wrote:
> hi all,
> I can't understand how this code work, its behavior is really weird
> for me...
>
> I want find the first number in extend[] which is larger than num, so
> I wrote:
> def find(num):
> count=0
> for elem in extend:
> if elem count+=1
> return count
>
> I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> 5.6],
> it works fine: find(4) returns 3, extend[3] is 4.5.
> But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> 4.6, 3.4, 2.1, 0.3],
> find(4) returns 6, extend[6] is 3.4!
>
> what's going on here? I really can't understand

Actually your function "find" returns the number of elements in list
extend, which are smaller than the argument. Perhaps you wanted to
'break' when once the condition is met.

 def find(num):
 count=0
 for elem in extend:
 if elem>num: break
 else: count+=1
 return count

Btw a concise way could be:
def getfirstbigger(num):
for i,x in enumerate(extend):
if x>num:return i
return len(extend)

HTH,


-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird behavior in search in a list

2007-03-29 Thread Amit Khemka
> On 29 Mar 2007 04:51:00 -0700, Su Y <[EMAIL PROTECTED]> wrote:

> > I want find the first number in extend[] which is larger than num, so


> On 3/29/07, Amit Khemka <[EMAIL PROTECTED]> wrote:
> Btw a concise way could be:
> def getfirstbigger(num):
> for i,x in enumerate(extend):
> if x>num:return i
> return len(extend)

I forgot to add that you can as well 'return' the the item (along with
the index), but in case all the items in the list are smaller than the
argument, what return value do you require?
-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python automatic testing: mocking an imported module?

2007-03-29 Thread [EMAIL PROTECTED]
On Mar 27, 9:13 pm, "Chris Lasher" <[EMAIL PROTECTED]> wrote:
> On Mar 27, 6:18 pm, "Silfheed" <[EMAIL PROTECTED]> wrote:
>
> > Heyas
>
> > So we have the following situation: we have a testee.py that we want
> > to automatically test out and verifiy that it is worthy of being
> > deployed.  We want our tester.py to test the code for testee.py
> > without changing the code for testee.py.  testee.py has a module in it
> > that we want to mock in some tests and in others use the real module.
>
> I think you mean "testee.py *imports* a module", rather than "has a
> module in it". Semantics but I was thrown off by this at first.
>
> Why not write tests for the module that testee.py imports (here called
> "foo.py")? If you write out the tests and foo.py passes to spec, then
> you should feel confident it will work correctly with testee.py. Never
> trust it; always play paranoid coder, but feel comfortable enough
> using it.
>
> After all, why should you feel comfortable using modules in the
> standard library? Nobody guarantees bugs don't still lurk in there
> (heck, c.l.p just found one inpdbtoday),

A slight correction. At present it looks like the bug is in Python,
and its handling after setting the current frame's f_lineno when it
refers to byte code offset 0, not pdb. And if you scan c.l.p for
another oddity in pdb with respect to tracebacks, there is possibly
another bug in Python (not strictly pdb).

> however, they have unit
> tests out the wazzoo that demonstrate, to the best of our knowledge,
> the module works to spec.

Actually, as far as I know pdb *doesn't* have any unit tests! (pydb
does though ;-)

But all this nit-picking aside, I do agree with what you have to say
most whole heartedly. (And I'd say maybe a couple more unit tests for
Python to cover these bugs are in order.)

> If that approach is good enough for the
> standard library, wouldn't it be good enough for you?
>
> Chris


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


Re: Weird behavior in search in a list

2007-03-29 Thread Josh

"Su Y" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On 3ÔÂ29ÈÕ, ÏÂÎç7ʱ51·Ö, "Su Y" <[EMAIL PROTECTED]> wrote:
> hi all,
> I can't understand how this code work, its behavior is really weird
> for me...
>
> I want find the first number in extend[] which is larger than num, soI 
> wrote:
>
> def find(num):
> count=0
> for elem in extend:
> if elem count+=1
  else:
 break
> return count
>
you need to break out of the loop when you first encounter num>elem. The 
reason it works in your sorted list scenario is because elem will be > num, 
always, after some point. It won't be in your unsorted list.

I've added the else: break in your code above
j


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

Re: Weird behavior in search in a list

2007-03-29 Thread Michael Bentley

On Mar 29, 2007, at 6:51 AM, Su Y wrote:
>
> I want find the first number in extend[] which is larger than num, so
> I wrote:
> def find(num):
> count=0
> for elem in extend:
> if elem count+=1
> return count
>
> I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> 5.6],
> it works fine: find(4) returns 3, extend[3] is 4.5.
> But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> 4.6, 3.4, 2.1, 0.3],
> find(4) returns 6, extend[6] is 3.4!
>
> what's going on here? I really can't understand

find() loops through the list, and every time it finds a value less  
than num it increments count.  So in your second example the values  
1.1, 2.3, 3.2,  3.4, 2.1, and 0.3 are all less than 4, which means  
count will be 6.

As you learned, a sorted list behaves as you expect.  So one approach  
is to sort your list first.  But another perhaps better approach is  
to do something like:

def find(num):
# check to make sure there *is* a value greater than num
if max(extend) > num:
# then return the smallest value that is greater than num
return min([x for x in extend if x > num])
else:
return None

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


Re: Weird behavior in search in a list

2007-03-29 Thread Amit Khemka
On 3/29/07, Michael Bentley <[EMAIL PROTECTED]> wrote:
>
> On Mar 29, 2007, at 6:51 AM, Su Y wrote:
> >
> > I want find the first number in extend[] which is larger than num, so


> def find(num):
> # check to make sure there *is* a value greater than num
> if max(extend) > num:
> # then return the smallest value that is greater than num
> return min([x for x in extend if x > num])
> else:
> return None

I think OP wants the first value in the list greater than 'num' not
the smallest greater value in the list.

cheers,
-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird behavior in search in a list

2007-03-29 Thread Su Y
On 3月29日, 下午8时22分, Michael Bentley <[EMAIL PROTECTED]> wrote:
> On Mar 29, 2007, at 6:51 AM, Su Y wrote:
>
>
>
>
>
> > I want find the first number in extend[] which is larger than num, so
> > I wrote:
> > def find(num):
> > count=0
> > for elem in extend:
> > if elem > count+=1
> > return count
>
> > I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> > 5.6],
> > it works fine: find(4) returns 3, extend[3] is 4.5.
> > But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> > 4.6, 3.4, 2.1, 0.3],
> > find(4) returns 6, extend[6] is 3.4!
>
> > what's going on here? I really can't understand
>
> find() loops through the list, and every time it finds a value less
> than num it increments count.  So in your second example the values
> 1.1, 2.3, 3.2,  3.4, 2.1, and 0.3 are all less than 4, which means
> count will be 6.
>
> As you learned, a sorted list behaves as you expect.  So one approach
> is to sort your list first.  But another perhaps better approach is
> to do something like:
>
> def find(num):
> # check to make sure there *is* a value greater than num
> if max(extend) > num:
> # then return the smallest value that is greater than num
> return min([x for x in extend if x > num])
> else:
> return None
>
> Hope this helps,
> Michael

oh yes, it's the "break" I forgot... Thank you, it helps me a lot!

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

Re: PDB does not allow jumping to first statement?

2007-03-29 Thread [EMAIL PROTECTED]
On Mar 28, 6:05 pm, "Chris Lasher" <[EMAIL PROTECTED]> wrote:
> I have submitted this as a bug via SourceForge:
>  func=detail&atid=105470&aid=1689458&group_id=5470>
> or if munged
> 
>
> ThePythonfolks would like a test case and/or a patch. This is well
> beyond my ken as a humblePythonuser. Could anybody more
> knowledgeable please contribute one or both? Duncan or Rocky, would
> you be able to spare time and effort?
>
> Chris

First and foremost, thanks for submitting the bug report!

Alas, I don't use Python much anymore in day-to-day activities. Ruby
rules! However some weekend (when I'm not doing work) I'll try to find
time to conjure up an example.

But here's a sketch of how I think a small test case would work. One
would use sys.settrace() to set up the mechanism to get the current
frame after each statement gets run. In the function, say bugcheck(),
which used as the hook given to sys.settrace(), if the caller's
f_lineno is not the first statement, one would set it to the first
statement noting that the reassignment has happened so we don't loop
indefinitely. Then one would return from the function which will let
the program do a step and check what value of f_lineno appears in the
subsequent calls of bugcheck().

Alternatively one could write a .pdbrc which basically issues the
"step" and "jump" commands and prints out the line number. (In pydb or
gdb the command to print the current line would be  "info line"; in
pdb I'm not sure what the best command is - "list"?, "bt?

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


Re: Long way around UnicodeDecodeError, or 'ascii' codec can't decode byte

2007-03-29 Thread Paul Boddie
On 29 Mar, 06:26, "Oleg  Parashchenko" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm working on an unicode-aware application. I like to use "print" to
> debug programs, but in this case it was nightmare. The most popular
> result of "print" was:
>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xXX in position
> 0: ordinal not in range(128)

What does sys.stdout.encoding say?

> I spent two hours fixing it, and I hope it's done. The solution is one
> of the ugliest hack I ever written, but it solves the pain. The full
> story and the code is in my blog:
>
> http://uucode.com/blog/2007/03/23/shut-up-you-dummy-7-bit-python/

Calling sys.setdefaultencoding might not even help in this case, and
the consensus is that it may be harmful to your code's portability
[1]. Writing output to a terminal may be influenced by your locale,
but I'm not convinced that going through all the locale settings and
setting the character set is the best approach (or even the right
one).

What do you get if you do this...?

import locale
locale.setlocale(locale.LC_ALL, "")
print locale.getlocale()

What is your terminal encoding?

Usually, if I'm wanting to print Unicode objects, I explicitly encode
them into something I know the terminal will support. The codecs
module can help with writing Unicode to streams in different
encodings, too.

Paul

[1] http://groups.google.com/group/comp.lang.python/msg/431017a4cb4bb8ea

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


Re: Finding User Profile path

2007-03-29 Thread kyosohma
On Mar 29, 2:50 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
>
> > I am trying to query our domain to get a list of our users profile
> > locations. I thought I might be able to use WMI, but I can't get it to
> > work.
>
> Can you be a bit more specific: did WMI itself not work? Or the
> Python WMI module? What were the problems? (All this, obviously,
> if you're interested in pursuing that path).
>
> I am using a Windows XP Pro workstation and Python 2.4 on a
>
> > mixed environment of Debian Linux (with Samba) and Windows servers. We
> > are in the process of moving the user profiles from an NT box to a
> > Debian box, but due to the many different servers in the organization,
> > it is a pain to keep track of which have been moved and which haven't.
>
> Have a look at the win32net module from the pywin32
> extensions, specifically functions like NetUserGetInfo
> and NetUserSetInfo. You have to pick your USER_INFO a
> bit (look around the MSDN pages) but I think you can do
> what you're after.
>
> TJG

Thanks for the reply. One of my co-workers thought I could do
something like this:

c = wmi.WMI()
for i in c.Win32_UserAccount(Name=user):
# Get user paths somehow.

I messed around with that, but I think he was mistaken. It has lots of
good info, but not what I need.

I apologize for not being specific. I will look at those win32net
functions.

Mike

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


Re: Modal value of an array

2007-03-29 Thread bearophileHUGS
Alex Martelli:
> >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
> >>> max(foo, key=foo.count)

It's a very nice solution, the shortest too. But I think it's better
to develop your own well tested and efficient stats module (and there
is one already done that can be found around) and import it when you
need functions, instead of using similar onliners or re-writing code.
As you know your solution becomes rather slow if the list is quite
long, and it works with lists only.
This uses more memory but it's probably much faster for longer
interables:

from collections import defaultdict

def mode(seq):
freqs = defaultdict(int)
for el in seq:
freqs[el] += 1
return max(freqs.itervalues())


Generally you may want to know what's the mode element(s) too:

def mode2(seq):
freqs = defaultdict(int)
for el in seq:
freqs[el] += 1
maxfreq = max(freqs.itervalues())
mode_els = [el for el,f in freqs.iteritems() if f == maxfreq]
return maxfreq, mode_els

foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
print mode(foo)
print mode2(foo)

Bye,
bearophile

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


Weird gcc behaviour with function pointer types

2007-03-29 Thread greg
In my quest to eliminate C compiler warnings from
Pyrex output, I've discovered some utterly bizarre
behaviour from gcc 3.3.

The following code:

   void g(struct foo *x) {
   }

   void f(void) {
 void (*h)(struct foo *);
 h = g;
   }

produces the following warning:

   blarg.c: In function `f':
   blarg.c:6: warning: assignment from incompatible pointer type

However, adding the following line at the top:

   typedef struct foo Foo;

makes the warning go away. The mere *presence* of
the typedef is all that's needed -- it doesn't even
have to be used.

This looks like a bug in gcc to me -- what do people
think?

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


Re: YouTube showing repr() of a tuple

2007-03-29 Thread Daniel Nogradi
> Thought this might amuse some of you:
>
> 
>
> I'd heard that YouTube uses Python, but it's fun to see proof of that,
> even if it comes in the form of a minor bug.


But their web frontend is (probably) in php:

http://youtube.com/results.php?search_query=korect+my+speling
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can I clear a dictionary in python

2007-03-29 Thread Larry Bates
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Larry Bates  <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> I create a dictionary like this
>>> myDict = {}
>>>
>>> and I add entry like this:
>>> myDict['a'] = 1
>>> but how can I empty the whole dictionary?
>> just point myDict to an empty dictionary again
>>
>> myDict={}
> 
> Go back and read Christian's post, then post a followup explaning why his
> solution is better than yours.  Your explanation should use id().

I believe he (as many new to Python do) are mired in old
programming thinking that variables "contain" things.
As I'm sure you kno, variables point to things in Python.
I don't believe that there are lots of other objects
pointing to this dictionary.  Perhaps the OP can clarify
for us.  If there aren't other objects pointing to
this dictionary it would make NO sense to iterate over a
dictionary and delete all the keys/values so I tried to read
between the lines and answer what I believe the OP thought he
was asking.  BTW-I didn't see you posting an answer to what
you thought was the "correct" question, just criticizing me
for taking the time to answer what I perceived the OP was
asking.

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


Re: Finding User Profile path

2007-03-29 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> One of my co-workers thought I could do
> something like this:
> 
> c = wmi.WMI()
> for i in c.Win32_UserAccount(Name=user):
> # Get user paths somehow.
> 
> I messed around with that, but I think he was mistaken. It has lots of
> good info, but not what I need.
> 
> I apologize for not being specific. I will look at those win32net
> functions.
> 
> Mike

Might depend on what you mean by "profile" but would the
users' homeDirectory/homeDrive active directory attributes
or the profilePath be of use here? If so, they're fairly
easy to get hold of.

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


Problem with class variables

2007-03-29 Thread Dag
I have a problem which is probaly very simple to solve, but I can't
find a nice solution.
I have the following code 

class Test:
def __init__(self):
self.a=[1,2,3,4]
self.b=self.a
def swap(self):
self.a[0],self.a[3]=self.a[3],self.a[0]
def prnt(self):
print self.a
print self.b
c=Test()
c.swap()
c.prnt()

which returns 
[4,2,3,1]
[4,2,3,1]

Now I understand why it is doing this, but it's not what I want.  How to
I get it to return
[4,2,3,1]
[1,2,3,4]

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


gettext files manager

2007-03-29 Thread [EMAIL PROTECTED]
Does anyone know if Python gettext module or something else in Python
can "manage" po/mo files - list all strings from po/mo, show
untranslated, fuzzy strings ? I need something like that for a
"translations manager" :)

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


Re: urllib timeout issues

2007-03-29 Thread supercooper
On Mar 27, 4:50 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 27 Mar 2007 17:41:44 -0300, supercooper <[EMAIL PROTECTED]>
> escribió:
>
>
>
> > On Mar 27, 3:13 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
> >> En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <[EMAIL PROTECTED]>
> >> escribió:
>
> >> > I am downloading images using the script below. Sometimes it will go
> >> > for 10 mins, sometimes 2 hours before timing out with the following
> >> > error:
>
> >> > urllib.urlretrieve(fullurl, localfile)
> >> > IOError: [Errno socket error] (10060, 'Operation timed out')
>
> >> > I have searched this forum extensively and tried to avoid timing out,
> >> > but to no avail. Anyone have any ideas as to why I keep getting a
> >> > timeout? I thought setting the socket timeout did it, but it didnt.
>
> >> You should do the opposite: timing out *early* -not waiting 2 hours- and
> >> handling the error (maybe using a queue to hold pending requests)
>
> >> --
> >> Gabriel Genellina
>
> > Gabriel, thanks for the input. So are you saying there is no way to
> > realistically *prevent* the timeout from occurring in the first
>
> Exactly. The error is out of your control: maybe the server is down,
> irresponsive, overloaded, a proxy has any problems, any network problem,
> etc.
>
> > place?  And by timing out early, do you mean to set the timeout for x
> > seconds and if and when the timeout occurs, handle the error and start
> > the process again somehow on the pending requests?  Thanks.
>
> Exactly!
> Another option: Python is cool, but there is no need to reinvent the
> wheel. Use wget instead :)
>
> --
> Gabriel Genellina

Gabriel...thanks for the tip on wget...its awesome! I even built it on
my mac. It is working like a champ for hours on end...

Thanks!

chad




import os, shutil, string

images = [['34095d2','Nashoba'],
['34096c8','Nebo'],
['36095a4','Neodesha'],
['33095h7','New Oberlin'],
['35096f3','Newby'],
['35094e5','Nicut'],
['34096g2','Non'],
['35096h6','North Village'],
['35095g3','Northeast Muskogee'],
['35095g4','Northwest Muskogee'],
['35096f2','Nuyaka'],
['34094e6','Octavia'],
['36096a5','Oilton'],
['35096d3','Okemah'],
['35096c3','Okemah SE'],
['35096e2','Okfuskee'],
['35096e1','Okmulgee Lake'],
['35095f7','Okmulgee NE'],
['35095f8','Okmulgee North'],
['35095e8','Okmulgee South'],
['35095e4','Oktaha'],
['34094b7','Old Glory Mountain'],
['36096a4','Olive'],
['34096d3','Olney'],
['36095a6','Oneta'],
['34097a2','Overbrook']]

wgetDir = 'C:/Program Files/wget/o'
exts = ['tif', 'tfw']
url = 'http://www.archive.org/download/'
home = '//fayfiler/seecoapps/Geology/GEOREFRENCED IMAGES/TOPO/Oklahoma
UTMz14meters NAD27/'

for image in images:
for ext in exts:
fullurl = url + 'usgs_drg_ok_' + image[0][:5] + '_' + image[0]
[5:] + '/o' + image[0] + '.' + ext
os.system('wget %s -t 10 -a log.log' % fullurl)
shutil.move(wgetDir + image[0] + '.' + ext, home + 'o' +
image[0] + '_' + string.replace(image[1], ' ', '_') + '.' + ext)

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


Re: Problem with class variables

2007-03-29 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Dag wrote:

> I have a problem which is probaly very simple to solve, but I can't
> find a nice solution.
> I have the following code 
> 
> class Test:
> def __init__(self):
> self.a=[1,2,3,4]
> self.b=self.a
  self.b = list(self.a)

BTW this is about instance variable, not class variables.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding User Profile path

2007-03-29 Thread kyosohma
On Mar 29, 8:23 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > One of my co-workers thought I could do
> > something like this:
>
> > c = wmi.WMI()
> > for i in c.Win32_UserAccount(Name=user):
> > # Get user paths somehow.
>
> > I messed around with that, but I think he was mistaken. It has lots of
> > good info, but not what I need.
>
> > I apologize for not being specific. I will look at those win32net
> > functions.
>
> > Mike
>
> Might depend on what you mean by "profile" but would the
> users' homeDirectory/homeDrive active directory attributes
> or the profilePath be of use here? If so, they're fairly
> easy to get hold of.
>
> TJG

Yes. It's the homeDirectory as you say. Once again the IT community's
use of multiple terms for the same thing has bitten me.

Mike

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


Re: Problem with class variables

2007-03-29 Thread kyosohma
On Mar 29, 8:43 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, Dag wrote:
> > I have a problem which is probaly very simple to solve, but I can't
> > find a nice solution.
> > I have the following code
>
> > class Test:
> > def __init__(self):
> > self.a=[1,2,3,4]
> > self.b=self.a
>
>   self.b = list(self.a)
>
> BTW this is about instance variable, not class variables.
>
> Ciao,
> Marc 'BlackJack' Rintsch

One of the many ways to do this:

class Test:
def __init__(self):
self.a=[1,2,3,4]
#self.b=self.a
def swap(self):
self.a[0],self.a[3]=self.a[3],self.a[0]
return self.a
def prnt(self):
print self.a
x = self.swap()
print x

c=Test()
c.prnt()


Mike

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


Re: Finding User Profile path

2007-03-29 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> On Mar 29, 8:23 am, Tim Golden <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> One of my co-workers thought I could do
>>> something like this:
>>> c = wmi.WMI()
>>> for i in c.Win32_UserAccount(Name=user):
>>> # Get user paths somehow.
>>> I messed around with that, but I think he was mistaken. It has lots of
>>> good info, but not what I need.
>>> I apologize for not being specific. I will look at those win32net
>>> functions.
>>> Mike
>> Might depend on what you mean by "profile" but would the
>> users' homeDirectory/homeDrive active directory attributes
>> or the profilePath be of use here? If so, they're fairly
>> easy to get hold of.
>>
>> TJG
> 
> Yes. It's the homeDirectory as you say. Once again the IT community's
> use of multiple terms for the same thing has bitten me.

I take it you're OK for getting things out of AD?

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


Re: upgrading python (and other modules)

2007-03-29 Thread kyosohma
On Mar 29, 1:14 am, Astan Chee <[EMAIL PROTECTED]> wrote:
> Forget I asked this question.
> I've solved it using wxPython 2.6.3.3
> Cheers
>
> Astan Chee wrote:
> > Hi,
> > I was once using python 2.4 in win2k with wxPython 2.4.2.4 (if im not
> > mistaken) with it.
> > Now i've upgraded to winXP and am using python 2.5 with wxPython 2.8.1.1.
> > The problem Im currently having is that in my code:
>
> > from wxPython.wx import *
> > from wxPython.grid import *
> > from wxPython.html import *
>
> > no longer works. An error/warning appears:
>
> > Warning (from warnings module):
> >   File "C:\stanc_home\WHIP\whip.py", line 7
> > from wxPython.wx import *
> > DeprecationWarning: The wxPython compatibility package is no longer
> > automatically generated or activly maintained.  Please switch to the wx
> > package as soon as possible.
>
> > Traceback (most recent call last):
> >   File "C:\stanc_home\WHIP\whip.py", line 10, in 
> > from wxPython.html import *
> >   File "C:\Python25\lib\site-packages\wx-2.8-msw-ansi\wxPython\html.py",
> > line 151, in 
> > wxHtmlWindowEvent = wx.html.HtmlWindowEvent
> > AttributeError: 'module' object has no attribute 'HtmlWindowEvent'
>
> > How should I be importing in the new wx?
> > Thanks!
> > Astan

The wxPython community typically recommends NOT doing a "from
wxPython.wx import *" due to the increased likelihood of namespace
poisoning. If you really want to know how to do it anyway, you should
contact the wxPython users group directly at http://wxpython.org/maillist.php

Mike

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


Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread Paul McGuire
On Mar 29, 1:50 am, John Nagle <[EMAIL PROTECTED]> wrote:
> Here's a construct with which BeautifulSoup has problems.  It's
> from "http://support.microsoft.com/contactussupport/?ws=support";.
>
> This is the original:
>
> http://www.microsoft.com/usability/enroll.mspx";
>  id="L_75998"
>  title="".  So all that following stuff is from what
> follows the next "-->" which terminates a comment.
>

No, that comment is inside a quoted string, so it should be ok.

If you are just trying to extract  tags, this pyparsing
scraper gets them, including this problematic one:


import urllib
from pyparsing import makeHTMLTags

pg = urllib.urlopen("http://support.microsoft.com/contactussupport/?
ws=support")
htmlSrc = pg.read()
pg.close()

# only take first tag returned from makeHTMLTags, not interested in
# closing  tags
anchorTag = makeHTMLTags("A")[0]

for a in anchorTag.searchString(htmlSrc):
if "title" in a:
print "Title:", a.title
print "HREF:", a.href
# or use this statement to dump the complete tag contents
# print a.dump()
print

Prints:
Title: 

Re: Problem with class variables

2007-03-29 Thread Thomas Krüger
Dag schrieb:
> I have a problem which is probaly very simple to solve, but I can't
> find a nice solution.
> I have the following code 
> 
> class Test:
> def __init__(self):
> self.a=[1,2,3,4]
> self.b=self.a
> def swap(self):
> self.a[0],self.a[3]=self.a[3],self.a[0]
> def prnt(self):
> print self.a
> print self.b
> c=Test()
> c.swap()
> c.prnt()
> 
> which returns 
> [4,2,3,1]
> [4,2,3,1]
> 
> Now I understand why it is doing this, but it's not what I want.  How to
> I get it to return
> [4,2,3,1]
> [1,2,3,4]
> 
> Dag 

Use a copy of self.a:
self.b = self.a[:]

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


Re: YouTube showing repr() of a tuple

2007-03-29 Thread Leif K-Brooks
Leif K-Brooks wrote:
> Thought this might amuse some of you:
> 
> 

Better example:


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


Re: Finding User Profile path

2007-03-29 Thread kyosohma
On Mar 29, 9:05 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Mar 29, 8:23 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote:
> >>> One of my co-workers thought I could do
> >>> something like this:
> >>> c = wmi.WMI()
> >>> for i in c.Win32_UserAccount(Name=user):
> >>> # Get user paths somehow.
> >>> I messed around with that, but I think he was mistaken. It has lots of
> >>> good info, but not what I need.
> >>> I apologize for not being specific. I will look at those win32net
> >>> functions.
> >>> Mike
> >> Might depend on what you mean by "profile" but would the
> >> users' homeDirectory/homeDrive active directory attributes
> >> or the profilePath be of use here? If so, they're fairly
> >> easy to get hold of.
>
> >> TJG
>
> > Yes. It's the homeDirectory as you say. Once again the IT community's
> > use of multiple terms for the same thing has bitten me.
>
> I take it you're OK for getting things out of AD?
>
> TJG

Actually no. Our organization does not use Active Directory. In fact,
the server I need to query happens to be an NT 4.0 box. We do have a
Win2k Server, but it is for specialized services.

Mike

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


Re: Creating a new data structure while filtering its data origin.

2007-03-29 Thread FlipFish2007
On Mar 28, 4:44 pm, <[EMAIL PROTECTED]> wrote:
> Hi everyone.
>
> I'm trying to work with very simple data structures but I'm stuck in the very 
> first steps. If someone has the luxury of a few minutes and can give an 
> advice how to resolve this, I'll really appreciate it.
>
> 1- I have a list of tuples like this:
> lista= [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2), (168, 
> 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203, 141, 1), (562, 
> 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568, 142, 2), (568, 
> 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]
> and I want to end with a dict like this:
> {141: {1: [203, 213, 201], 2: [168, ], 3: [162, ]}, 142: {1: [503, 513, 501], 
> 2: [568, ], 4: [562, ]}}
>  the logic of the final output:
>  a) the outer dict's key is a set() of the 2rd value of the input.
>  b) the inner dict's key is a set() of the 3th value for tuples which 3rd 
> value equals a).
>  c) the inner list will be fill up with the 1st value of every tuple which 
> 3rd value equals b) and its 2rd value equals a).
>
> So far, the only thing it seems I can achieve is the first part:
> outer_dict = dict([(x,dict()) for x in set(row[1] for row in lista)])
>
> >From then on, I'm starting to get tired after several successful failures (I 
> >tried with itertools, with straight loops ...) and I don't know which can be 
> >the easier way to get that final output.
>
> Thanks in advance.

dict([[b,dict([[k, dict([[x, None] for (x,y,z) in lista if y==b and
z==k]).keys()] for (i,j,k) in lista if j==b])] for (a,b,c) in lista])

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


make RE more cleaver to avoid inappropriate : sre_constants.error: redefinition of group name

2007-03-29 Thread aspineux

I want to parse

'[EMAIL PROTECTED]' or '<[EMAIL PROTECTED]>' and get the email address [EMAIL 
PROTECTED]

the regex is

r'<[EMAIL PROTECTED]>|[EMAIL PROTECTED]'

now, I want to give it a name

r'<(?P[EMAIL PROTECTED])>|(?P[EMAIL PROTECTED])'

sre_constants.error: redefinition of group name 'email' as group 2;
was group 1

BUT because I use a | , I will get only one group named 'email' !

Any comment ?

PS: I know the solution for this case is to use  r'(?P<)?(?P
[EMAIL PROTECTED])(?(lt)>)'

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


A nice way to use regex for complicate parsing

2007-03-29 Thread aspineux

My goal is to write a parser for these imaginary string from the SMTP
protocol, regarding RFC 821 and 1869.
I'm a little flexible with the BNF from these RFC :-)
Any comment ?

tests=[ 'MAIL FROM:<[EMAIL PROTECTED]>',
'MAIL FROM:[EMAIL PROTECTED]',
'MAIL FROM:<[EMAIL PROTECTED]> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:[EMAIL PROTECTED] SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com>',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com SIZE=1234
[EMAIL PROTECTED]',
]

def RN(name, regex):
"""protect using () and give an optional name to a regex"""
if name:
return r'(?P<%s>%s)' % (name, regex)
else:
return r'(?:%s)' % regex


regex={}

#  ::=  "."  "."  "." 
regex['dotnum']=RN(None, r'[012]?\d?\d\.[012]?\d?\d\.[012]?\d?\d\.
[012]?\d?\d' % regex)
#  ::=  |  "." 
regex['dot_string']=RN(None, r'[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*' %
regex)
#  ::=   |  "." 
regex['domain']=RN('domain', r'%(dotnum)s|%(dot_string)s' % regex)
#  ::= any one of the 128 ASCII characters except , , quote
("), or backslash (\)
regex['q']=RN(None, r'[^\n\r"\\]' % regex)
#  ::= any one of the 128 ASCII characters (no exceptions)
regex['x']=RN(None, r'.' % regex)
#  ::=  "\"  | "\"   |  |  
regex['qtext']=RN(None, r'(?:\\%(x)s|%(q)s)+' % regex)
#  ::=  """  """
regex['quoted_string']=RN('quoted_string', r'"%(qtext)s"' % regex)
#  ::=  | 
regex['local_part']=RN('local_part', r'%(quoted_string)s|%
(dot_string)s' % regex)
#  ::=  "@" 
regex['mailbox']=RN('mailbox', r'%(local_part)[EMAIL PROTECTED](domain)s' % 
regex)
#  ::= "<" [  ":" ]  ">"
# also accept address without <>
regex['path']=RN('path', r'(?P<)?%(mailbox)s(?(path_lt)>)' %
regex)
# esmtp-keyword::= (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
regex['esmtp_keyword']=RN(None, r'[a-zA-Z0-9][-a-zA-Z0-9]*' % regex)
# esmtp-value  ::= 1*http://mail.python.org/mailman/listinfo/python-list


Islam, the Religion of Ease

2007-03-29 Thread moslim
Excuse me!!
Would you stop for a moment?!
O...man...Haven't you thought-one day- about yourself ?
Who has made it?
Have you seen a design which hasn't a designer ?!
Have you seen a wonderful,delicate work without a worker ?!
It's you and the whole universe!..
Who has made them all ?!!
You know who ?.. It's "ALLAH",prise be to him.
Just think for a moment.
How are you going to be after death ?!
Can you believe that this exact system of the universe and all of
these great creation will end in in nothing...just after death!
Have you thought, for a second, How to save your soul from Allah's
punishment?!
Haven't you thought about what is the right religion?!
Read ... and think deeply before you answer..
It is religion of Islam.
It is the religion that Mohammad-peace upon him- the last prophet, had
been sent by.
It is the religion that the right Bible- which is not distorted-has
preached.
Just have a look at The Bible of (Bernaba).
Don't be emstional.
Be rational and judge..
Just look..listen...compare..and then judge and say your word.
We advise you visiting :
http://www.islam-guide.com
http://www.thetruereligion.org
http://www.beconvinced.com
http://www.plaintruth.org
http://english.islamway.com
http://www.todayislam.com
http://www.prophetmuhammed.org
http://www.islamtoday.net/english/
http://www.islamunveiled.org
http://www.islamic-knowledge.com

We willingly recive any inquries at the e-mail :

[EMAIL PROTECTED]

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


Re: how can I clear a dictionary in python

2007-03-29 Thread Bruno Desthuilliers
Larry Bates a écrit :
> Aahz wrote:
>> In article <[EMAIL PROTECTED]>,
>> Larry Bates  <[EMAIL PROTECTED]> wrote:
>>> [EMAIL PROTECTED] wrote:
 I create a dictionary like this
 myDict = {}

 and I add entry like this:
 myDict['a'] = 1
 but how can I empty the whole dictionary?
>>> just point myDict to an empty dictionary again
>>>
>>> myDict={}
>> Go back and read Christian's post, then post a followup explaning why his
>> solution is better than yours.  Your explanation should use id().
> 
> I believe he (as many new to Python do) are mired in old
> programming thinking that variables "contain" things.

Does "he" refer to Christian Tismer ? If so, you may want to use google 
and correct your beliefs (hint: does 'stackless Python' ring a bell ?).

> As I'm sure you kno, variables point to things in Python.

(conceptually) names are keys associated with an object in a given 
namespace. FWIW, be assured that Christians knows this pretty well.

> I don't believe that there are lots of other objects
> pointing to this dictionary.

You just cannot *know* this. This might be true now, this might be false 
now, and this might change anytime. Assuming anything here is the road 
to disaster. Don't assume, do the righ thing.

>  Perhaps the OP can clarify
> for us.  If there aren't other objects pointing to
> this dictionary it would make NO sense to iterate over a
> dictionary and delete all the keys/values

You don't iterate over anything. Dicts being the central datastructure 
in Python, you can bet your ass they are optimized to death (or near 
death). If you have any doubt, then still don't assume : verify (hint: 
import timeit). And yet even if clearing a dict happens to be a bit 
slower than instanciating a new one, rebinding a name and mutating an 
object are still two very different concepts in Python, with very 
different consequences. The OP explicitely asked for clearing a dict, 
not for creating a new one.

> so I tried to read
> between the lines

Why ?

> and answer what I believe the OP thought he
> was asking.

What the OP asked was quite clear, and not subject to any 
interpretation. And the correct answer is obviously not the one you gave.

>  BTW-I didn't see you posting an answer to what
> you thought was the "correct" question, just criticizing me
> for taking the time to answer what I perceived the OP was
> asking.

If you cannot understand the difference between criticism and a friendly 
correction,  nor why you should actually thank the one correcting you 
when you're wrong, I guess there's no point trying explaining why 
correcting wrong answers on newsgroups is actually important.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A nice way to use regex for complicate parsing

2007-03-29 Thread Shane Geiger

It would be worth learning pyparsing to do this.



aspineux wrote:

My goal is to write a parser for these imaginary string from the SMTP
protocol, regarding RFC 821 and 1869.
I'm a little flexible with the BNF from these RFC :-)
Any comment ?

tests=[ 'MAIL FROM:<[EMAIL PROTECTED]>',
'MAIL FROM:[EMAIL PROTECTED]',
'MAIL FROM:<[EMAIL PROTECTED]> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:[EMAIL PROTECTED] SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com>',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com SIZE=1234
[EMAIL PROTECTED]',
]

def RN(name, regex):
"""protect using () and give an optional name to a regex"""
if name:
return r'(?P<%s>%s)' % (name, regex)
else:
return r'(?:%s)' % regex


regex={}

#  ::=  "."  "."  "." 
regex['dotnum']=RN(None, r'[012]?\d?\d\.[012]?\d?\d\.[012]?\d?\d\.
[012]?\d?\d' % regex)
#  ::=  |  "." 
regex['dot_string']=RN(None, r'[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*' %
regex)
#  ::=   |  "." 
regex['domain']=RN('domain', r'%(dotnum)s|%(dot_string)s' % regex)
#  ::= any one of the 128 ASCII characters except , , quote
("), or backslash (\)
regex['q']=RN(None, r'[^\n\r"\\]' % regex)
#  ::= any one of the 128 ASCII characters (no exceptions)
regex['x']=RN(None, r'.' % regex)
#  ::=  "\"  | "\"   |  |  
regex['qtext']=RN(None, r'(?:\\%(x)s|%(q)s)+' % regex)
#  ::=  """  """
regex['quoted_string']=RN('quoted_string', r'"%(qtext)s"' % regex)
#  ::=  | 
regex['local_part']=RN('local_part', r'%(quoted_string)s|%
(dot_string)s' % regex)
#  ::=  "@" 
regex['mailbox']=RN('mailbox', r'%(local_part)[EMAIL PROTECTED](domain)s' % 
regex)
#  ::= "<" [  ":" ]  ">"
# also accept address without <>
regex['path']=RN('path', r'(?P<)?%(mailbox)s(?(path_lt)>)' %
regex)
# esmtp-keyword::= (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
regex['esmtp_keyword']=RN(None, r'[a-zA-Z0-9][-a-zA-Z0-9]*' % regex)
# esmtp-value  ::= 1*

--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: Why doesnt __getattr__ with decorator dont call __get_method in decorator

2007-03-29 Thread glomde

> To get python to run the __get__ method I think you have to call
> __getattr__ explicitly:
> a.__getattr__('test')
>
> If you do:
> a.test
> python follows a different routine: it checks for the existence of the
> attribute, then check if there is a __getattr__ attribute. Now the
> speculative bit: then I conjecture that python assumes that
> __getattr__ is a function with two arguments and directly passes them
> on to it.  Indeed
>
> type(a).__dict__['__getattr__'](a, 'test')
>
> seems to produce the same errors as a.test, whether the instance
> attribute is set or not.
> And this explain why there are too many arguments (error message
> above).
>
> --
> Arnaud

So is this a python bug? I assumed it was seen as function but dont
understand why it is like this. But interesting that if you call
__getattr__ explicitly it works.

Intuitevely I would assumet that the same route should be followed
in both case.

Maybe it is because __getattr__ is called only when you have an
exception.

/T





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


Re: XML/encoding/prolog/python hell...

2007-03-29 Thread fscked
Here is what I currently have. Still missing prolog information and
namespace info. Encoding is irritating me also. :)

import os,sys
import csv
from elementtree.ElementTree import Element, SubElement, ElementTree,
tostring

def indent(elem, level=0):
i = "\n" + level*"  "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + "  "
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i

root = Element("boxes")
myfile = open('ClientsXMLUpdate.csv')
csvreader = csv.reader(myfile)

for row in csvreader:
mainbox = SubElement(root, "box")
r2 = csv.reader(myfile)
b = r2.next()
mainbox.attrib["city"] = b[10]
mainbox.attrib["country"] = b[9]
mainbox.attrib["phone"] = b[8]
mainbox.attrib["address"] = b[7]
mainbox.attrib["name"] = b[6]
mainbox.attrib["pl_heartbeat"] = b[5]
mainbox.attrib["sw_ver"] = b[4]
mainbox.attrib["hw_ver"] = b[3]
mainbox.attrib["date_activated"] = b[2]
mainbox.attrib["mac_address"] = b[1]
mainbox.attrib["boxid"] = b[0]

indent(root)
ElementTree(root).write('test.xml', "UTF-8")

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


What are OOP's Jargons and Complexities

2007-03-29 Thread Xah Lee
What are OOP's Jargons and Complexities

Xah Lee, 20050128

Classes, Methods, Objects

In computer languages, often a function definition looks like this:

subroutine f (x1, x2, ...) {
  variables ...
  do this or that
}

In advanced languages such as LISP family, it is not uncommon to
define functions inside a function. For example:

subroutine f (x1, x2, ...) {
  variables...
  subroutine f1 (x1...) {...}
  subroutine f2 (x1...) {...}
}

Often these f1 f2 inner functions are used inside f, and are not
relevant outside of f. Such power of the language gradually developed
into a style of programing. For example:

subroutine a_surface () {
  coordinatesList = ...;
  subroutine translate (distance) {...}
  subroutine rotate (angle) {..}
}

Such a style is that the a_surface is no longer viewed as a function.
But instead, a boxed set of functions, centered around a piece of
datum. And, all functions for manipulating this piece of datum are all
embodied in this function. For example:

subroutine a_surface (arg) {
  coordinatesList = ...
  subroutine translate (distance) {set coordinatesList to translated
version}
  subroutine rotate (angle) {set coordinatesList to rotated version}
  subroutine return () {return coordinatesList}

  if (no arg) {do nothing}
else { apply arg to coordinatesList }
}

In this way, one uses a_surface as a piece of datum that are bundled
with its own set of functions:

mySurface = a_surface   // assign subroutine to a variable
mySurface(rotate(angle))// now the surface datum has been
rotated
mySurface(translate(distance))  // now its translated
newSurface = mySurface(return())

So now, a_surface is no longer viewed as a subroutine, but a boxed set
of things centered around a piece of datum. All functions that work on
the datum are included in the boxed set. This paradigm possible in
functional languages has refined so much so that it spread to other
groups and became known as Object Oriented Programing, and complete
languages with new syntax catered to such scheme emerged.

In such languages, instead of writing them like this:

mySurface = a_surface;
mySurface(rotate(angle));

the syntax is changed to like this, for example:

mySurface = new a_surface();
mySurface.rotate(angle);

In such languages, the super subroutine a_surface is no longer called
a function or subroutine. It is now called a “Class”. And now the
variable holding the function "mySurface" is now called a “Object”.
Subroutines inside the function a_surface are no longer called inner-
subroutines. They are called “Methods”. The act of assigning a super-
subroutine to a variable is called instantiation.

This style of programing and language has become so fanatical that in
such dedicated languages like Java, everything in the language are
Classes. One can no longer just define a variable or subroutine.
Instead, one defines these super-subroutines (classes) that has inner-
subroutines (methods). Every line of code are now inside such super-
subroutine. And one assigns subroutines to variables inside other
subroutines to create objects. And one calls inner-subroutines
(methods) thru these “object” variables to manipulate the data defined
in the super-subroutine. In this fashion, even basic primitives like
numbers, strings, and lists are no longer atomic entities. They are
now subroutines with inner-subroutines.

For example, in Java, a string is a class String. And inside the class
String, there are Methods to manipulate strings, such as finding the
number of chars, or extracting parts of the string. This can get very
complicated. For example, in Java, there are actually two Classes of
strings: One is String, and the other is StringBuffer. Which one to
use depends on whether you intend to change the datum.

So, a simple code like this in normal languages:

a = "a string";
b = "another one";
c = join(a,b);
print c;

or in lisp style

(set a "a string")
(set b "another one")
(set c (join a b))
(print c)

becomes in Java:

public class test {
  public static void main(String[] args) {
String a = new String("a string");
String b = new String("another one");
StringBuffer c = new StringBuffer(40);
c.append(a); c.append(b);
System.out.println(c.toString());
}
}

Here, the “new String” creates a String object. The “new
StringBuffer(40)” creates the changeable string object StringBuffer,
with room for 40 chars. “append” is a method of StringBuffer. It is
used to join two Strings.

Notice the syntax “c.append(a)”, which we can view it as calling a
inner-subroutine “append”, on a super-subroutine that has been
assigned to c, where, the inner-subroutine modifies the inner datum by
appending the value of a to it.

And in the above Java example, StringBuffer class has another method
“toString()” used to convert this into a String Class, necessary
because System.out.println's parameter requires a String type, not
StringBuffer.

For a example of the complexity of classes and methods, see the Java

inf class (was: gmpy floating point exception)

2007-03-29 Thread Martin Manns
On Thu, 29 Mar 2007 00:57:03 -0700
[EMAIL PROTECTED] (Alex Martelli) wrote:

> Martin Manns <[EMAIL PROTECTED]> wrote:
> > 2) Is there any inf type around with
> > a + inf == inf
> > inf > a (as long as a != inf)
> > etc.
> > that works with any other type?
> 
> You mean something like:
> 
> class inf(object):
> def __radd__(self, other): return self
> def __gt__(self, other): return self is not other
> # etc
> inf = inf()

Actually, I meant something a bit more sophisticated:
a=inf()
b=inf()
c=-inf()
d=1e9
e=numpy.float64(1e9)
f=gmpy.mpq(1,2)

a > b   OverflowError (AmbiguousValueError?)
a == b  OverflowError (AmbiguousValueError?)
a + b   inf (New inf instance)
a + c   OverflowError (AmbiguousValueError?)
a + d   a
max(a,b)inf (New inf instance)
max(a,c)a
max(a,d)a
max(a,b) == a   OverflowError (AmbiguousValueError?)
max(a,b) == b   OverflowError (AmbiguousValueError?)
max(a,b) > aOverflowError (AmbiguousValueError?)
max(a,b) >= a   True (if somehow possible)
max(a,b) < aFalse (if somehow possible)
a is b  False
a > c   True
a == -a False
a == -c OverflowError (AmbiguousValueError?)
a > d   True
a > e   True
c > f   False

The idea is a class that permits non-ambiguous comparisons but throws
exceptions if ambiguous comparisons are made. Since I think that
setting up such a class involves quite some effort (especially
considering things such as a + a) I just wanted to know if something
similar is already around. I am aware of the PEP 326 but I feel that it
does not really address the problem.

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


Re: make RE more cleaver to avoid inappropriate : sre_constants.error: redefinition of group name

2007-03-29 Thread attn . steven . kuo
On Mar 29, 7:22 am, "aspineux" <[EMAIL PROTECTED]> wrote:
> I want to parse
>
> '[EMAIL PROTECTED]' or '<[EMAIL PROTECTED]>' and get the email address [EMAIL 
> PROTECTED]
>
> the regex is
>
> r'<[EMAIL PROTECTED]>|[EMAIL PROTECTED]'
>
> now, I want to give it a name
>
> r'<(?P[EMAIL PROTECTED])>|(?P[EMAIL PROTECTED])'
>
> sre_constants.error: redefinition of group name 'email' as group 2;
> was group 1
>
> BUT because I use a | , I will get only one group named 'email' !
>
> Any comment ?
>
> PS: I know the solution for this case is to use  r'(?P<)?(?P
> [EMAIL PROTECTED])(?(lt)>)'



Regular expressions, alternation, named groups ... oh my!

It tends to get quite complex especially if you need
to reject cases where the string contains a left bracket
and not the right, or visa-versa.

>>> pattern = re.compile(r'(?P<[EMAIL PROTECTED]>|(?>> PROTECTED](?!>))')
>>> for email in ('[EMAIL PROTECTED]' , '<[EMAIL PROTECTED]>', '<[EMAIL 
>>> PROTECTED]'):
... matched = pattern.search(email)
... if matched is not None:
... print matched.group('email')
...
[EMAIL PROTECTED]
<[EMAIL PROTECTED]>


I suggest you try some other solution (maybe pyparsing).

--
Hope this helps,
Steven

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


What is the timeout value of HTTP

2007-03-29 Thread ken
Can you please tell me what is the timeout value of httplib.HTTP?

i.e. how long python will wait for a response in the below code?

   h = httplib.HTTP(self.url, 8080)
h.putrequest('GET', '/sample/?url=' + self.url)
h.endheaders()

Thank you.

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


Re: Creating a new data structure while filtering its data origin.

2007-03-29 Thread attn . steven . kuo
On Mar 28, 1:44 pm, <[EMAIL PROTECTED]> wrote:
> Hi everyone.
>
> I'm trying to work with very simple data structures but I'm stuck in the very 
> first steps. If someone has the luxury of a few minutes and can give an 
> advice how to resolve this, I'll really appreciate it.
>
> 1- I have a list of tuples like this:
> lista= [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2), (168, 
> 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203, 141, 1), (562, 
> 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568, 142, 2), (568, 
> 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]
> and I want to end with a dict like this:
> {141: {1: [203, 213, 201], 2: [168, ], 3: [162, ]}, 142: {1: [503, 513, 501], 
> 2: [568, ], 4: [562, ]}}


(snipped)

I think you can use, with python 2.5, defaultdict for
this.  I only have access to 2.4.4 here, so my facsimile
is:

class defaultd(dict):
def __getitem__(self, k):
if k not in self:
self[k] = defaultd()
return dict.__getitem__(self, k)

lista = [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2),
(168, 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203,
141,
1), (562, 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568,
142, 2), (568, 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]

dd = defaultd()

for value, outerkey, innerkey in lista:
li = dd[outerkey].setdefault(innerkey, [])
if value not in li:
li.insert(0, value)
# or, li.append(value) if you want to reverse order

print dd

I happen to like the "autovivification" feature
found in perl and was pleased to see defaultdict in
python 2.5.  OTOH, python programmers more experienced
than I might see this and run away screaming.


--
Hope this helps,
Steven

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


Re: Finding User Profile path

2007-03-29 Thread Tim Golden
[resending as the original seems to have got lost;
apologies if it appears as a duplicate]

At the risk of insulting your intelligence, here's a
rough-and-ready non-AD solution (culled from some code I
had somewhere):


import win32net
import win32netcon

dc = win32net.NetGetAnyDCName (None, None)
#
# Or your specific server name, if you want
#

resume = 0
while 1:
   (_users, total, resume) = \
 win32net.NetUserEnum (
   dc,
   3,
   win32netcon.FILTER_NORMAL_ACCOUNT,
   resume,
   win32netcon.MAX_PREFERRED_LENGTH
 )
   for _user in _users:
 print _user['name'], _user['home_dir'], _user['profile']
   if not resume:
 break



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


Re: What is the timeout value of HTTP

2007-03-29 Thread Alex Martelli
ken <[EMAIL PROTECTED]> wrote:

> Can you please tell me what is the timeout value of httplib.HTTP?
> 
> i.e. how long python will wait for a response in the below code?
> 
>h = httplib.HTTP(self.url, 8080)
> h.putrequest('GET', '/sample/?url=' + self.url)
> h.endheaders()

HTTP per se does not define any timeout -- if self.url is correctly
resolved by DNS and accepts a TCP connection on port 8080, and then just
hangs forever, you'll be waiting.  You can force timeouts yourself by
playing with socket.setdefaulttimeout(...) before you start the HTTP
interaction.


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


Re: Finding a module's sub modules at runtime

2007-03-29 Thread Alex Martelli
Joshua J. Kugler <[EMAIL PROTECTED]> wrote:

> still be nicely portable.  It just seems that since Python is gathering
> that information anyway, it should make it available without me having to
> walk the directory tree.

Sorry, where is Python "gathering that information anyway"?  Unless I'm
mistaken, Python by default does not walk directory trees of subpackages
-- what makes you think it does?


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


Re: A nice way to use regex for complicate parsing

2007-03-29 Thread Paul McGuire
On Mar 29, 9:42 am, Shane Geiger <[EMAIL PROTECTED]> wrote:
> It would be worth learning pyparsing to do this.
>

Thanks to Shane and Steven for the ref to pyparsing.  I also was
struck by this post, thinking "this is pyparsing written in re's and
dicts".

The approach you are taking is *very* much like the thought process I
went through when first implementing pyparsing.  I wanted to easily
compose expressions from other expressions.  In your case, you are
string interpolating using a cumulative dict of prior expressions.
Pyparsing uses various subclasses of the ParserElement class, with
operator definitions for alternation ("|" or "^" depending on non-
greedy vs. greedy), composition ("+"), and negation ("~").  Pyparsing
also uses its own extended results construct, ParseResults, which
supports named results fields, accessible using list indicies, dict
names, or instance names.

Here is the pyparsing treatment of your example (I may not have gotten
every part correct, but my point is more the similarity of our
approaches).  Note the access to the smtp parameters via the Dict
transformer.

-- Paul


from pyparsing import *

#  ::=  "."  "."  "." 
intgr = Word(nums)
dotnum = Combine(intgr + "." + intgr + "." + intgr + "." + intgr)

#  ::=  |  "." 
string_ = Word(alphanums)
dotstring = Combine(delimitedList(string_,"."))

#  ::=   |  "." 
domain = dotnum | dotstring

#  ::= any one of the 128 ASCII characters except , , quote
("), or backslash (\)
#  ::= any one of the 128 ASCII characters (no exceptions)
#  ::=  "\"  | "\"   |  |  
#  ::=  """  """
quotedString = dblQuotedString  # <- just use pre-defined expr from
pyparsing

#  ::=  | 
localpart = (dotstring | quotedString).setResultsName("localpart")

#  ::=  "@" 
mailbox = Combine(localpart + "@" + domain).setResultsName("mailbox")

#  ::= "<" [  ":" ]  ">"
# also accept address without <>
path = "<" + mailbox + ">" | mailbox

# esmtp-keyword::= (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
esmtpkeyword = Word(alphanums,alphanums+"-")

# esmtp-value  ::= 1*']
- mailbox: ['[EMAIL PROTECTED]']
  - localpart: johnsmith
- parameters: []

MATCH
[['[EMAIL PROTECTED]']]
- mailbox: ['[EMAIL PROTECTED]']
  - localpart: johnsmith
- parameters: []

MATCH
['<', ['[EMAIL PROTECTED]'], '>', ['SIZE', '1234'], ['OTHER',
'[EMAIL PROTECTED]']]
- OTHER: [EMAIL PROTECTED]
- SIZE: 1234
- mailbox: ['[EMAIL PROTECTED]']
  - localpart: johnsmith
- parameters: [['SIZE', '1234'], ['OTHER', '[EMAIL PROTECTED]']]
  - OTHER: [EMAIL PROTECTED]
  - SIZE: 1234
SIZE is 1234

MATCH
[['[EMAIL PROTECTED]'], ['SIZE', '1234'], ['OTHER', '[EMAIL PROTECTED]']]
- OTHER: [EMAIL PROTECTED]
- SIZE: 1234
- mailbox: ['[EMAIL PROTECTED]']
  - localpart: johnsmith
- parameters: [['SIZE', '1234'], ['OTHER', '[EMAIL PROTECTED]']]
  - OTHER: [EMAIL PROTECTED]
  - SIZE: 1234
SIZE is 1234

MATCH
['<', ['"[EMAIL PROTECTED]> legal=email"@addresscom'], '>']
- mailbox: ['"[EMAIL PROTECTED]> legal=email"@addresscom']
  - localpart: "[EMAIL PROTECTED]> legal=email"
- parameters: []

MATCH
[['"[EMAIL PROTECTED]> legal=email"@addresscom']]
- mailbox: ['"[EMAIL PROTECTED]> legal=email"@addresscom']
  - localpart: "[EMAIL PROTECTED]> legal=email"
- parameters: []

MATCH
['<', ['"[EMAIL PROTECTED]> legal=email"@addresscom'], '>', ['SIZE', '1234'],
['OTHER', '[EMAIL PROTECTED]']]
- OTHER: [EMAIL PROTECTED]
- SIZE: 1234
- mailbox: ['"[EMAIL PROTECTED]> legal=email"@addresscom']
  - localpart: "[EMAIL PROTECTED]> legal=email"
- parameters: [['SIZE', '1234'], ['OTHER', '[EMAIL PROTECTED]']]
  - OTHER: [EMAIL PROTECTED]
  - SIZE: 1234
SIZE is 1234

MATCH
[['"[EMAIL PROTECTED]> legal=email"@addresscom'], ['SIZE', '1234'], ['OTHER',
'[EMAIL PROTECTED]']]
- OTHER: [EMAIL PROTECTED]
- SIZE: 1234
- mailbox: ['"[EMAIL PROTECTED]> legal=email"@addresscom']
  - localpart: "[EMAIL PROTECTED]> legal=email"
- parameters: [['SIZE', '1234'], ['OTHER', '[EMAIL PROTECTED]']]
  - OTHER: [EMAIL PROTECTED]
  - SIZE: 1234
SIZE is 1234

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


Re: manually implementing staticmethod()?

2007-03-29 Thread Alex Martelli
7stud <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> Can someone show me how to manually implement staticmethod()?  Here is

Simplest way:

class smethod(object):
  def __init__(self, f): self.f=f
  def __call__(self, *a, **k): return self.f(*a, **k)


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


File deletion after 72 hours of creation

2007-03-29 Thread [EMAIL PROTECTED]
I'm looking for a simple method to delete a folder after 72 "Business
hours" (saturday/sunday doesnt count) since its creation. Note that
This is on a linux system and I realize that it will be the last
modified time. These files wont be modified since their creation.

Im very confused on how to work with the number easily.

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


Re: Weird gcc behaviour with function pointer types

2007-03-29 Thread attn . steven . kuo
On Mar 29, 6:05 am, greg <[EMAIL PROTECTED]> wrote:
> In my quest to eliminate C compiler warnings from
> Pyrex output, I've discovered some utterly bizarre
> behaviour from gcc 3.3.
>
> The following code:
>
>void g(struct foo *x) {
>}
>
>void f(void) {
>  void (*h)(struct foo *);
>  h = g;
>}
>
> produces the following warning:
>
>blarg.c: In function `f':
>blarg.c:6: warning: assignment from incompatible pointer type
>
> However, adding the following line at the top:
>
>typedef struct foo Foo;
>
> makes the warning go away. The mere *presence* of
> the typedef is all that's needed -- it doesn't even
> have to be used.
>
> This looks like a bug in gcc to me -- what do people
> think?



Was there no (forward) declaration nor
definition of struct foo ahead of your functions?

I get no warnings with this:


struct foo; /* forward declaration */

void g(struct foo *x) {
}

void f(void) {
void (*h)(struct foo *);
h = g;
}


Using:

Target: powerpc-apple-darwin8
Configured with: /private/var/tmp/gcc/gcc-5026.obj~19/src/configure --
disable-checking --prefix=/usr --mandir=/share/man --enable-
languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^+.-]*$/s/
$/-4.0/ --with-gxx-include-dir=/include/gcc/darwin/4.0/c++ --
build=powerpc-apple-darwin8 --host=powerpc-apple-darwin8 --
target=powerpc-apple-darwin8
Thread model: posix

gcc version 4.0.0 (Apple Computer, Inc. build 5026)

--
Hope this helps,
Steven

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


Re: make RE more cleaver to avoid inappropriate : sre_constants.error: redefinition of group name

2007-03-29 Thread aspineux
On 29 mar, 16:22, "aspineux" <[EMAIL PROTECTED]> wrote:
> I want to parse
>
> '[EMAIL PROTECTED]' or '<[EMAIL PROTECTED]>' and get the email address [EMAIL 
> PROTECTED]
>
> the regex is
>
> r'<[EMAIL PROTECTED]>|[EMAIL PROTECTED]'
>
> now, if I want to give it a name
>
> r'<(?P[EMAIL PROTECTED])>|(?P[EMAIL PROTECTED])'
>
> sre_constants.error: redefinition of group name 'email' as group 2;
> was group 1
>
> BUT because I use a | , I will get only one group named 'email' !

THEN my regex is meaningful, and the error is meaningless and
somrthing
should be change into 're'

But maybe I'm wrong ?

>
> Any comment ?

I'm trying to start a discussion about something that can be improved
in 're',
not looking for a solution about email parsing :-)


>
> PS: I know the solution for this case is to use  r'(?P<)?(?P
> [EMAIL PROTECTED])(?(lt)>)'


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


Re: pattern search

2007-03-29 Thread Fabian Braennstroem
Hi Paul,

Paul McGuire schrieb am 03/27/2007 07:19 PM:
> On Mar 27, 3:13 pm, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
>> Hi to all,
>>
>> Wojciech Mu?a schrieb am 03/27/2007 03:34 PM:
>>
>>> Fabian Braennstroem wrote:
 Now, I would like to improve it by searching for different 'real'
 patterns just like using 'ls' in bash. E.g. the entry
 'car*.pdf' should select all pdf files with a beginning 'car'.
 Does anyone have an idea, how to do it?
>>> Use module glob.
>> Thanks for your help! glob works pretty good, except that I just
>> deleted all my lastet pdf files :-(
>>
>> Greetings!
>> Fabian
> 
> Then I shudder to think what might have happened if you had used
> re's! :)

A different feature it had was to copy the whole home-partition
(about 19G) into one of its own directories ... the strange thing:
it just needed seconds to do that and I did not have the permission
to all files and directories! It was pretty strange! Hopefully it
was no security bug in python...

Greetings!
Fabian

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


Re: File deletion after 72 hours of creation

2007-03-29 Thread skip

Alex> I'm looking for a simple method to delete a folder after 72
Alex> "Business hours" (saturday/sunday doesnt count) since its
Alex> creation. Note that This is on a linux system and I realize that
Alex> it will be the last modified time. These files wont be modified
Alex> since their creation.

Alex> Im very confused on how to work with the number easily.

Take a look at the dateutil module.  Its relativedelta object has some
weekday sense:

http://labix.org/python-dateutil

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


Re: Finding User Profile path

2007-03-29 Thread kyosohma
On Mar 29, 10:30 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> [resending as the original seems to have got lost;
> apologies if it appears as a duplicate]
>
> At the risk of insulting your intelligence, here's a
> rough-and-ready non-AD solution (culled from some code I
> had somewhere):
>
> 
> import win32net
> import win32netcon
>
> dc = win32net.NetGetAnyDCName (None, None)
> #
> # Or your specific server name, if you want
> #
>
> resume = 0
> while 1:
>(_users, total, resume) = \
>  win32net.NetUserEnum (
>dc,
>3,
>win32netcon.FILTER_NORMAL_ACCOUNT,
>resume,
>win32netcon.MAX_PREFERRED_LENGTH
>  )
>for _user in _users:
>  print _user['name'], _user['home_dir'], _user['profile']
>if not resume:
>  break
>
> 
>
> TJG

Thanks a lot. That seems to work the way we need. And don't worry too
much about my intelligence...I've only been programming in Python
since last May.

Mike

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


Re: PyPy 1.0: JIT compilers for free and more

2007-03-29 Thread Bart Ogryczak
On 28 mar, 23:36, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
> Carl Friedrich Bolz napisa³(a):
>
> > Welcome to the PyPy 1.0 release - a milestone integrating the results
> > of four years of research, engineering, management and sprinting
> > efforts, concluding the 28 months phase of EU co-funding!
>
> So it took 4 yars of work and over 2 yaers of consumption of EU funds,
> yeah, great.

> Could anybody explain, what this gives to Python and its users? Would
> we, eventually, get GIL-free VM, that is capable to consume all
> available power of multicore processors?

http://codespeak.net/pypy/dist/pypy/doc/stackless.html

> Or, maybe, we'll get something
> special, I am unable to dream of? Or is it purely academic project to
> create Python VM in Python?

RTFM.


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


Re: with timeout(...):

2007-03-29 Thread Nick Craig-Wood
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> > 
> > I beleive the convention is when calling an OS function which might
> > block the global interpreter lock is dropped, thus allowing other
> > python bytecode to run.
> 
> 
>  So what? That doesn't help you, as you are single-threaded here. The 
>  released lock won't prevent the called C-code from taking as long as it 
>  wants. |And there is nothing you can do about that.

I'm assuming that the timeout function is running in a thread...

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can I clear a dictionary in python

2007-03-29 Thread Larry Bates
Bruno Desthuilliers wrote:
> Larry Bates a écrit :
>> Aahz wrote:
>>> In article <[EMAIL PROTECTED]>,
>>> Larry Bates  <[EMAIL PROTECTED]> wrote:
 [EMAIL PROTECTED] wrote:
> I create a dictionary like this
> myDict = {}
>
> and I add entry like this:
> myDict['a'] = 1
> but how can I empty the whole dictionary?
 just point myDict to an empty dictionary again

 myDict={}
>>> Go back and read Christian's post, then post a followup explaning why
>>> his
>>> solution is better than yours.  Your explanation should use id().
>>
>> I believe he (as many new to Python do) are mired in old
>> programming thinking that variables "contain" things.
> 
> Does "he" refer to Christian Tismer ? If so, you may want to use google
> and correct your beliefs (hint: does 'stackless Python' ring a bell ?).
> 
>> As I'm sure you kno, variables point to things in Python.
> 
> (conceptually) names are keys associated with an object in a given
> namespace. FWIW, be assured that Christians knows this pretty well.
> 
>> I don't believe that there are lots of other objects
>> pointing to this dictionary.
> 
> You just cannot *know* this. This might be true now, this might be false
> now, and this might change anytime. Assuming anything here is the road
> to disaster. Don't assume, do the righ thing.
> 
>>  Perhaps the OP can clarify
>> for us.  If there aren't other objects pointing to
>> this dictionary it would make NO sense to iterate over a
>> dictionary and delete all the keys/values
> 
> You don't iterate over anything. Dicts being the central datastructure
> in Python, you can bet your ass they are optimized to death (or near
> death). If you have any doubt, then still don't assume : verify (hint:
> import timeit). And yet even if clearing a dict happens to be a bit
> slower than instanciating a new one, rebinding a name and mutating an
> object are still two very different concepts in Python, with very
> different consequences. The OP explicitely asked for clearing a dict,
> not for creating a new one.
> 
>> so I tried to read
>> between the lines
> 
> Why ?
> 
>> and answer what I believe the OP thought he
>> was asking.
> 
> What the OP asked was quite clear, and not subject to any
> interpretation. And the correct answer is obviously not the one you gave.
> 
>>  BTW-I didn't see you posting an answer to what
>> you thought was the "correct" question, just criticizing me
>> for taking the time to answer what I perceived the OP was
>> asking.
> 
> If you cannot understand the difference between criticism and a friendly
> correction,  nor why you should actually thank the one correcting you
> when you're wrong, I guess there's no point trying explaining why
> correcting wrong answers on newsgroups is actually important.

I stand corrected about my answer, but I'll stick to my assumption
(until told otherwise by the OP) that the question that was asked
wasn't precisely what the OP wanted to accomplish.  It was just too
simple to mean what you guys assumed (e.g. complex dictionary pointed
to by lots of other objects, etc.).  I don't mind being corrected with
the proper information, but Aahz's post doesn't make any sense.  He said
"Go back and read Christian's answer...". Christian's answers were not
answers to the OP's question at all.  Here is what shows up in my
newsreader:

'''
Reading the Python docs might help.
But before, I would try a dir(myDict).
Maybe you will find an easter-egg
which has exactly the name you are looking for?

cheers - chris
'''

and

'''
This is wrong and not answering the question.
Creating a new dict does not change the dict.
He wants to clear *this* dict, and maybe he
cannot know how many other objects are
referring to this dict.

cheers -- chris
'''

You appear to be the only one that apparently posted the correct
answer myDict.clear() for which I thank you.  I learned two things
today: 1) answer EXACTLY the question that is asked and 2) dicts
have a clear method that is safer than my answer.

-Larry


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


Re: dynamic module does not define init function (initpsycopgmodule)

2007-03-29 Thread Gabriel Genellina
En Wed, 28 Mar 2007 17:16:43 -0300, kickslop <[EMAIL PROTECTED]> escribió:

> Clearly I am doing something braindead here with psycopg 1.1.21
> (psycopg2 is not an option).
>
> Any ideas?  I get the same results when I build it with Red Hat's GCC
> 3.4.6 setup as well as our in-house GCC 3.3.5 setup.
>
> Linux rcf-temp3 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:32:02 EDT 2006
> x86_64 x86_64 x86_64 GNU/Linux
>
> Python 2.3.4 (#1, Sep 26 2006, 17:25:54)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import psycopgmodule
> Traceback (most recent call last):
>   File "", line 1, in ?
> ImportError: dynamic module does not define init function
> (initpsycopgmodule)

I've never used it, but the module appears to be called psycopg.
Try `import psycopg` instead

> psycopg-1.1.21 % nm -a psycopgmodule.so | grep init
> 4748 T _init
> 5000 T initpsycopg
...should work.

-- 
Gabriel Genellina

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


Re: BeautifulSoup vs. Microsoft

2007-03-29 Thread John Nagle
Duncan Booth wrote:
> John Nagle <[EMAIL PROTECTED]> wrote:
> 
> 
>>Strictly speaking, it's Microsoft's fault.
>>
>> title="".  So all that following stuff is from what
>>follows the next "-->" which terminates a comment.
> 
> 
> It is an attribute value, and unescaped angle brackets are valid in 
> attributes. It looks to me like a bug in BeautifulSoup.

I think you're right.  The HTML 4 spec,

http://www.w3.org/TR/html4/intro/sgmltut.html

says "Note that comments are markup".  So recognizing comment syntax
inside an attribute is, in fact, an error in BeautifulSoup.

The source HTML on the Microsoft page is thus syntactically correct,
although meaningless.  That's the only place on that page with a
comment-type form in an attribute.

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


Re: What is the timeout value of HTTP

2007-03-29 Thread Facundo Batista
ken wrote:

> i.e. how long python will wait for a response in the below code?
>
>h = httplib.HTTP(self.url, 8080)
> h.putrequest('GET', '/sample/?url=' + self.url)
> h.endheaders()

For ever. 

In Py<=2.5, httplib.HTTP doesn't have a timeout, so you have to do
something like:

>>> import socket
>>> socket.setdefaulttimeout(...)
>>> h = httplib.HTTP(...)

Beware that *all* sockets created after the call to setdefaulttimeout()
will have that default.

httplib.HTTP now has a timeout, but in the development trunk (you'll
have to checkout the SVN code and compile Python yourself, or wait until
Py2.6).

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: PyPy 1.0: JIT compilers for free and more

2007-03-29 Thread Carl Friedrich Bolz
Duncan Booth wrote:
> Robin Becker <[EMAIL PROTECTED]> wrote:
> 
>> I am hugely encouraged by this
>>
>> C:\Python\devel\pypy-1.0.0>\python24\python \python\lib\test
> \pystone.py
>> Pystone(1.1) time for 5 passes = 1.49586
>> This machine benchmarks at 33425.6 pystones/second
>>
>> C:\Python\devel\pypy-1.0.0>.\pypy-c.exe \python\lib\test\pystone.py
>> Pystone(1.1) time for 5 passes = 2.16123e-005
>> This machine benchmarks at 2.3135e+009 pystones/second
>>
>>
>> :) not
> 
> It looks like time.clock() is completely borked.

time.clock was indeed borked under windows (of by a factor of 1000). 
fixed in svn now.

Cheers,

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


Re: with timeout(...):

2007-03-29 Thread Jean-Paul Calderone
On Thu, 29 Mar 2007 11:30:04 -0500, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>> >
>> > I beleive the convention is when calling an OS function which might
>> > block the global interpreter lock is dropped, thus allowing other
>> > python bytecode to run.
>>
>>
>>  So what? That doesn't help you, as you are single-threaded here. The
>>  released lock won't prevent the called C-code from taking as long as it
>>  wants. |And there is nothing you can do about that.
>
>I'm assuming that the timeout function is running in a thread...

What does it do when the timeout expires?  How does it interrupt recv(2)
or write(2) or `for (int i = 0; i < (unsigned)-1; ++i);'?

This is what we're talking about, right?

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


encoding confusions

2007-03-29 Thread Tim Arnold
I have the contents of a file that contains French documentation.
I've iterated over it and now I want to write it out to a file.

I'm running into problems and I don't understand why--I don't get how the 
encoding works.
My first attempt was just this:
< snipped code for classes, etc; fname is string, codecs module loaded.>
< self.contents is the French file's contents as a single string >

tFile = codecs.open(fname,'w',encoding='latin-1', errors='ignore')
tFile.write(self.contents)
tFile.close()

ok, so that didn't work and I read some more and did this:
tFile.write(self.contents.encode('latin-1'))

but that gives me the same error
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 48: 
ordinal not in range(128)

this is python2.4.1 (hpux)
sys.getdefaultencoding()
'ascii'

thanks,
--Tim Arnold


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


Best way to wait for string input

2007-03-29 Thread kevinliu23
Hi guys,

Python newbie here for some expert help. So basically I want to design
a menu system that waits for a string input. I'm not sure what the
best way of going about this is. The current system waits for a single
character input using msvcrt.kbhit( ) and msvcrt.getch( ). Is there
something equivalent to wait for string inputs?

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


Question about details of __import__

2007-03-29 Thread Mitko Haralanov
Hi all,

I am going to do my best to describe the issue that I am having and
hopefully someone can shed some light on it:

I have three modules that a comprising the problem:
./core.py
./log.py
./resources/simple/__init__.py

core.py looks something like this (simplified version):

import log
class Core:
def __init__ (self):
self.logger = log.Logger ("core", log.ERROR,
"/home/logs/log") 
try:
module = __import__ ("resources.simple",globals
(), locals (), ["simple"]) 
except ImportError:
print "Error importing"

self.rs = module.Resource ()

resources/simple/__init__.py look like this (again, simplified version):

import log
class Resource:
def __init__ (self):
self.logger = log.Logger ("resource", log.ERROR)

and finally, log.py:

import logging

global_info = [None, None, None]

def Logger (name, level, filename=None):
global global_info
print global_info
if not global_info[0] and not global_info[1]:
global_info[0] = name
global_info[1] = level
global_info[2] = filename

logging.basicConfig (level, format=...)
else:
if filename:
print "ERROR: logger already initialized"

return logging.getLogger (name)

The problem that I am seeing is that 'global_info' in the log.py module
is [None, None, None] on both calls of log.Logger (), even though the
initial call (from core.py) sets it to the passed in values.

According to the Python documentation, I am using the __import__
statement correctly to get what I want? It seems like, the guts of the
import/__import__ code are creating two different namespaces for the
log.py module.

 (if you are wondering why I am using __import__ in my class
constructor, it is because the name of the module that should be
imported is read out of a configuration file).

Could someone help with what could be going wrong here?
-- 
Mitko Haralanov  [EMAIL PROTECTED]
Senior Software Engineer 650.934.8064
System Interconnect Group   http://www.qlogic.com

==
 Professor: Some say I'm robbing the cradle but I say she's robbing the
grave.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which methods to use?

2007-03-29 Thread Gabriel Genellina
En Thu, 29 Mar 2007 01:56:15 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:

> By the way, "id(obj) == id(another_object)" is just a long way of writing
> "obj is another_object".

Just as a side note: that's not true, testing by id() only works if both  
objects are alive at the same time.

py> id(object()) == id(object())
True
py> object() is object()
False

So using the `is` operator is the only safe way to test for identity.

-- 
Gabriel Genellina

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


Re: Best way to wait for string input

2007-03-29 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, kevinliu23
wrote:

> Python newbie here for some expert help. So basically I want to design
> a menu system that waits for a string input. I'm not sure what the
> best way of going about this is. The current system waits for a single
> character input using msvcrt.kbhit( ) and msvcrt.getch( ). Is there
> something equivalent to wait for string inputs?

The builtin `raw_input()`?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding confusions

2007-03-29 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Tim Arnold wrote:

> I have the contents of a file that contains French documentation.
> I've iterated over it and now I want to write it out to a file.
> 
> I'm running into problems and I don't understand why--I don't get how the 
> encoding works.
> My first attempt was just this:
> < snipped code for classes, etc; fname is string, codecs module loaded.>
> < self.contents is the French file's contents as a single string >

What is the type of `self.contents`, `str` or `unicode`?  You *decode*
strings to unicode objects and you *encode* unicode objects to strings. 
It doesn't make sense to encode a string in 'latin-1' because it must be
decoded first and the "automatic" decoding assumes ASCII and barfs if
there's something non-ascii in the string.

Ciao,
Marc 'BlackJack' Rintsch

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


Any "consumer review generators" available?

2007-03-29 Thread aralsky
I am looking for a fake consumer review generator that could generate realistic 
looking reviews for any products, kind of like on amazon.com but generated by 
Artificial Intelligence. Is there a package available in your favorite 
programing language... thx alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any "consumer review generators" available?

2007-03-29 Thread Paul McGuire
On Mar 29, 1:19 pm, [EMAIL PROTECTED] wrote:
> I am looking for a fake consumer review generator that could generate 
> realistic looking reviews for any products, kind of like on amazon.com but 
> generated by Artificial Intelligence. Is there a package available in your 
> favorite programing language... thx alan

I have a fake supervisor reference generator for job interviews, a
fake house inspection generator for real estate transactions, and a
fake parole testimony generator - maybe you could adapt one of them
(unfortunately, they are written in dissembler).

-- Paul

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


Re: with timeout(...):

2007-03-29 Thread John Nagle
Diez B. Roggisch wrote:
> Nick Craig-Wood wrote:
> 
> 
>>Did anyone write a contextmanager implementing a timeout for
>>python2.5?
>>
>>And have it work reliably and in a cross platform way!
> 
> Cross platform isn't the issue here - reliability though is. To put it
> simple: can't be done that way. You could of course add a timer to the
> python bytecode core, that would "jump back" to a stored savepoint or
> something like that.

 Early versions of Scheme had a neat solution to this problem.
You could run a function with a limited amount of "fuel".  When the
"fuel" ran out, the call returned with a closure.  You could
run the closure again and pick up from where the function had been
interrupted, or just discard the closure.

 So there's conceptually a clean way to do this.  It's probably
not worth having in Python, but there is an approach that will work.

 LISP-type systems tend to be more suitable for this sort of thing.
Traditionally, LISP had the concept of a "break", where
execution could stop and the programmer (never the end user) could
interact with the computation in progress.

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


Re: Question about details of __import__

2007-03-29 Thread Gabriel Genellina
En Thu, 29 Mar 2007 14:42:33 -0300, Mitko Haralanov <[EMAIL PROTECTED]>  
escribió:

> I have three modules that a comprising the problem:
> ./core.py
> ./log.py
> ./resources/simple/__init__.py

Surely there is a ./resources/__init__.py too?

> The problem that I am seeing is that 'global_info' in the log.py module
> is [None, None, None] on both calls of log.Logger (), even though the
> initial call (from core.py) sets it to the passed in values.
> According to the Python documentation, I am using the __import__
> statement correctly to get what I want? It seems like, the guts of the
> import/__import__ code are creating two different namespaces for the
> log.py module.

You may check if this is the case, looking at sys.modules

>  (if you are wondering why I am using __import__ in my class
> constructor, it is because the name of the module that should be
> imported is read out of a configuration file).

Anyway you could import the package and lookup the module inside using  
getattr:

import resources
name = "simple"
module = getattr(resources, name)
self.rs = module.Resource()

-- 
Gabriel Genellina

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


Re: Question about details of __import__

2007-03-29 Thread Mitko Haralanov
On Thu, 29 Mar 2007 15:43:46 -0300
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> Surely there is a ./resources/__init__.py too?

There sure is:
./resources/__init__.py is:
__all__ = ['simple', 'other']

> You may check if this is the case, looking at sys.modules

I did look at sys.modules but I wasn't sure what to look for. There was
a log module in the list but what else should I look for?

> Anyway you could import the package and lookup the module inside
> using getattr:
> 
> import resources
> name = "simple"
> module = getattr(resources, name)
> self.rs = module.Resource()

Since the ./resources/__init__.py does not actually import any of the
modules below it, this trick won't work but just for an experiment,
I'll change the code and try it.

-- 
Mitko Haralanov  [EMAIL PROTECTED]
Senior Software Engineer 650.934.8064
System Interconnect Group   http://www.qlogic.com

==
Disraeli was pretty close: actually, there are Lies, Damn lies,
Statistics, Benchmarks, and Delivery dates.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any "consumer review generators" available?

2007-03-29 Thread Peter Otten
Paul McGuire wrote:

> On Mar 29, 1:19 pm, [EMAIL PROTECTED] wrote:
>> I am looking for a fake consumer review generator that could generate
>> realistic looking reviews for any products, kind of like on amazon.com
>> but generated by Artificial Intelligence. Is there a package available in
>> your favorite programing language... thx alan
> 
> I have a fake supervisor reference generator for job interviews, a
> fake house inspection generator for real estate transactions, and a
> fake parole testimony generator - maybe you could adapt one of them
> (unfortunately, they are written in dissembler).
> 
> -- Paul

OP, please disregard. That was just Paul's fake usenet post generator
kicking in.

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


Re: Any "consumer review generators" available?

2007-03-29 Thread Uri Guttman
> "a" == aralsky  <[EMAIL PROTECTED]> writes:

  a> I am looking for a fake consumer review generator that could
  a> generate realistic looking reviews for any products, kind of like
  a> on amazon.com but generated by Artificial Intelligence. Is there a
  a> package available in your favorite programing language... thx alan

it's called a human being. and hope you find some with ethics which you
don't seem to have.

uri

-- 
Uri Guttman  --  [EMAIL PROTECTED]   http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs    http://jobs.perl.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding a module's sub modules at runtime

2007-03-29 Thread Joshua J. Kugler
On Thursday 29 March 2007 07:33, Alex Martelli wrote:

> Joshua J. Kugler <[EMAIL PROTECTED]> wrote:
> 
>> still be nicely portable.  It just seems that since Python is gathering
>> that information anyway, it should make it available without me having to
>> walk the directory tree.
> 
> Sorry, where is Python "gathering that information anyway"?  Unless I'm
> mistaken, Python by default does not walk directory trees of subpackages
> -- what makes you think it does?

Hmm...right: dynamic language, runtime binding.  It would go out and find
whether or not Module1.Module2 existed only when import was called.  Sorry,
my bad.  I am assuming, however, that the help function walks the directory
tree, or else I would not get output like this:

>>> import ModTest
>>> help(ModTest)
Help on package ModTest:

NAME
ModTest

FILE
/usr/local/lib/python2.4/site-packages/ModTest/__init__.py

PACKAGE CONTENTS
AModule
BModule
CModule

Thanks for the clarification.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: PyPy 1.0: JIT compilers for free and more

2007-03-29 Thread [EMAIL PROTECTED]
On Mar 28, 5:36 pm, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
> Carl Friedrich Bolz napisa³(a):
>
> > Welcome to the PyPy 1.0 release - a milestone integrating the results
> > of four years of research, engineering, management and sprinting
> > efforts, concluding the 28 months phase of EU co-funding!
>
> So it took 4 yars of work and over 2 yaers of consumption of EU funds,
> yeah, great.
>
> Could anybody explain, what this gives to Python and its users? Would
> we, eventually, get GIL-free VM, that is capable to consume all
> available power of multicore processors?

That is the eventual hope, along with a faster Python interpreter
(with a true functional JIT), and stackless features, and more easily
developed syntax, and retargetable front- and back- ends (allowing,
e.g. easier development of Python on the .NET CLI, JVM, etc, or other
languages like Javascript, Lisp, or whatever on the PyPy VM), and fast
extensions written in RPython instead of C, and many other features.

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


How can I get the content of a web site using http library

2007-03-29 Thread [EMAIL PROTECTED]
I am trying to get the content of a web site like this:
But my question is how can I do a 'GET' request without putting the '/
index.html''


   h = httplib.HTTP('www.yahoo.com')

# it takes 2 arguments here, but I don't know if the site has
'/index.html' , how can I leave this out?

h.putrequest('GET')
h.endheaders()

errcode, errmsg, headers = h.getreply()

if (errcode == 200):

f = h.getfile()

Thank you for your help.

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


Hellow World:)

2007-03-29 Thread void pointer
Hi All ..I am looking for PDF version of " Practical Python"  and a language to 
stick to .Should I find that book ,I wil lconsder  this Python :)
   
  Thanks 
   

 
-
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I get the content of a web site using http library

2007-03-29 Thread kyosohma
On Mar 29, 2:18 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> I am trying to get the content of a web site like this:
> But my question is how can I do a 'GET' request without putting the '/
> index.html''
>
>h = httplib.HTTP('www.yahoo.com')
>
> # it takes 2 arguments here, but I don't know if the site has
> '/index.html' , how can I leave this out?
>
> h.putrequest('GET')
> h.endheaders()
>
> errcode, errmsg, headers = h.getreply()
>
> if (errcode == 200):
>
> f = h.getfile()
>
> Thank you for your help.

You may want to go with the urllib module instead. Check out the how-
to below:

http://www.voidspace.org.uk/python/articles/urllib2.shtml

Mike

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


Re: Question about details of __import__

2007-03-29 Thread Gabriel Genellina
En Thu, 29 Mar 2007 15:56:54 -0300, Mitko Haralanov <[EMAIL PROTECTED]>  
escribió:

>> You may check if this is the case, looking at sys.modules
>
> I did look at sys.modules but I wasn't sure what to look for. There was
> a log module in the list but what else should I look for?

If you think that Python got confused and has two duplicate modules, try  
to find them in sys.modules. Perhaps under the names 'log' and 'xxx.log'
Or, using print, try to see *when* your global variable is reset to None.

-- 
Gabriel Genellina

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


Re: How can I get the content of a web site using http library

2007-03-29 Thread [EMAIL PROTECTED]
On Mar 29, 2:34 pm, [EMAIL PROTECTED] wrote:
> On Mar 29, 2:18 pm, "[EMAIL PROTECTED]"
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > I am trying to get the content of a web site like this:
> > But my question is how can I do a 'GET' request without putting the '/
> > index.html''
>
> >h = httplib.HTTP('www.yahoo.com')
>
> > # it takes 2 arguments here, but I don't know if the site has
> > '/index.html' , how can I leave this out?
>
> > h.putrequest('GET')
> > h.endheaders()
>
> > errcode, errmsg, headers = h.getreply()
>
> > if (errcode == 200):
>
> > f = h.getfile()
>
> > Thank you for your help.
>
> You may want to go with the urllib module instead. Check out the how-
> to below:
>
> http://www.voidspace.org.uk/python/articles/urllib2.shtml
>
> Mike

Thanks. Can you please tell me how can I do a Post form submission
using the urlLib2 library? I look at your link, but i cant find an
example there.

Thank you.

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


Re: How can I get the content of a web site using http library

2007-03-29 Thread Thorsten Kampe
* [EMAIL PROTECTED] (29 Mar 2007 12:18:19 -0700)
> I am trying to get the content of a web site like this:
> But my question is how can I do a 'GET' request without putting the '/
> index.html''

import urllib
print urllib.urlopen('http://www.yahoo.com/').read()
-- 
http://mail.python.org/mailman/listinfo/python-list


Web21C Python SDK - announce

2007-03-29 Thread Otu Ekanem

The BT Web21C python SDK is a package which abstract the SOAP/WsSecurity
stack from end users allowing them to write python
code to access BT plethora of webservices directly.

You can use it to make phone calls, conference calls, send text messages
(SMS) and locate people based on cell of origin data.

I have a short introduction here
http://rants.ekanem.de/2007/03/29/make-it-ring-with-python/ and the actual
website is at http://web21c.bt.com/

--
Otu Ekanem

http://www.ekanem.de
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I get the content of a web site using http library

2007-03-29 Thread kyosohma
On Mar 29, 3:07 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> * [EMAIL PROTECTED] (29 Mar 2007 12:18:19 -0700)
>
> > I am trying to get the content of a web site like this:
> > But my question is how can I do a 'GET' request without putting the '/
> > index.html''
>
> import urllib
> print urllib.urlopen('http://www.yahoo.com/').read()

Posting to a form:

urllib:
http://www.thescripts.com/forum/thread23871.html

httplib:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
http://www.python.org/infogami-faq/library/how-can-i-mimic-cgi-form-submission-method-post/

Mike

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


  1   2   >