Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread John Machin
On Feb 12, 4:24 pm, Samuel Karl Peterson
<[EMAIL PROTECTED]> wrote:
> C-like way to do it, (warning, untested in python):
>
> for i in range(8):
> for j in range(8):
> for offset_i in range(-1,2):
> for offset_j in range(-1, 2):
> row = i + offset_i
> col = j + offset_j
> if (row < 0 or row > 7) or (col < 0 or col > 8) \
>or ((row,col) == (i,j)):
> continue
> # else do something with board[row][col]
>
> I realize this is gross and un-Pythonic and does the same thing

It's also just a little bit inefficient. Never mind the algorithm,
we'll talk about that later. Let's just improve the code a little:

side_range = range(8)
delta_range = range(-1, 2)
for i in side_range:
for offset_i in delta_range:
row = i + offset_i
if not (0 <= row <= 7): continue
for j in side_range:
for offset_j in delta_range:
if not offset_i and not offset_j: continue
col = j + offset_j
if not(0 <= col <= 7): continue
# *now* it's safe to do something
# with (row, col)

Such hoisting of code out of inner loops is done for you by a C
compiler -- Python assumes you know what you are doing :-)

Now for the algorithm: all of that testing to see if you are about to
sail off the end of the world is a bit ugly and slow. You can use bit-
bashing, as Paul suggested, even though it's on Steven D'Aprano's list
of 6 deadly sins :-)

Another approach that has been used is to have a 9 x 9 storage area;
the squares off the edge contain a value that is neither "empty" nor
any value that represents a piece. So with careful coding, they
automatically fail tests like "can I capture the piece on this
square" [no, it's not a piece] and "can I move here" [no, it's not
empty]. If the game is chess, you need 10 x 10 to cater for those
pesky knights.

Cheers,
John

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


Re: randomly generate n of each of two types

2007-02-11 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> Ah, I see what you mean... you're reminding me that the Original Poster
> seems to want a biased set of almost-but-not-quite-randomly chosen
> values, so that random_values(1) must return one each of True and False
> and never True, True or False, False.

I thought that was what was specified, "generate n of each of two
types".  So if n=10 and the two types are true and false, generate 10
trues and 10 falses.  random.shuffle is the most direct way to do it
but I gave another approach that doesn't use auxiliary space except
for a few variables.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread bearophileHUGS
James Stroud:
> import operator
> srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
> is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]])

Or maybe (untested), Python V.2.5:

srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = any(ary[row+i][col+j] for (i,j) in srch)

Or:

is_adj = any(ary[row+i][col+j] for i in [-1,0,1] for j in [-1,0,1] if
(i,j) != (0,0))

Bye,
bearophile

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


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread James Stroud
Paul Rubin wrote:
> "agent-s" <[EMAIL PROTECTED]> writes:
> 
>>Basically I'm programming a board game and I have to use a list of
>>lists to represent the board (a list of 8 lists with 8 elements each).
>>I have to search the adjacent cells for existing pieces and I was
>>wondering how I would go about doing this efficiently. Thanks
> 
> 
> You're getting a bunch of Pythonic suggestions which are easy to
> understand though not so efficient.  If you're after efficiency you
> might look at a book like Welsh and Baczynskyj "Computer Chess II" for
> some techniques (warning, this is a rather old book though) and
> program in a closer-to-the-metal language.  One common approach these
> days is "bit boards".  Basically you represent the board state as a
> bunch of 64-bit words, one bit per square.  So for checking occupancy,
> you'd have a word having the bits set for occupied squares.  If you
> only want to check adjacent squares (king moves), you could have a
> bunch of bit masks (one for each square) with bits set only for the
> adjacent squares (similarly for bishop moves, rook moves, etc.)  Then
> to check adjacency you'd mask off the appropriate bits for that
> square, then AND it against the occupancy word.  Normally you'd have
> separate occupancy words for your own pieces and your opponent's.

In defense of the less efficient suggestions, he did say he had to use a 
list of lists. But what you describe is pretty cool.

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


Re: randomly generate n of each of two types

2007-02-11 Thread Steven D'Aprano
On Sun, 11 Feb 2007 22:20:24 -0800, Paul Rubin wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> If you want to avoid shuffle, here's an alternative:
>> 
>> def random_values(n, valuelist=[True, False]):
>> N = len(valuelist)
>> for _ in range(N*n):
>>  yield valuelist[random.randrange(0, N)]
> 
> That is not guaranteed to yield exactly equal numbers of true and false.

Neither is any random number generator. That's why because it's *random*.

Ah, I see what you mean... you're reminding me that the Original Poster
seems to want a biased set of almost-but-not-quite-randomly chosen
values, so that random_values(1) must return one each of True and False
and never True, True or False, False.

You're right, that's how the O.P. implicitly specified the problem. But it
may not be what he wants.



-- 
Steven D'Aprano 

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


Re: string.replace non-ascii characters

2007-02-11 Thread Steven D'Aprano
On Mon, 12 Feb 2007 03:01:55 -0300, Gabriel Genellina wrote:

> En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson  
> <[EMAIL PROTECTED]> escribió:
> 
> Sorry to steal the thread! This is only related to your signature:
> 
>> "if programmers were paid to remove code instead of adding it,
>> software would be much better" -- unknown
> 
> I just did that last week. Around 250 useless lines removed from a 1000  
> lines module.
[snip]

Hot out of uni, my first programming job was assisting a consultant who
was writing an application in Apple's "Hypertalk", a so-called "fourth
generation language" with an English-like syntax, aimed at non-programmers.

Virtually the first thing I did was refactor part of his code that looked
something like this:

set the name of button id 1 to 1
set the name of button id 2 to 2
set the name of button id 3 to 3
...
set the name of button id 399 to 399
set the name of button id 400 to 400


into something like this:

for i = 1 to 400:
set the name of button id i to i


-- 
Steven D'Aprano 

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


Re: randomly generate n of each of two types

2007-02-11 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> If you want to avoid shuffle, here's an alternative:
> 
> def random_values(n, valuelist=[True, False]):
> N = len(valuelist)
> for _ in range(N*n):
>  yield valuelist[random.randrange(0, N)]

That is not guaranteed to yield exactly equal numbers of true and false.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: randomly generate n of each of two types

2007-02-11 Thread Steven D'Aprano
On Mon, 12 Feb 2007 00:57:35 +, Alan Isaac wrote:

> "Stargaming" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> ...   types *= n
>> ...   shuffle(types)
> 
> This again has the "costs" I referred to:
> creating a potentially large sequence,
> and shuffling it.  (Additionally, shuffle
> cannot achieve many of the possible
> shuffles of a large list, but I doubt this
> is easily evaded.)

Whether that second issue is a problem or not really depends on what you
intend doing with the random objects. But notice that Python uses the
Mersenne Twister PRNG, which has a period of 2**19937-1. That's *roughly*
equivalent to the number of permutations of a list with 2080 items.

If you really care about shuffling large lists, you can chain PRNGs. For
instance, you might use shuffle() to generate a random batch of items,
then use a completely different PRNG to shuffle the list again.



As for the first issue:

def random_values(n, valuelist=[True, False]):
for _ in range(n):
values = valuelist[:]
random.shuffle(values)
for item in types:
yield item

Notice that the default objects in the list aren't types, so the name
random_types is inappropriate. The user can pass any objects they like,
not just a list of types like [int, str].

Note also that this code isn't limited to lists of just two objects. You
can pass as many or as few as you like.

It also doesn't build a large list, but any regularities in the shuffle
algorithm will show up in here. Unless you're doing cryptography, that
probably doesn't matter.

If you want to avoid shuffle, here's an alternative:

def random_values(n, valuelist=[True, False]):
N = len(valuelist)
for _ in range(N*n):
 yield valuelist[random.randrange(0, N)]




-- 
Steven D'Aprano 

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


Re: string.replace non-ascii characters

2007-02-11 Thread Gabriel Genellina
En Mon, 12 Feb 2007 02:38:29 -0300, Samuel Karl Peterson  
<[EMAIL PROTECTED]> escribió:

Sorry to steal the thread! This is only related to your signature:

> "if programmers were paid to remove code instead of adding it,
> software would be much better" -- unknown

I just did that last week. Around 250 useless lines removed from a 1000  
lines module. I think the original coder didn't read the tutorial past the  
dictionary examples: *all* functions returned a dictionary or list of  
dictionaries! Of course using different names for the same thing here and  
there, ugh... I just throw in a few classes and containers, removed all  
the nonsensical packing/unpacking of data going back and forth, for a net  
decrease of 25% in size (and a great increase in robustness,  
maintainability, etc).
If I were paid for the number of lines *written* that would not be a great  
deal :)

-- 
Gabriel Genellina

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


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread Paul Rubin
"agent-s" <[EMAIL PROTECTED]> writes:
> Basically I'm programming a board game and I have to use a list of
> lists to represent the board (a list of 8 lists with 8 elements each).
> I have to search the adjacent cells for existing pieces and I was
> wondering how I would go about doing this efficiently. Thanks

You're getting a bunch of Pythonic suggestions which are easy to
understand though not so efficient.  If you're after efficiency you
might look at a book like Welsh and Baczynskyj "Computer Chess II" for
some techniques (warning, this is a rather old book though) and
program in a closer-to-the-metal language.  One common approach these
days is "bit boards".  Basically you represent the board state as a
bunch of 64-bit words, one bit per square.  So for checking occupancy,
you'd have a word having the bits set for occupied squares.  If you
only want to check adjacent squares (king moves), you could have a
bunch of bit masks (one for each square) with bits set only for the
adjacent squares (similarly for bishop moves, rook moves, etc.)  Then
to check adjacency you'd mask off the appropriate bits for that
square, then AND it against the occupancy word.  Normally you'd have
separate occupancy words for your own pieces and your opponent's.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread Gabriel Genellina
En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson  
<[EMAIL PROTECTED]> escribió:

> James Stroud <[EMAIL PROTECTED]> on Sun, 11 Feb 2007 16:53:16 -0800
> didst step forth and proclaim thus:
>
>> agent-s wrote:
>> > Basically I'm programming a board game and I have to use a list of
>> > lists to represent the board (a list of 8 lists with 8 elements each).
>> > I have to search the adjacent cells for existing pieces and I was
>> > wondering how I would go about doing this efficiently. Thanks

> Wow, maybe it's just me (I'm a pretty bad programmer) but this is
> where list comprehensions begin to look unreadable to me.  Here's a
> C-like way to do it, (warning, untested in python):

Just for fun, and to add one more way. This is a generator for adjacent  
indexes, that can be used to search for occupied cells, for locating a  
suitable next move, or whatever:

py> def adj(i, j):
...   for ni in (i-1, i, i+1):
... if ni not in range(8): continue
... for nj in (j-1, j, j+1):
...   if nj not in range(8): continue
...   if ni!=i or nj!=j:
... yield ni,nj
...
py>
py> print list(adj(4,3))
[(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4
py> print list(adj(7,3))
[(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)]
py> print list(adj(4,7))
[(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)]
py> print list(adj(0,7))
[(0, 6), (1, 6), (1, 7)]

-- 
Gabriel Genellina

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


Re: string.replace non-ascii characters

2007-02-11 Thread Samuel Karl Peterson
Steven Bethard <[EMAIL PROTECTED]> on Sun, 11 Feb 2007 22:23:59
-0700 didst step forth and proclaim thus:

> Samuel Karl Peterson wrote:
> > Greetings Pythonistas.  I have recently discovered a strange anomoly
> > with string.replace.  It seemingly, randomly does not deal with
> > characters of ordinal value > 127.  I ran into this problem while
> > downloading auction web pages from ebay and trying to replace the
> > "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from
> > urllib2.  Yet today, all is fine, no problems whatsoever.  Sadly, I
> > did not save the exact error message, but I believe it was a
> > ValueError thrown on string.replace and the message was something to
> > the effect "character value not within range(128).
> 
> Was it something like this?
> 
>  >>> u'\xa0'.replace('\xa0', '')
> Traceback (most recent call last):
>File "", line 1, in 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position
> 0: ordinal not in range(128)

Yeah that looks like exactly what was happening, thank you.  I wonder
why I had a unicode string though.  I thought urllib2 always spat out
a plain string.  Oh well.

u'\xa0'.encode('latin-1').replace('\xa0', " ")

Horray.
-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No module named pyExcelerator Error

2007-02-11 Thread Gabriel Genellina
En Mon, 12 Feb 2007 01:46:51 -0300, susan <[EMAIL PROTECTED]>  
escribió:

>> > $ python ./pyExcelerator/setup.py install
>>
>> Try this instead:
>> $ cdpyExcelerator
>> $ python ./setup.py install

> I still wonder why my way didn't work. I think maybe there's some hard
> code of installation directory, hence, installation won't be succesful
> if the directory is not exactly the same as the one in README.

It doesn't matter the directory name, what matters is that you run the  
script from the install dir (where setup.py resides) and not from other  
place.

-- 
Gabriel Genellina

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


message processing/threads

2007-02-11 Thread Jonathan Curran
I've been thinking about this for a bit and wanted some input as to the design 
of it. The problem is as such:

I need a program running in the background to process messages (FIFO order) 
which I would send using soap/xmlrpc/pyro (haven't decided yet). According to 
my thinking I would need to make this a threaded application. One thread to 
process the messages and the other thread(s) would be used to listen for 
messages and insert it into the message queue.

Is my thinking correct? Is there a better way to do such a thing?

Thanks for any input,

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


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread Samuel Karl Peterson
James Stroud <[EMAIL PROTECTED]> on Sun, 11 Feb 2007 16:53:16 -0800
didst step forth and proclaim thus:

> agent-s wrote:
> > Basically I'm programming a board game and I have to use a list of
> > lists to represent the board (a list of 8 lists with 8 elements each).
> > I have to search the adjacent cells for existing pieces and I was
> > wondering how I would go about doing this efficiently. Thanks
> >
> 
> This isn't very clear. What do you mean by "I have to search the
> adjacent cells for existing pieces"?
> 
> If piece is 1 and empty is 0 and piece is at ary[row][col]:
> 
> import operator
> srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
> is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]])

Wow, maybe it's just me (I'm a pretty bad programmer) but this is
where list comprehensions begin to look unreadable to me.  Here's a
C-like way to do it, (warning, untested in python):

for i in range(8):
for j in range(8):
for offset_i in range(-1,2):
for offset_j in range(-1, 2):
row = i + offset_i
col = j + offset_j
if (row < 0 or row > 7) or (col < 0 or col > 8) \
   or ((row,col) == (i,j)):
continue
# else do something with board[row][col]

I realize this is gross and un-Pythonic and does the same thing the
above code does, but it's probably the way I'd choose to do it :).
Then again, I've been negatively influenced by doing a game of life in
C a few months back.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string.replace non-ascii characters

2007-02-11 Thread Steven Bethard
Samuel Karl Peterson wrote:
> Greetings Pythonistas.  I have recently discovered a strange anomoly
> with string.replace.  It seemingly, randomly does not deal with
> characters of ordinal value > 127.  I ran into this problem while
> downloading auction web pages from ebay and trying to replace the
> "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from
> urllib2.  Yet today, all is fine, no problems whatsoever.  Sadly, I
> did not save the exact error message, but I believe it was a
> ValueError thrown on string.replace and the message was something to
> the effect "character value not within range(128).

Was it something like this?

 >>> u'\xa0'.replace('\xa0', '')
Traceback (most recent call last):
   File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: 
ordinal not in range(128)

You might get that if you're mixing str and unicode. If both strings are 
of one type or the other, you should be okay:

 >>> u'\xa0'.replace(u'\xa0', '')
u''
 >>> '\xa0'.replace('\xa0', '')
''

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


Re: About getattr()

2007-02-11 Thread Samuel Karl Peterson
"Jm lists" <[EMAIL PROTECTED]> on Mon, 12 Feb 2007 12:36:10
+0800 didst step forth and proclaim thus:

> Hello,
> 
> Since I can write the statement like:
> 
> >>> print os.path.isdir.__doc__
> Test whether a path is a directory
> 
> Why do I still need the getattr() func as below?
> 
> >>> print getattr(os.path,"isdir").__doc__
> Test whether a path is a directory

getattr lets you lookup an attribute given a string, so the attribute
wouldn't have to be hardcoded in your program, it could come from a
file, or from user input.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About getattr()

2007-02-11 Thread Leif K-Brooks
Jm lists wrote:
> Since I can write the statement like:
> 
 print os.path.isdir.__doc__
> Test whether a path is a directory
> 
> Why do I still need the getattr() func as below?
> 
 print getattr(os.path,"isdir").__doc__
> Test whether a path is a directory

You don't. getattr() is only useful when the attribute name is 
determined at runtime.
-- 
http://mail.python.org/mailman/listinfo/python-list


string.replace non-ascii characters

2007-02-11 Thread Samuel Karl Peterson
Greetings Pythonistas.  I have recently discovered a strange anomoly
with string.replace.  It seemingly, randomly does not deal with
characters of ordinal value > 127.  I ran into this problem while
downloading auction web pages from ebay and trying to replace the
"\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from
urllib2.  Yet today, all is fine, no problems whatsoever.  Sadly, I
did not save the exact error message, but I believe it was a
ValueError thrown on string.replace and the message was something to
the effect "character value not within range(128).

Some googling seemed to indicate other people have reported similar
troubles:

http://mail.python.org/pipermail/python-list/2006-July/391617.html

Anyone have any enlightening advice for me?

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No module named pyExcelerator Error

2007-02-11 Thread susan
On Feb 11, 11:22 pm, Samuel Karl Peterson
<[EMAIL PROTECTED]> wrote:
> "susan" <[EMAIL PROTECTED]> on 11 Feb 2007 16:55:35 -0800 didst
> step forth and proclaim thus:
>
> > Hi,
> > I'm new of Python, and this problem stucked me whole day but can't be
> > solved.
>
> [snip]
>
> > anybody can tell me where's wrong please? Thanks in advance!
>
> What are the contents of sys.path from an interactive prompt?  Have
> you tried the official windows Python?  Is there a reason you need to
> use the cygwin Python?
>
> --
> Sam Peterson
> skpeterson At nospam ucdavis.edu
> "if programmers were paid to remove code instead of adding it,
> software would be much better" -- unknown

Hi Sam,
There's no any special reason I use cygwin python, I just feel it's
easy and convinent to download and install.
Do you have any better suggestion?

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


Re: No module named pyExcelerator Error

2007-02-11 Thread susan
On Feb 11, 8:16 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
> On Feb 12, 11:55 am, "susan" <[EMAIL PROTECTED]> wrote:
>
> > Hi,
> > I'm new of Python, and this problem stucked me whole day but can't be
> > solved.
>
> > I use python 2.4.3, which is download from cygwin packages.
>
> Is your Python installation working properly for you with other
> things, or is installingpyExceleratorthe first thing that you have
> tried?
>
> > Then I
> > downloadedpyexcelerator-0.5.3a, unzip it,
>
> Is that "5" a typo? The latest version is 0.6.3a
>
>
>
> > $ python ./pyExcelerator/setup.py install
>
> Try this instead:
> $ cdpyExcelerator
> $ python ./setup.py install
>
> i.e. do what thepyExceleratorREADME tells you to do.
> """
> 0x0003. Installation.
> 
> As usually: python ./setup.py install
> """
> This may make a positive difference; it can't be worse.
>
> HTH,
> John

Dear John,

Thank you so much! I tried as you said, finally it works. You are
right, the version should be 0.6.3a.
I still wonder why my way didn't work. I think maybe there's some hard
code of installation directory, hence, installation won't be succesful
if the directory is not exactly the same as the one in README.

cheers,

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


Re: Saving PyOpenGl figures as ps

2007-02-11 Thread Mike C. Fletcher
Frank wrote:
> Hi,
>
> I installed pyopengl (opengl for python) on my linux box and
> everything works fine. But now I want to save the generated images as,
> e.g., ps or eps. How can I do that and how can I adjust the resolution
> (if necessary)? This is probably simple but for some reason I can not
> find out how to do that.
>
> I appreciate every hint!
>
> Thanks, Frank
>   
Hi Frank,

Take a look at the demos in OpenGL, particularly:

OpenGL-ctypes/OpenGL/Demo/GLUT/tom/conesave.py

which is a little GLUT application that renders into a GLUT windows and 
then allows you to save it. That's raster operation though (i.e. 
produces a PNG or JPG).  Raster operations can only save a portion of 
the screen as rendered, so if you want a higher resolution image you 
need to make a larger window.  If you want to get more advanced you can 
try using an off-screen buffer (pbuffer or MESA) for the rendering, 
which may (depending on implementation) allow for higher resolutions.

If you want a true vector graphic (PS, EPS) you'll need to use something 
like GL2PS.

http://www.geuz.org/gl2ps/

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


standardized us address

2007-02-11 Thread mark

Hi
Is there any python module that will convert address to standard US address
format:
for ex:

314 south chauncey avenue

should be:
314 s chauncey ave


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

About getattr()

2007-02-11 Thread Jm lists
Hello,

Since I can write the statement like:

>>> print os.path.isdir.__doc__
Test whether a path is a directory

Why do I still need the getattr() func as below?

>>> print getattr(os.path,"isdir").__doc__
Test whether a path is a directory

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


how to store and still search special characters in Python and MySql

2007-02-11 Thread ronrsr
I have an MySQL database called zingers. The structure is:

zid - integer, key, autoincrement
keyword - varchar
citation - text
quotation - text

I am having trouble storing text, as typed in latter two fields.
Special characters and punctuation all seem not to be stored and
retrieved correctly.

Special apostrophes and single quotes from Microsoft Word are causing
a
special problem, even though I have ''ed all 's

perhaps the encoding of the database itself should be different? it
is
currenlty latin_swedish_ci

Input and output is through a browser.

I think my problem may be that I need to encode the string before
saving it in the databse. Can anyone point me in the right direction
here?

here's the error message:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position
95: ordinal not in range(128)
  args = ('ascii', "update zingers set keywords =
'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal
not
in range(128)')
  encoding = 'ascii'
  end = 96
  object = "update zingers set keywords = 'a;Action;b;Religi...
\n
\n \n ' where zid = 422"
  reason = 'ordinal not in range(128)'
  start = 95

the characters I am trying to add are startquote and endquote copied
and pasted from Microsoft Word.

Can anyone help me on this?

bests,

-rsr-

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


Re: No module named pyExcelerator Error

2007-02-11 Thread Samuel Karl Peterson
"susan" <[EMAIL PROTECTED]> on 11 Feb 2007 16:55:35 -0800 didst
step forth and proclaim thus:

> Hi,
> I'm new of Python, and this problem stucked me whole day but can't be
> solved.

[snip]

> anybody can tell me where's wrong please? Thanks in advance!

What are the contents of sys.path from an interactive prompt?  Have
you tried the official windows Python?  Is there a reason you need to
use the cygwin Python?

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saving PyOpenGl figures as ps

2007-02-11 Thread Vasily Sulatskov
On Feb 12, 3:11 am, "Frank" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I installed pyopengl (opengl for python) on my linux box and
> everything works fine. But now I want to save the generated images as,
> e.g., ps or eps. How can I do that and how can I adjust the resolution
> (if necessary)? This is probably simple but for some reason I can not
> find out how to do that.
>
> I appreciate every hint!

Well, that's not that simple. Search the web, there are several
tutorials about PostScipt output.

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


Re: Help with Optimization of Python software: real-time audio controller

2007-02-11 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> So, for a music-based application where it's crucial to have real-time
> execution of serial writeouts and audio, as well as keeping a
> continual poll on the input from the same portcan this be done
> successfully in Python?  Does using Tkinter have anything to do with
> my timing issues?  Would it benefit me to move over to wxPython
> (something I've been considering doing)?  As for the metronome, should
> I incorporate the metronome thread into the "song processing" thread,
> since both are dealing with events whose timing is crucial?

I think you can't really do that, not just because of Python but also
as a result of using a multitasking OS that's not especially designed
for real time.  You have to rely on some buffering in the audio
hardware, so you don't have to be sample-accurate with the timings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Optimization of Python software: real-time audio controller

2007-02-11 Thread Vasily Sulatskov
Perhaps boosting priorities for time critical threads will help.

I don't know about MacOS but for Win32 something like that helps:

thread = win32api.GetCurrentThread()
win32process.SetThreadPriority(thread,
win32process.THREAD_PRIORITY_TIME_CRITICAL)

current_process = win32process.GetCurrentProcess()
win32process.SetPriorityClass(current_process,
win32process.REALTIME_PRIORITY_CLASS)


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


Re: How to find all the same words in a text?

2007-02-11 Thread Samuel Karl Peterson
[EMAIL PROTECTED] on 11 Feb 2007 08:16:11 -0800 didst step
forth and proclaim thus:

> More concisely:
> 
> import re
> 
> pattern = re.compile(r'\b324\b')
> indices = [ match.start() for match in
> pattern.finditer(target_string) ]
> print "Indices", indices
> print "Count: ", len(indices)
> 

Thank you, this is educational.  I didn't realize that finditer
returned match objects instead of tuples.

> Cheers,
> Steven
> 

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read/write 2D data from/to file..?

2007-02-11 Thread Vasily Sulatskov
On Feb 12, 6:47 am, "mech point" <[EMAIL PROTECTED]> wrote:
> I was able to read the data from file into a two dimensional array
> (lists)
>
> rows=[map(float,line.split())for line in file("data")]
>
> but How to write them back into the file.

Using matplotlib it will be:

import pylab
rows = pylab.load('src.dat')
pylab.save(rows, 'dst.dat')



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


Re: Read/write 2D data from/to file..?

2007-02-11 Thread Grant Edwards
On 2007-02-12, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2007-02-12, mech point <[EMAIL PROTECTED]> wrote:
>>
>> I was able to read the data from file into a two dimensional array
>> (lists)
>>
>> rows=[map(float,line.split())for line in file("data")]
>>
>> but How to write them back into the file.
>
> for r in rows:
> file.write(" ".join(map(str,r)) + "\n")

Doh.  Bad choice of names for my file object:

f = file("data","w")
for r in rows:
f.write(" ".join(map(str,r)) + "\n")

You can do it on one line if you want, but I find the above a
little bit clearer.  

-- 
Grant Edwards   grante Yow!  Spreading peanut
  at   butter reminds me of
   visi.comopera!! I wonder why?
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with Optimization of Python software: real-time audio controller

2007-02-11 Thread craiglewiston
I've been working on a Python-based music training application for a
few months, and have recently run into what I believe are some basic
limitations (or at least constraints) of Python with regards to
timing.  I'll try and give a decently thorough description, and
hopefully some of you can process this with your knowledge and help
steer me in the right direction.

As mentioned above, my application deals with music training. I have a
Tkinter GUI, which communicates via pyserial with an external device I
built myself.  The code reads in a MIDI file and converts the song to
"output data " for the external device and the GUI, all adjusted to
the user-selected tempo.  While the MIDI file is playing, there are 4
main actions the code must take:
1) Send "output data" signals out to the external hardware.
2) Poll the input from the external hardware device for incoming
keypresses.  If detected, then the play the sound corresponding to
that key.
3) Start and keep a metronome running for the durations of the song.
4) Update GUI

I'm able to get all the above "accomplished" through the use of
threads and a top-level loop (for updating the Tkinter GUI  - if
you've worked with threads and Tkinter, then you know that you can't
update a Tkinter GUI from a thread, but instead have to do it on the
top level loop).

While running, I have  the following threads implemented :
1) song processing thread - this thread steps incrementally through a
data matrix (the "output data"), and updates two variables:  GUI_vars
and  Device_vars
2) metronome thread  - this thread starts at the same time as thread
#1, and outputs a "beep" to the audio chain
3) poll input thread  - this thread loops continually, looking for
data on the serial Input.  When data is found, it starts playing the
sound corresponding to that key until a "note off" signal is received
4) top-level recursive loop (technically not a thread) for updating
GUI and calling Serial Write subfunction.  This loop monitors GUI_vars
and Device_vars, updating the GUI and writing out to the device when
either variable has changed

Currently, I have all of the above "working", although I'm running
into some serious timing issues.  When I run the program, I get
irregular timing for my metronome (if it sounds at all), as well as
irregular timing in writing to the external device.  It's extremely
crucial that threads #1 & #2 are executed as close to real-time as
possible, as they form the "core" of the song, and their elements
can't be delayed without "messing" the song up considerably.


I've read up quite a bit on different optimization methods in Python,
but am not sure which direction to head.  I've checked out profile,
Psyco, Pyrex, as well as just porting everything over to C.  Since I'm
on a Mac (Power PC), I can't use Psyco.  And doing any of the others
seemed like a big enough project that I should really ask someone else
before I embark.

So, for a music-based application where it's crucial to have real-time
execution of serial writeouts and audio, as well as keeping a
continual poll on the input from the same portcan this be done
successfully in Python?  Does using Tkinter have anything to do with
my timing issues?  Would it benefit me to move over to wxPython
(something I've been considering doing)?  As for the metronome, should
I incorporate the metronome thread into the "song processing" thread,
since both are dealing with events whose timing is crucial?

I'm a relative newbie (this is my first Python project) to Python, so
any help is GREATLY appreciated!

Also, just for reference, here's a list of the modules I'm using and
my system info:
Audio:  SndObj
Ser com: pyserial
GUI: Tkinter
System: Apple PowerBook G4 (PowerPC), Mac OS 10.4, Python 2.4.4

Thanks,
Craig Lewiston

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


Re: Read/write 2D data from/to file..?

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 22:47:30 -0300, mech point <[EMAIL PROTECTED]>  
escribió:

> I was able to read the data from file into a two dimensional array
> (lists)
>
> rows=[map(float,line.split())for line in file("data")]
>
> but How to write them back into the file.

This way uses the same structures as your example; line.split(",") ->  
",".join(...); map(float,...) -> map(str,...)

yourfile.writelines(",".join(map(str,row))+"\n" for row in rows)

If you are using Python<2.5, put [] inside the writelines call:  
writelines([","...]).
Or move the iteration outer. If you want control on the format too:
for row in rows:
   yourfile.write("%.2f,%.6g\n" % (row[0], row[1]))

-- 
Gabriel Genellina

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


Re: Read/write 2D data from/to file..?

2007-02-11 Thread Grant Edwards
On 2007-02-12, mech point <[EMAIL PROTECTED]> wrote:
>
> I was able to read the data from file into a two dimensional array
> (lists)
>
> rows=[map(float,line.split())for line in file("data")]
>
> but How to write them back into the file.

for r in rows:
file.write(" ".join(map(str,r)) + "\n")

-- 
Grant Edwards   grante Yow!  My nose feels like a
  at   bad Ronald Reagan movie...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read/write 2D data from/to file..?

2007-02-11 Thread John Machin
On Feb 12, 12:47 pm, "mech point" <[EMAIL PROTECTED]> wrote:
> I was able to read the data from file into a two dimensional array
> (lists)
>
> rows=[map(float,line.split())for line in file("data")]
>
> but How to write them back into the file.

Presuming that it is either mandatory to adopt the same style (or lack
thereof) as the input code, and/or futile to suggest otherwise:

file('data2','w').write('\n'.join(' '.join(repr(item)for item in
row)for row in rows)+'\n')


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


Re: compound statement from C "?:"

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 19:16:49 -0300, Holger <[EMAIL PROTECTED]> escribió:

>> >> if n == 1:
>> >> print "I saw a car"
>> >> else:
>> >> print "I saw %d cars" % n
>
> Personally I don't like the if-else approach because of the don't-
> repeat-yourself philosophy
>
>> D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is
>> quite clever :-)
> I like this one :-)
>
>> print "I saw %d car%s\n" % (n, ("", "s")[n != 1])
> And this one.

I presume all of this is only used as an example on using expressions. In  
any application with any chances of being i18n, the only viable way is the  
first one. Doing algebra on phrases is a no-no.

-- 
Gabriel Genellina

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


Read/write 2D data from/to file..?

2007-02-11 Thread mech point

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

Thank you,
srikanth

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


Re: compound statement from C "?:"

2007-02-11 Thread BJörn Lindqvist
On 11 Feb 2007 16:57:07 -0800, Carl Banks <[EMAIL PROTECTED]> wrote:
> You don't need any ternary operator to avoid repetition, anyways.  You
> could factor the common parts out like this:
>
> if n == 1:
> what = "a car"
> else:
> what = "%d cars" % n
> print "I saw %s" % what

Or even better (IMHO):

what = "%d cars" % n
if n == 1:
what = "a car"
print "I saw %s" % what

One less line and just as readable.

> but what's the point?  It's just a few repeated characters two lines
> apart.  Peter's version is the most easily read version here,
> including the one using the official ternary operator.

Agreed.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating pdf files in epydoc on Windows

2007-02-11 Thread Duncan Smith
Don Taylor wrote:
> Does anyone know what is needed to install to get epydoc to generate pdf
> files on Windows.  Besides epydoc itself of course.
> 
> Maybe there is a more appropriate forum to ask newbie questions about
> epydoc?
> 

As I remember, LaTeX and ghostscript.

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


Re: No module named pyExcelerator Error

2007-02-11 Thread John Machin
On Feb 12, 11:55 am, "susan" <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm new of Python, and this problem stucked me whole day but can't be
> solved.
>
> I use python 2.4.3, which is download from cygwin packages.

Is your Python installation working properly for you with other
things, or is installing pyExcelerator the first thing that you have
tried?

> Then I
> downloaded pyexcelerator-0.5.3a, unzip it,

Is that "5" a typo? The latest version is 0.6.3a

>
> $ python ./pyExcelerator/setup.py install

Try this instead:
$ cd pyExcelerator
$ python ./setup.py install

i.e. do what the pyExcelerator README tells you to do.
"""
0x0003. Installation.

As usually: python ./setup.py install
"""
This may make a positive difference; it can't be worse.

HTH,
John


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


Re: help please!!

2007-02-11 Thread James Stroud
darren112 wrote:
> Hi Im new to python and I desperately need help with this task
> This is everything of what I need to do...
> 
> The program to be written in Python obviously..
> 
> The program should support brute-forcing of the authentication process
> for a Telnet server via a dictionary attack.
> 
> The python program is required to take four parameters: a) the IP
> address of a Computer, b) the port number that the Telnet server is
> running on the computer , c) the name of a file containing a list if
> usernames, and b) the name of a file containing a list of word/phrases
> to be used as passwords.
> 
> The program should then attempt to authenticate itself to the Telnet
> server via trying every password for every username. The program
> should report when it is successful.
> 
> Please help me And as I am new to all this please post step by
> step instructions...
> 

I'm guessing this is a troll rather than a script kiddy. It seems more 
like bait than an "honest" question.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: randomly generate n of each of two types

2007-02-11 Thread Alan Isaac
"Stargaming" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> ...   types *= n
> ...   shuffle(types)

This again has the "costs" I referred to:
creating a potentially large sequence,
and shuffling it.  (Additionally, shuffle
cannot achieve many of the possible
shuffles of a large list, but I doubt this
is easily evaded.)

So as far as I can tell, this is the same
approach as the original (first) solution.

Cheers,
Alan Isaac


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


Re: compound statement from C "?:"

2007-02-11 Thread Carl Banks
On Feb 11, 5:16 pm, "Holger" <[EMAIL PROTECTED]> wrote:
> Thanks all for good input.
> It seems like there's no the-python-way for this one.
>
> Currently I'm forced to use cygwin - and python in cygwin is still not
> 2.5 so I can't use the new inline if-else ternary operator.
>
> > >> if n == 1:
> > >> print "I saw a car"
> > >> else:
> > >> print "I saw %d cars" % n
>
> Personally I don't like the if-else approach because of the don't-
> repeat-yourself philosophy

You shouldn't be worried a repeating few characters from a short,
simple print statement.  It's not a mortal sin.

You don't need any ternary operator to avoid repetition, anyways.  You
could factor the common parts out like this:

if n == 1:
what = "a car"
else:
what = "%d cars" % n
print "I saw %s" % what

but what's the point?  It's just a few repeated characters two lines
apart.  Peter's version is the most easily read version here,
including the one using the official ternary operator.


Carl Banks

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


No module named pyExcelerator Error

2007-02-11 Thread susan
Hi,
I'm new of Python, and this problem stucked me whole day but can't be
solved.

I use python 2.4.3, which is download from cygwin packages. Then I
downloaded pyexcelerator-0.5.3a, unzip it,

$ python ./pyExcelerator/setup.py install
running install
running build
running build_py
package init file 'pyExcelerator/__init__.py' not found (or not a
regular file)
copying pyExcelerator/setup.py -> build/lib/pyExcelerator
package init file 'pyExcelerator/__init__.py' not found (or not a
regular file)
running install_lib
copying build/lib/pyExcelerator/setup.py -> /usr/lib/python2.4/site-
packages/pyE
xcelerator
byte-compiling /usr/lib/python2.4/site-packages/pyExcelerator/setup.py
to setup.
pyc

But 'pyExcelerator/__init__.py' is absolutely there, I don't know why
I got the warning. Then I tried to import pyExcelerator,
>>> import pyExcelerator
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named pyExcelerator

anybody can tell me where's wrong please? Thanks in advance!

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


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread James Stroud
agent-s wrote:
> Basically I'm programming a board game and I have to use a list of
> lists to represent the board (a list of 8 lists with 8 elements each).
> I have to search the adjacent cells for existing pieces and I was
> wondering how I would go about doing this efficiently. Thanks
> 

This isn't very clear. What do you mean by "I have to search the 
adjacent cells for existing pieces"?

If piece is 1 and empty is 0 and piece is at ary[row][col]:

import operator
srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]])


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


searching a list of lists as a two-dimensional array?

2007-02-11 Thread agent-s
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks

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


Re: Hacking in python

2007-02-11 Thread Marshillboy
On Feb 10, 5:25 pm, "Geoff Hill" <[EMAIL PROTECTED]> wrote:
> The word "hack" can be known as a "smart/quick fix" to a problem.

Giving the benefit of the doubt here, perhaps Enes Naci saw this
article: http://www.hetland.org/python/instant-hacking.php and got
some strange idea about confusing programming with breaking into
computer systems.  Maybe.

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


New Pythin user looking foe some good examples to study

2007-02-11 Thread Johnny Garcia
I have just discovered Python and am familiarizing myself with the syntax 
but I have always found that code examples where the best way for me to 
learn.



Can anyone point me to a site with some good open source functioning python 
applications?



I would appreciate any help.



Also, does anyone know of any good Linux or python user groups in the orange 
county, California area?


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


Re: Database Programming with Python

2007-02-11 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>I wanted to connect Python to Ms-Access database using ADO or ODBC. I
>have Python 2.5 and on mxODBC site, it has no higher version build
>than 2.4. Moreoever, mxODBC is required for ADODB.
>Can anyone guide me on this what should I do to make it work on Python
>2.5? I have python 2.5 running on server.

You don't actually need mxODBC to use ADODB.  As long as you have the
pywin32 extensions, you have what you need.

import win32com.client
conn = win32com.client.Dispatch('ADODB.Connection')
conn.Open( "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=x.mdb" )
cmd = win32com.client.Dispatch('ADODB.Command')
cmd.ActiveConnection = conn

cmd.CommandText = "SELECT firstname,lastname FROM users;"
rs = cmd.Execute()[0]
while not rs.EOF:
# Use elements of rs
rs.MoveNext()

There are samples on the web.  Google should help.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regexps and lists

2007-02-11 Thread John Machin
On Feb 12, 9:08 am, "Paddy" <[EMAIL PROTECTED]> wrote:
> I don't know enough to write an R.E. engine so forgive me if I am
> being naive.
> I have had to atch text involving lists in the past. These are usually
> comma separated words such as
>  "egg,beans,ham,spam,spam"
> you can match that with:
>  r"(\w+)(,\w+)*"

You *can*, but why do that? What are you trying to achieve? What is
the point of distinguishing the first element from the remainder?

See if any of the following do what you want:

| >>> s = "egg,beans,ham,spam,spam"
| >>> s.split(',')
| ['egg', 'beans', 'ham', 'spam', 'spam']
| >>> import re
| >>> re.split(r",", s)
| ['egg', 'beans', 'ham', 'spam', 'spam']
| >>> re.split(r"(,)", s)
| ['egg', ',', 'beans', ',', 'ham', ',', 'spam', ',', 'spam']

> and when you look at the groups you get the following
> >>> import re
> >>> re.match(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups()
> ('egg', ',spam')
>
> Notice how you only get the last match as the second groups value.
>
> It would be nice if a repeat operator acting on a group turned that
> group into a sequence returning every match, in order. (or an empty
> sequence for no matches).
>
> The above exaple would become:
>
>  >>> import re>>> re.newmatch(r"(\w+)(,\w+)*", 
> "egg,beans,ham,spam,spam").groups()
>
> ('egg', ('beans', 'ham', 'spam', ',spam'))

And then what are you going to do with the answer? Something like
this, maybe:

| >>> actual_answer = ('egg', ('beans', 'ham', 'spam', ',spam'))
| >>> [actual_answer[0]] +list(actual_answer[1])
| ['egg', 'beans', 'ham', 'spam', ',spam']


> 1, Is it possible?

Maybe, but I doubt the utility ...

> do any other RE engines do this?

If your Google is not working, then mine isn't either.

> 2, Should it be added to Python?

No.

HTH,

John

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


Re: Parsing HTML

2007-02-11 Thread Paul McGuire
On Feb 10, 5:03 pm, "mtuller" <[EMAIL PROTECTED]> wrote:
> Alright. I have tried everything I can find, but am not getting
> anywhere. I have a web page that has data like this:
>
> 
> 
> LETTER
> 
> 33,699
> 
> 1.0
> 
> 
>
> What is show is only a small section.
>
> I want to extract the 33,699 (which is dynamic) and set the value to a
> variable so that I can insert it into a database. I have tried parsing
> the html with pyparsing, and the examples will get it to print all
> instances with span, of which there are a hundred or so when I use:
>
> for srvrtokens in printCount.searchString(printerListHTML):
> print srvrtokens
>
> If I set the last line to srvtokens[3] I get the values, but I don't
> know grab a single line and then set that as a variable.
>

So what you are saying is that you need to make your pattern more
specific.  So I suggest adding these items to your matching pattern:
- only match span if inside a  with attribute 'headers="col2_1"'
- only match if the span body is an integer (with optional comma
separater for thousands)

This grammar adds these more specific tests for matching the input
HTML (note also the use of results names to make it easy to extract
the integer number, and a parse action added to integer to convert the
'33,699' string to the integer 33699).

-- Paul


htmlSource = """

LETTER

33,699

1.0

"""

from pyparsing import makeHTMLTags, Word, nums, ParseException

tdStart, tdEnd = makeHTMLTags('td')
spanStart, spanEnd = makeHTMLTags('span')

def onlyAcceptWithTagAttr(attrname,attrval):
def action(tagAttrs):
if not(attrname in tagAttrs and tagAttrs[attrname]==attrval):
raise ParseException("",0,"")
return action

tdStart.setParseAction(onlyAcceptWithTagAttr("headers","col2_1"))
spanStart.setParseAction(onlyAcceptWithTagAttr("class","hpPageText"))

integer = Word(nums,nums+',')
integer.setParseAction(lambda t:int("".join(c for c in t[0] if c !=
',')))

patt = tdStart + spanStart + integer.setResultsName("intValue") +
spanEnd + tdEnd

for matches in patt.searchString(htmlSource):
print matches.intValue

prints:
33699


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


Re: compound statement from C "?:"

2007-02-11 Thread Holger
Thanks all for good input.
It seems like there's no the-python-way for this one.

Currently I'm forced to use cygwin - and python in cygwin is still not
2.5 so I can't use the new inline if-else ternary operator.

> >> if n == 1:
> >> print "I saw a car"
> >> else:
> >> print "I saw %d cars" % n

Personally I don't like the if-else approach because of the don't-
repeat-yourself philosophy

> D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is
> quite clever :-)
>
> Peter

I like this one :-)

> print "I saw %d car%s\n" % (n, ("", "s")[n != 1])

And this one.

/Holger

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


Saving PyOpenGl figures as ps

2007-02-11 Thread Frank
Hi,

I installed pyopengl (opengl for python) on my linux box and
everything works fine. But now I want to save the generated images as,
e.g., ps or eps. How can I do that and how can I adjust the resolution
(if necessary)? This is probably simple but for some reason I can not
find out how to do that.

I appreciate every hint!

Thanks, Frank

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


Regexps and lists

2007-02-11 Thread Paddy
I don't know enough to write an R.E. engine so forgive me if I am
being naive.
I have had to atch text involving lists in the past. These are usually
comma separated words such as
 "egg,beans,ham,spam,spam"
you can match that with:
 r"(\w+)(,\w+)*"
and when you look at the groups you get the following

>>> import re
>>> re.match(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups()
('egg', ',spam')
>>>

Notice how you only get the last match as the second groups value.

It would be nice if a repeat operator acting on a group turned that
group into a sequence returning every match, in order. (or an empty
sequence for no matches).

The above exaple would become:

 >>> import re
>>> re.newmatch(r"(\w+)(,\w+)*", "egg,beans,ham,spam,spam").groups()
('egg', ('beans', 'ham', 'spam', ',spam'))
>>>

1, Is it possible? do any other RE engines do this?
2, Should it be added to Python?

- Paddy.

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


Re: Regular Expressions

2007-02-11 Thread Steve Holden
[EMAIL PROTECTED] wrote:
>> That's a little harsh -- regexes have their place, together with pointer
>> arithmetic, bit manipulations, reverse polish notation and goto. The
>> problem is when people use them inappropriately e.g. using a regex when a
>> simple string.find will do.
>>
>>> A quote attributed variously to
>>> Tim Peters and Jamie Zawinski says "Some people, when confronted with a
>>> problem, think 'I know, I'll use regular expressions.' Now they have two
>>> problems."
>> I believe that is correctly attributed to Jamie Zawinski.
>>
>> --
>> Steven
> 
> So as a newbie, I have to ask. I've played with the re module now for
> a while, I think regular expressions are super fun and useful. As far
> as them being a problem I found they can be tricky and sometimes the
> regex's I've devised do unexpected things...(which I can think of two
> instances where that unexpected thing was something that I had hoped
> to get into further down the line, yay for me!). So I guess I don't
> really understand why they are a "bad idea" to use. I don't know of
> any other way yet to parse specific data out of a text, html, or xml
> file without resorting to regular expressions.
> What other ways are there?
> 
Re's aren't inherently bad. Just avoid using them as a hammer to the 
extent that all your problems look like nails.

They wouldn't exist if there weren't problems it was appropriate to use 
them on. Just try to use simpler techniques first.

For example, don't use re's to find out if a string starts with a 
specific substring when you could instead use the .startswith() string 
method.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: Problem with reimporting modules

2007-02-11 Thread Christoph Zwerschke
Thanks for the detailed explanations, Gabriel.

> At that time, all values in the module namespace are set to 
> None (for breaking possible cycles, I presume). print_hello now has a 
> func_globals with all names set to None. (Perhaps the names could have 
> been deleted instead, so print_hello() would raise a NameError, but I'm 
> just describing the current CPython implementation)

Yes, that was the thing that confused me a bit. I had expected that an 
error is raised or that the namespace has a reference to the module and 
is reestablished when the module has been reloaded.

Anyway, I have solved the problem in a different way now.

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


Re: randomly generate n of each of two types

2007-02-11 Thread Stargaming
Alan Isaac schrieb:
> I need access to 2*n random choices for two types
> subject to a constraint that in the end I have
> drawn n of each.  I first tried::
> 
> def random_types(n,typelist=[True,False]):
> types = typelist*n
> random.shuffle(types)
> for next_type in types:
> yield next_type
> 
> This works but has some obvious costs.
> To avoid those I considered this instead::
> 
> def random_types(n,typelist=[True,False]):
> type0, type1 = typelist
> ct0, ct1 = 0,0
> while ct0+ct1<2*n:
> if random.random() < ((n-ct0)/(2*n-ct0-ct1)):
> next_type = type0
> ct0 += 1
> else:
> next_type = type1
> ct1 += 1
> yield next_type
> 
> Does this seem a good way to go?  Comments welcome.

I think there's any easier way using random's function `shuffle`.

 >>> from random import shuffle
 >>> def randomly(n, types):
...   types *= n
...   shuffle(types)
...   for x in types: yield x
...
 >>> randomly(1, [True, False])

 >>> list(randomly(1, [True, False]))
[True, False]
 >>> list(randomly(2, [True, False]))
[True, False, True, False]
 >>> list(randomly(4, [True, False]))
[False, True, False, False, False, True, True, True]

You can even do this with an arbitrary number of choices:
 >>> list(randomly(2, [True, False, None, NotImplemented]))
[NotImplemented, None, NotImplemented, False, False, None, True, True]

Notice that this method works in-place, ie
 >>> a = [True, False]
 >>> list(randomly(2, a))
[False, False, True, True]
 >>> a # a changed!
[False, False, True, True]

This can be changed by creating a copy, though.

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


MySQLdb binaries (was Re: huge amounts of pure...)

2007-02-11 Thread John J. Lee
Robin Becker <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] wrote:
> > John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no
> > John> tested Windows executable available, although there's an untested
> > John> version from a World of Warcraft guild available.
> > As Andy Dustman has pointed out a number of times, he doesn't do
> > Windows.
> > Someone in the MySQLdb community who does use Windows is going to have to
> > fill that void.
> ..
> 
> well I have managed to build both extant versions
> (MySQL-python-1.2.1_p2 & MySQL-python-1.2.2b2) from source with the
> aid of Mr Dustman's comments in the site.cfg files and a very minor
> hack to the earlier version. I had to have the sources for Mysql
> available as well, but that probably comes with the territory. It
> seems the very latest version won't play well with earlier MySQL so I
> used MySQL-python-1.2.1_p2 as we are still using some 4.0.27 databases.
> 
> Given that I used a particular version of MySQL, 5.0.33, to build
> against I'm not certain that my builds are useful for everyone. I copy
> here the differences I had to make to the source to get stuff to build
> and run against stock win32 Python-2.5
[...]

Robin may be right, but the resulting binaries are here (not
supported, use at your own risk):

http://www.reportlab.org/ftp/MySQLdb-1.1.2b2-win32-py25.zip

or

ftp://www.reportlab.org/MySQLdb-1.1.2b2-win32-py25.zip


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


Re: help please!!

2007-02-11 Thread azrael
Hey yo kiddie, I hope that you are using the web for some time. So you
can get the meaning from my post.:


LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL, ROTF, LOL,
ROTF, LOL, ROTF, LOL, ROTF,

my stomach hurts

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


Re: urllib2 request htaccess page through proxy

2007-02-11 Thread John J. Lee
Alessandro Fachin <[EMAIL PROTECTED]> writes:

> I write this simply code that should give me the access to private page with
> htaccess using a proxy, i don't known because it's wrong... 
[...]
> i get no access on access.log from apache2 and nothing from the proxy in
> tcpdump log. If i use only the proxy with a page that doesn't use htaccess
> it works... if anyone could help,regards...
[...]
> urllib2.HTTPError: HTTP Error 401: Authorization Required

Works for me (using Squid and Apache both running on localhost).
Looking at what goes over the wire, I see a 401 followed by a 299
response, which is what is expected (the 401 prompts the client to
send the username and password, which is then rewarded with the 200).

Could you describe in more detail what your proxy and Apache
configuration are like?  And more about your network (on what machines
do proxy, HTTP server, and HTTP client run -- all on the same machine,
some on the same machine, all three on three different machines?)  The
more detail the better.


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


Re: Regular Expressions

2007-02-11 Thread John Machin
On Feb 12, 3:35 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> > That's a little harsh -- regexes have their place, together with pointer
> > arithmetic, bit manipulations, reverse polish notation and goto. The
> > problem is when people use them inappropriately e.g. using a regex when a
> > simple string.find will do.
>
> > > A quote attributed variously to
> > > Tim Peters and Jamie Zawinski says "Some people, when confronted with a
> > > problem, think 'I know, I'll use regular expressions.' Now they have two
> > > problems."
>
> > I believe that is correctly attributed to Jamie Zawinski.
>
> > --
> > Steven
>
> So as a newbie, I have to ask. I've played with the re module now for
> a while, I think regular expressions are super fun and useful. As far
> as them being a problem I found they can be tricky and sometimes the
> regex's I've devised do unexpected things...(which I can think of two
> instances where that unexpected thing was something that I had hoped
> to get into further down the line, yay for me!). So I guess I don't
> really understand why they are a "bad idea" to use.

Regexes are not "bad". However people tend to overuse them, whether
they are overkill (like Gabriel's date-splitting example) or underkill
-- see your next sentence :-)

> I don't know of
> any other way yet to parse specific data out of a text, html, or xml
> file without resorting to regular expressions.
> What other ways are there?

Text: Paul Maguire's pyparsing module (Google is your friend); read
David Mertz's book on text processing with Python (free download, I
believe); modules for specific data formats e.g. csv

HTML: htmllib and HTMLParser (both in the Python library),
BeautifulSoup (again GIYF)

XML: xml.* in the Python library. ElementTree (recommended) is
included in Python 2.5; use xml.etree.cElementTree.

HTH,
John

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


Re: help please!!

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 16:40:45 -0300, darren112 <[EMAIL PROTECTED]>  
escribió:

> The program should support brute-forcing of the authentication process
> for a Telnet server via a dictionary attack.

You should first read the Python Tutorial. After you get proficient with  
the basic programming structures, reading and writing files, networking,  
then use the telnetlib module (included with the standard Python library)  
to write your program. Depending on your previous experience and daily  
time, that might take from a couple days to one or two months.

-- 
Gabriel Genellina

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


Re: Problem with reimporting modules

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 15:56:16 -0300, Christoph Zwerschke <[EMAIL PROTECTED]>  
escribió:

> Yes I know about reload(), but TurboGears (TurboKid) does not use it and
> the docs say that removing modules from sys.module is possible to force
> reloading of modules. I don't want to rewrite everything since it's a
> pretty complex thing with modules which are compiled from templates
> which can depend from other templates etc...

If you remove the module from sys.modules, when you import it again you  
end up with a *new*, fresh, module object, unrelated to the original one.

Quoting your original message again:

> I tracked it down to the following behavior of Python. Assume you have a
> module hello.py like that:
>   hello. py 
> greeting = 'Hello!'
> def print_hello():
>  print greeting
> ---
>  Now run the following code:
>  from hello import print_hello
> print_hello()
> import sys
> del sys.modules['hello'] # delete module
> import hello # recreate module
> print_hello()
>  The second print_hello() prints "None" instead of "Hello!". Why is that?

Notice that you are mixing references here. You first import print_hello  
 from hello, and after deleting the module, you import hello (not  
print_hello). And you expect that your old reference to print_hello now  
refers to the new function. The whole point of reloading/reimporting a  
module is to get the *new* contents, but that only works if you refer to  
things using the module.function notation, not if you hold a reference to  
the function (which will always be the original function).

In short, your code should be:

import hello
hello.print_hello()
import sys
del sys.modules['hello']
import hello
hello.print_hello()

or, using reload:

import hello
hello.print_hello()
reload(hello)
hello.print_hello()

If you think that always typing module.function is too much - well, don't  
try to reload modules then :)
Somewhere I read that at Google the policy is to always import modules,  
never functions, and this may be a good reason for it.

If you want to know the details: print_hello doesn't hold a reference to  
the containing module, only to its namespace, in the func_globals  
attribute. When you delete the last reference to the module, it gets  
destroyed. At that time, all values in the module namespace are set to  
None (for breaking possible cycles, I presume). print_hello now has a  
func_globals with all names set to None. (Perhaps the names could have  
been deleted instead, so print_hello() would raise a NameError, but I'm  
just describing the current CPython implementation)

-- 
Gabriel Genellina

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


Re: help please!!

2007-02-11 Thread Jonathan Curran
On Sunday 11 February 2007 13:40, darren112 wrote:
> Hi Im new to python and I desperately need help with this task
> This is everything of what I need to do...
>
> The program to be written in Python obviously..
>
> The program should support brute-forcing of the authentication process
> for a Telnet server via a dictionary attack.
>
> The python program is required to take four parameters: a) the IP
> address of a Computer, b) the port number that the Telnet server is
> running on the computer , c) the name of a file containing a list if
> usernames, and b) the name of a file containing a list of word/phrases
> to be used as passwords.
>
> The program should then attempt to authenticate itself to the Telnet
> server via trying every password for every username. The program
> should report when it is successful.
>
> Please help me And as I am new to all this please post step by
> step instructions...

/me points and laughs at you. Hahahahaha, stupid script kiddie. Get a life.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help please!!

2007-02-11 Thread azrael
well, this sounds funn.

1) dont expect someone to do your homework.
2) dont expect someone to do dirty homework
3) dont expect someone to do your home work especially when it's
something that could make you problems, or the person that is helping
you
4) from your message i can "read" that you need the application, and
not some knowledge. I don't know what other guys here think about it,
if my opinion can considered, you are on your own.

i suggest you take a python tutorial and learn how to do it yourself.
This situation stinks.






On Feb 11, 8:40 pm, "darren112" <[EMAIL PROTECTED]> wrote:
> Hi Im new to python and I desperately need help with this task
> This is everything of what I need to do...
>
> The program to be written in Python obviously..
>
> The program should support brute-forcing of the authentication process
> for a Telnet server via a dictionary attack.
>
> The python program is required to take four parameters: a) the IP
> address of a Computer, b) the port number that the Telnet server is
> running on the computer , c) the name of a file containing a list if
> usernames, and b) the name of a file containing a list of word/phrases
> to be used as passwords.
>
> The program should then attempt to authenticate itself to the Telnet
> server via trying every password for every username. The program
> should report when it is successful.
>
> Please help me And as I am new to all this please post step by
> step instructions...


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


Re: help please!!

2007-02-11 Thread hg
darren112 wrote:

> Hi Im new to python and I desperately need help with this task
> This is everything of what I need to do...
> 
> The program to be written in Python obviously..
> 
> The program should support brute-forcing of the authentication process
> for a Telnet server via a dictionary attack.
> 
> The python program is required to take four parameters: a) the IP
> address of a Computer, b) the port number that the Telnet server is
> running on the computer , c) the name of a file containing a list if
> usernames, and b) the name of a file containing a list of word/phrases
> to be used as passwords.
> 
> The program should then attempt to authenticate itself to the Telnet
> server via trying every password for every username. The program
> should report when it is successful.
> 
> Please help me And as I am new to all this please post step by
> step instructions...

That is funny !

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


help please!!

2007-02-11 Thread darren112
Hi Im new to python and I desperately need help with this task
This is everything of what I need to do...

The program to be written in Python obviously..

The program should support brute-forcing of the authentication process
for a Telnet server via a dictionary attack.

The python program is required to take four parameters: a) the IP
address of a Computer, b) the port number that the Telnet server is
running on the computer , c) the name of a file containing a list if
usernames, and b) the name of a file containing a list of word/phrases
to be used as passwords.

The program should then attempt to authenticate itself to the Telnet
server via trying every password for every username. The program
should report when it is successful.

Please help me And as I am new to all this please post step by
step instructions...

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


Re: Pyhton script

2007-02-11 Thread Jonathan Curran
On Sunday 11 February 2007 11:47, soussou97 wrote:
> Hi;
>
> I would like to automatically delivery, I seek a script in python which
> will be excecute from a Windows station to allows via sftp:
>
> 1- to connect to a Linux server for storing of the files
> 2- Next execute on the Linux server, some actions: Copy, gzip, mv etc...
> 3- to use a config file for the parameters: server name, login, password...
>
> Regards;
> --
> View this message in context:
> http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801 Sent from the
> Python - python-list mailing list archive at Nabble.com.

Just joking with the last message, though I hope that you weren't looking for 
someone to just send it to you. Take a look at Paramiko, it's exactly the 
library you need to do these things.

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


Re: Pyhton script

2007-02-11 Thread Jonathan Curran
On Sunday 11 February 2007 11:47, soussou97 wrote:
> Hi;
>
> I would like to automatically delivery, I seek a script in python which
> will be excecute from a Windows station to allows via sftp:
>
> 1- to connect to a Linux server for storing of the files
> 2- Next execute on the Linux server, some actions: Copy, gzip, mv etc...
> 3- to use a config file for the parameters: server name, login, password...
>
> Regards;
> --
> View this message in context:
> http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801 Sent from the
> Python - python-list mailing list archive at Nabble.com.

How much are you willing to spend on this script? ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an XML fragment as a child node in a pre-existing Element tree

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 15:15:21 -0300, Rajarshi <[EMAIL PROTECTED]>  
escribió:

> Hi, I'm using ElementTree for some RSS processing. The point where I
> face a problem is that within an  I need to add another
> child node (in addition to  etc) which is a well-formed XML
> document (Chemical Markup Language to be precise).
>
> So my code looks like:
>
> import cElementTree as ET
>
> c = open('x.cml').readlines()
> c = string.join(c)
> cml = ET.XML(c)

All the above thing can be replaced by:
cml = ET.parse("x.cml")

>
> Now I also have the following code:
>
> def addItem(self, title, link, description, cml = None):
> RSSitem = ET.SubElement ( self.RSSchannel, 'item' )
>
> ET.SubElement( RSSitem, 'title' ).text = title
> ET.SubElement( RSSitem, 'description' ).text = description
>
> What I'm confused is how I can add the cml Element object that I
> generated, to the RSSitem as a child node.

SubElement is just a convenience function for creating a new element and  
appending it to an existing parent element. As you already have the new  
subelement, just use append:

RSSitem.append(cml)

See the documentation at http://www.effbot.org/zone/element-index.htm

-- 
Gabriel Genellina

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


Re: Problem with reimporting modules

2007-02-11 Thread Christoph Zwerschke
Yes I know about reload(), but TurboGears (TurboKid) does not use it and 
the docs say that removing modules from sys.module is possible to force 
reloading of modules. I don't want to rewrite everything since it's a 
pretty complex thing with modules which are compiled from templates 
which can depend from other templates etc...
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding an XML fragment as a child node in a pre-existing Element tree

2007-02-11 Thread Rajarshi
Hi, I'm using ElementTree for some RSS processing. The point where I
face a problem is that within an  I need to add another
child node (in addition to  etc) which is a well-formed XML
document (Chemical Markup Language to be precise).

So my code looks like:

import cElementTree as ET

c = open('x.cml').readlines()
c = string.join(c)
cml = ET.XML(c)

Now I also have the following code:

def addItem(self, title, link, description, cml = None):
RSSitem = ET.SubElement ( self.RSSchannel, 'item' )

ET.SubElement( RSSitem, 'title' ).text = title
ET.SubElement( RSSitem, 'description' ).text = description

What I'm confused is how I can add the cml Element object that I
generated, to the RSSitem as a child node.

Do I need to manually traverse the tree of the CML document and add it
one by one to the RSSitem as a child node? Or is there a smarter way
to do this?

Any pointers would be greatly appreciated
Thanks,

Rajarshi

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


Re: Regular Expressions

2007-02-11 Thread Gabriel Genellina
En Sun, 11 Feb 2007 13:35:26 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:

>> (Steven?)
>> That's a little harsh -- regexes have their place, together with pointer
>> arithmetic, bit manipulations, reverse polish notation and goto. The
>> problem is when people use them inappropriately e.g. using a regex when  
>> a
>> simple string.find will do.
>
> So as a newbie, I have to ask. I've played with the re module now for
> a while, I think regular expressions are super fun and useful. As far
> as them being a problem I found they can be tricky and sometimes the
> regex's I've devised do unexpected things...(which I can think of two
> instances where that unexpected thing was something that I had hoped
> to get into further down the line, yay for me!). So I guess I don't
> really understand why they are a "bad idea" to use. I don't know of
> any other way yet to parse specific data out of a text, html, or xml
> file without resorting to regular expressions.
> What other ways are there?

For very simple things, it's easier/faster to use string methods like find  
or split. By example, splitting "2007-02-11" into y,m,d parts:
y,m,d = date.split("-")
is a lot faster than matching "(\d+)-(\d+)-(\d+)"
On the other hand, complex tasks like parsing an HTML/XML document,  
*can't* be done with a regexp alone; but people insist anyway, and then  
complain when it doesn't work as expected, and ask how to "fix" the  
regexp...
Good usage of regexps maybe goes in the middle.

-- 
Gabriel Genellina

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


Re: Regular Expressions

2007-02-11 Thread skip

jwz> Some people, when confronted with a problem, think 'I know, I'll
jwz> use regular expressions.' Now they have two problems.

dbl> So as a newbie, I have to ask  So I guess I don't really
dbl> understand why they are a "bad idea" to use. 

Regular expressions are fine in their place, however, you can get carried
away.  For example:

http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html

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


Generating pdf files in epydoc on Windows

2007-02-11 Thread Don Taylor
Does anyone know what is needed to install to get epydoc to generate pdf
files on Windows.  Besides epydoc itself of course.

Maybe there is a more appropriate forum to ask newbie questions about 
epydoc?

Thanks,

Don.

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


Pyhton script

2007-02-11 Thread soussou97

Hi; 

I would like to automatically delivery, I seek a script in python which will
be excecute from a Windows station to allows via sftp: 

1- to connect to a Linux server for storing of the files
2- Next execute on the Linux server, some actions: Copy, gzip, mv etc... 
3- to use a config file for the parameters: server name, login, password...

Regards;
-- 
View this message in context: 
http://www.nabble.com/Pyhton-script-tf3209528.html#a8912801
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: randomly generate n of each of two types

2007-02-11 Thread Paul Rubin
"Alan Isaac" <[EMAIL PROTECTED]> writes:
> I need access to 2*n random choices for two types
> subject to a constraint that in the end I have
> drawn n of each.  I first tried::

You mean you basically want to generate 2*n bools of which exactly
half are True and half are False?  Hmm (untested):

from random import random
def random_types(n):
total = 2*n
trues_needed = n
for i in xrange(total):
   if random() < float(trues_needed) / float(total):
  trues_needed -= 1
  yield True
   else:
  yield False
   total -= 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't find a way to display and print pdf through python.

2007-02-11 Thread krishnakant Mane
well yes,
I need to view reports on line and also print them from within my app.
so yes I need to display the pdf in my app and print it as well.
regards.
Krishnakant
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions

2007-02-11 Thread [EMAIL PROTECTED]

> That's a little harsh -- regexes have their place, together with pointer
> arithmetic, bit manipulations, reverse polish notation and goto. The
> problem is when people use them inappropriately e.g. using a regex when a
> simple string.find will do.
>
> > A quote attributed variously to
> > Tim Peters and Jamie Zawinski says "Some people, when confronted with a
> > problem, think 'I know, I'll use regular expressions.' Now they have two
> > problems."
>
> I believe that is correctly attributed to Jamie Zawinski.
>
> --
> Steven

So as a newbie, I have to ask. I've played with the re module now for
a while, I think regular expressions are super fun and useful. As far
as them being a problem I found they can be tricky and sometimes the
regex's I've devised do unexpected things...(which I can think of two
instances where that unexpected thing was something that I had hoped
to get into further down the line, yay for me!). So I guess I don't
really understand why they are a "bad idea" to use. I don't know of
any other way yet to parse specific data out of a text, html, or xml
file without resorting to regular expressions.
What other ways are there?

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


Re: pygame and python 2.5

2007-02-11 Thread [EMAIL PROTECTED]
On Feb 11, 5:33?am, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Sun, 11 Feb 2007 01:08:21 -0800, [EMAIL PROTECTED] wrote:
> >> An update is in the works for those
> >> using more recent releases,
>
> > That's good news, although the responsible thing
> > to do was not relaease version 2.5 until such issues
> > are resolved.
>
> I realize you're a Windows user, and a Windows user with an AOL email
> address at that,

Now I know what it felt like to be a Shiite
living in Iraq.

> so it may come as a shock to learn that the computer
> industry doesn't start and finish on Windows. I don't see why the needs of
> Windows users like yourself should come ahead of the needs of users on Mac
> OS, Linux, Solaris, etc.
>
> >> but that won't help users who don't have
> >> access to Visual Studio.
>
> > That can be solved by throwing money at the problem.
> > But money doesn't help when the solution is on the
> > far side of the moon.
>
> You're mixing metaphors and I don't understand what you mean.
>
>
>
>
>
> >> >> Yes, it's
> >> >> occasionally very frustrating to the rest of us, but that's life.
>
> >> > As the Kurds are well aware.
>
> >> I really don't think you help your argument by trying to draw parallels
> >> between the problems of compiler non-availability and those of a
> >> population subject to random genocide.
>
> > You missed the point of the analogy.
>
> > The US government suggested to the oppressed tribes
> > in Iraq that they should rise up and overthrow
> > Saddam Hussein at the end of the first Gulf War.
> > And what did the US government do when they rose up?
> > Nothing. They were left to twist in the wind.
>
> Both the southern Iraqis (mostly so-called "marsh Arabs" and Shiites) and
> the northern Kurds rose up against Saddam Hussein. After the Kurdish
> rebellion failed, the US and UK belatedly provided them with aid, lots of
> aid, and kept the northern no-fly zone going until it was no longer
> relevant (2003, the second invasion of Iraq).
>
> It was the southern Iraqis who were left to be slaughtered. Although
> technically there was a no-fly zone in the south, it wasn't enforced
> when it really counted -- while the rebellion was in full force, the
> Iraqi government asked the US for permission to fly into the south.
> Permission was given, and the Iraq air force used combat aircraft against
> the rebels. Unlike the Kurds, they got no aid, neither money nor military
> support.
>
> The end result was that the southern Iraqs were hung out to dry, while the
> Kurds ended up a virtually independent state-within-a-state, with their
> own "government", their own army, and US and British aircraft protecting
> them.
>
> >> Try to keep things in perspective, please.
>
> > See if you can see the similarity.
>
> > I buy into Python. I spend a lot of effort
> > developing a math library based on GMPY to use
> > in my research. I discover a bug in GMPY and
> > actually go to a lot of effort and solve it.
>
> Good on you, and I'm not being sarcastic. But do try to keep a bit of
> perspective. Whatever your problem, you're not being bombed or shot.
> Frankly, the fact that you not only came up with the analogy, but continue
> to defend it, suggests an over-active sense of your own entitlement.
>
> > But _I_ can't even use it because I've been
> > left to twist in the wind by the fact that
> > Python 2.5 for Windows was built with an
> > obsolete compiler that's not even available.
> > Luckily, unlike the Kurds, my situation had
> > a happy ending, someone else compiled the fixed
> > GMPY source and made a 2.5 Windows version
> > available. But can anyone say what will happen
> > the next time?
>
> Get yourself a compiler, then you won't be relying on the kindness of
> strangers.
>
> If that's not practical, for whatever reason, then remember: you're
> relying on the kindness of strangers. They don't owe you a thing. If
> anything, you owe them.
>
> [snip]
>
> >> Your efforts would probably be far better spent trying to build a
> >> back-end for mingw or some similar system into Python's development
> >> system, to allow Python for Windows to be built on a regular rather than
> >> a one-off basis using a completely open source tool chain.
>
> > No, as I said elsewhere, I'm not a software developer,
> > I'm an amateur math researcher. My efforts are best spent
> > as an actual end user
>
> If you won't scratch your own itch, don't be surprised if nobody else
> cares enough to scratch it for you.
>
> > to find and report bugs that the
> > developers never see. Remember, a programmer, because he
> > wrote it, only _thinks_ he knows how the program works.
> > Whereas I, the user, _know_ how it works.
>
> Oh wow. That's the most audacious, self-involved and sheer arrogant claim
> I've ever heard, and I've heard a lot of nonsense sprouted by arrogant
> know-nothings with delusions of grandeur. For the sake of your
> credibility, I hope you can support that claim.
>
> [snip]
>
> >> It's much harder than snip

Re: pygame and python 2.5

2007-02-11 Thread [EMAIL PROTECTED]
On Feb 11, 4:24 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 11, 1:35?am, Steve Holden <[EMAIL PROTECTED]> wrote:
> [...]
>  After all, they have already given freely and generously, and if they 
>  choose
>  not to give more on top of that, it's really up to them.
> >>> Right. Get people to commit and then abandon them. Nice.
> >> Anyone who committed to Python did so without being battered by a
> >> multi-million dollar advertising campaign.
>
> > Multi-million dollar ad campaigns mean nothing to me.
> > I committed to Python because it's a great language.
> > I've dabbled in perl, Visual BASIC, UBASIC, REXX, Java,
> > Scheme, C and C++ but Python is the one I use.
>
> Yes, but your decision must surely have been an informed one, and there
> must surely be reasons why Python remains your choice.
>
>
>
>
>
> >> The Python Software
> >> Foundation has only recently dipped its toes in the advocacy waters,
> >> with results that are still under evaluation. And the use of the
> >> Microsoft "free" VC6 SDK was never a part of the "official" means of
> >> producing Python or its extensions, it was a community-developed
> >> solution to the lack of availability of a free VS-compatible compilation
> >> system for extension modules.
>
> >> I agree that there are frustrations involved with maintaining extension
> >> modules on the Windows platform without having a copy of Visual Studio
> >> (of the correct version) available. One of the reasons Python still uses
> >> an outdated version of VS is to avoid forcing people to upgrade. Any
> >> such decision will have fallout.
>
> > Such as anyone who tries to get in the game late.
>
> I'm afraid it does seem to work out like that, yes.
>
> >> An update is in the works for those
> >> using more recent releases,
>
> > That's good news, although the responsible thing
> > to do was not relaease version 2.5 until such issues
> > are resolved.
>
> Well that would be an issue for the release team. I'm not sure what
> Anthony Baxter (the release manager) would have to say in response to
> this point.

Possibly something like:

"I realize you're a Windows user, and a Windows user with
an AOL email address at that, so it may come as a shock
to learn that the computer industry doesn't start and
finish on Windows. I don't see why the needs of Windows
users like yourself should come ahead of the needs of
users on Mac OS, Linux, Solaris, etc." - Steven D'Arpano

I would hope that it would instead be that the needs of
all users are equal.

>
> >> but that won't help users who don't have
> >> access to Visual Studio.
>
> > That can be solved by throwing money at the problem.
> > But money doesn't help when the solution is on the
> > far side of the moon.
>
> I see your problem, but I don't know what I can do to help you.

Well, that was the point of this, to get people to
see the problem.

> There
> were also, as I remember it, issues with the updated version of Visual
> Studio being non-conformant with standards in some significant way, but
> I never took part in the discussions on those issues.
>
>  Yes, it's
>  occasionally very frustrating to the rest of us, but that's life.
> >>> As the Kurds are well aware.
> >> I really don't think you help your argument by trying to draw parallels
> >> between the problems of compiler non-availability and those of a
> >> population subject to random genocide.
>
> > You missed the point of the analogy.
>
> Perhaps because it wasn't a very good one?
>
>
>
>
>
> > The US government suggested to the oppressed tribes
> > in Iraq that they should rise up and overthrow
> > Saddam Hussein at the end of the first Gulf War.
> > And what did the US government do when they rose up?
> > Nothing. They were left to twist in the wind.
>
> >> Try to keep things in perspective, please.
>
> > See if you can see the similarity.
>
> > I buy into Python. I spend a lot of effort
> > developing a math library based on GMPY to use
> > in my research. I discover a bug in GMPY and
> > actually go to a lot of effort and solve it.
> > But _I_ can't even use it because I've been
> > left to twist in the wind by the fact that
> > Python 2.5 for Windows was built with an
> > obsolete compiler that's not even available.
>
> > Luckily, unlike the Kurds, my situation had
> > a happy ending, someone else compiled the fixed
> > GMPY source and made a 2.5 Windows version
> > available. But can anyone say what will happen
> > the next time?
>
> Presumably not. I presume you have been reporting your bugs through the
> Sourceforge project to keep the developers in touch with the issues you
> have found?

Last time I tried, it didn't work and e-mail to the
maintainer didn't get any response.

> Normally a package's maintainers will produce updated
> installers,

Unless they have stopped doing Windows developement as
part of their job as is the case with GMPY. Luckily,
there's someone out there who does create Windows
binaries.


randomly generate n of each of two types

2007-02-11 Thread Alan Isaac
I need access to 2*n random choices for two types
subject to a constraint that in the end I have
drawn n of each.  I first tried::

def random_types(n,typelist=[True,False]):
types = typelist*n
random.shuffle(types)
for next_type in types:
yield next_type

This works but has some obvious costs.
To avoid those I considered this instead::

def random_types(n,typelist=[True,False]):
type0, type1 = typelist
ct0, ct1 = 0,0
while ct0+ct1<2*n:
if random.random() < ((n-ct0)/(2*n-ct0-ct1)):
next_type = type0
ct0 += 1
else:
next_type = type1
ct1 += 1
yield next_type

Does this seem a good way to go?  Comments welcome.

Thank you,
Alan Isaac


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


Re: can't find a way to display and print pdf through python.

2007-02-11 Thread Christian Stapfer
krishnakant Mane wrote in message 
news:[EMAIL PROTECTED]
> On 11/02/07, Vishal Bhargava <[EMAIL PROTECTED]> wrote:
>> Use Report Lab...
> I mentioned in my first email that I am already using reportlab.
> but I can only generate pdf out of that.
> I want to display it on screen and I also will be giving a print
> button which should do the printing job.
> by the way I use wxpython for gui.

Under Windows you could do it by embedding Adobe's
ActiveX control in your application. Don't know
about Linux, though. Perhaps you could just convert
your PDF to a raster image for display (eg. by
using ImageMagick's convert) under Linux?

Regards,
Christian

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


Re: How to find all the same words in a text?

2007-02-11 Thread attn . steven . kuo
On Feb 11, 5:13 am, Samuel Karl Peterson
<[EMAIL PROTECTED]> wrote:
> "Johny" <[EMAIL PROTECTED]> on 10 Feb 2007 05:29:23 -0800 didst step
> forth and proclaim thus:
>
> > I need to find all the same words in a text .
> > What would be the best idea  to do that?
>
> I make no claims of this being the best approach:
>
> 
> def findOccurances(a_string, word):
> """
> Given a string and a word, returns a double:
> [0] = count [1] = list of indexes where word occurs
> """
> import re
> count = 0
> indexes = []
> start = 0 # offset for successive passes
> pattern = re.compile(r'\b%s\b' % word, re.I)
>
> while True:
> match = pattern.search(a_string)
> if not match: break
> count += 1;
> indexes.append(match.start() + start)
> start += match.end()
> a_string = a_string[match.end():]
>
> return (count, indexes)
> 
>
> Seems to work for me.  No guarantees.
>



More concisely:

import re

pattern = re.compile(r'\b324\b')
indices = [ match.start() for match in
pattern.finditer(target_string) ]
print "Indices", indices
print "Count: ", len(indices)

--
Cheers,
Steven

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


Re: How to access an absolute address through Python?

2007-02-11 Thread Grant Edwards
On 2007-02-11, volcano <[EMAIL PROTECTED]> wrote:

> Can it be done,

Yes.

> and if yes - how?

/proc/kmem

-- 
Grant Edwards   grante Yow!  Nipples, dimples,
  at   knuckles, NICKLES,
   visi.comwrinkles, pimples!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with reimporting modules

2007-02-11 Thread Dustan
On Feb 11, 5:53 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> I'm currently investigating a problem that can hit you in TurboGears
> when Kid template modules are reloaded in the background, because in
> certain situations, global variables suddenly are set to None values.
>
> I tracked it down to the following behavior of Python. Assume you have a
> module hello.py like that:
>
>  hello. py 
> greeting = 'Hello!'
> def print_hello():
>  print greeting
> ---
>
> Now run the following code:
>
> from hello import print_hello
> print_hello()
> import sys
> del sys.modules['hello'] # delete module
> import hello # recreate module
> print_hello()
>
> The second print_hello() prints "None" instead of "Hello!". Why is that?
> I had expected that it either prints an error or print "Hello!" as well.
>
> Is this intended behavior of Python?
>
> -- Christoph

You're most likely looking for reload:
http://docs.python.org/lib/built-in-funcs.html#l2h-61
The documentation does imply that deleting a module from sys.modules
may not be what you want:
http://docs.python.org/lib/module-sys.html#l2h-5147

>>> import sys
>>> import warnings as previous_warnings # for example
>>> # testing whether reload returns the same module object:
... reload(previous_warnings) is previous_warnings
True
>>> # the following result is rather intuitive, but for
... # the sake of demonstration, I'll do it anyway.
... del sys.modules['warnings']
>>> import warnings as after_warnings
>>> after_warnings is previous_warnings
False

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


Re: How to access an absolute address through Python?

2007-02-11 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> > My goal is to sync program with external equipment through a register
> > defined as an absolute physical address. I know how to do it from C -
> > was curious if it may be done from Python. Can it be done?
> >
> No. You'd have to use a compiled extension.

Well, you don't necessarily have to deal with the C API or ctypes; it
may be enough to invoke an external program that accesses the
necessary memory address.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gvim: doc string editing

2007-02-11 Thread [EMAIL PROTECTED]
On Feb 11, 7:01 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-02-11, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > Hi, I am using gvim, and am looking for a way to tell gvim to
> > automatically wrap long lines into multiple lines ( by
> > automatically inserting the newline character) when I edit doc
> > strings. I am sure somebody must have done this.
>
> If tw (textwidth) is set to some apposite number, then it should
> just work (unfortunately, this will also cause your code to wrap
> unless you set up the comment strings properly for Python).
> Alternatively, you can use the gq formatting command to wrap the
> comment after it is composed.
>
> Do :h format_comments for the full dope.
>
> --
> Neil Cerutti

gq works great. Thanks.
-
Suresh

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


Re: HTML Parsing

2007-02-11 Thread Fredrik Lundh
John Machin wrote:

> One can even use ElementTree, if the HTML is well-formed. See below.
> However if it is as ill-formed as the sample (4th "td" element not
> closed; I've omitted it below), then the OP would be better off
> sticking with Beautiful Soup :-)

or get the best of both worlds:

http://effbot.org/zone/element-soup.htm

 



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


Re: How to access an absolute address through Python?

2007-02-11 Thread volcano
On Feb 11, 3:46 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> volcano wrote:
> > On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> [...]
> >> What's your goal?  What do you expect at the memory address you want to
> >> access?
>
> >> Ciao,
> >> Marc 'BlackJack' Rintsch
>
> > My goal is to sync program with external equipment through a register
> > defined as an absolute physical address. I know how to do it from C -
> > was curious if it may be done from Python. Can it be done?
>
> No. You'd have to use a compiled extension.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenwebhttp://del.icio.us/steve.holden
> Blog of Note:  http://holdenweb.blogspot.com
> See you at PyCon?http://us.pycon.org/TX2007


Steve, Fred, thank you. This is exactly what I have done, though I did
hope for shortcut. Life is tough:)!

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


Re: gvim: doc string editing

2007-02-11 Thread Neil Cerutti
On 2007-02-11, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi, I am using gvim, and am looking for a way to tell gvim to
> automatically wrap long lines into multiple lines ( by
> automatically inserting the newline character) when I edit doc
> strings. I am sure somebody must have done this.

If tw (textwidth) is set to some apposite number, then it should
just work (unfortunately, this will also cause your code to wrap
unless you set up the comment strings properly for Python).
Alternatively, you can use the gq formatting command to wrap the
comment after it is composed.

Do :h format_comments for the full dope.

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


gvim: doc string editing

2007-02-11 Thread [EMAIL PROTECTED]
Hi, I am using gvim, and am looking for a way to tell gvim to
automatically wrap long lines into multiple lines ( by automatically
inserting the newline character) when I edit doc strings. I am sure
somebody must have done this.

-
Suresh

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


urllib2 request htaccess page through proxy

2007-02-11 Thread Alessandro Fachin
I write this simply code that should give me the access to private page with
htaccess using a proxy, i don't known because it's wrong... 


import urllib,urllib2

#input url
url="http://localhost/private/file";

#proxy set up
proxy_handler = urllib2.ProxyHandler({'http': 'http://myproxy:'})

#htaccess set up
user="matteo"
password="matteo"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(proxy_handler,authhandler)
urllib2.install_opener(opener)

#open the url
req=urllib2.Request(url)
data=urllib2.urlopen(req).read()
print data

i get no access on access.log from apache2 and nothing from the proxy in
tcpdump log. If i use only the proxy with a page that doesn't use htaccess
it works... if anyone could help,regards...




Traceback (most recent call last):
  File "proxy.py", line 22, in ?
data=urllib2.urlopen(req).read()
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 130, in urlopen
return _opener.open(url, data)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 364, in open
response = meth(req, response)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 471, in http_response
response = self.parent.error(
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 396, in error
result = self._call_chain(*args)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 337, in _call_chain
result = func(*args)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 741, in http_error_401
host, req, headers)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 720, in http_error_auth_reqed
return self.retry_http_basic_auth(host, req, realm)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 730, in retry_http_basic_auth
return self.parent.open(req)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 364, in open
response = meth(req, response)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 471, in http_response
response = self.parent.error(
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 402, in error
return self._call_chain(*args)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 337, in _call_chain
result = func(*args)
 
File 
"/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py",
line 480, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Authorization Required




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


Re: How to find all the same words in a text?

2007-02-11 Thread Maël Benjamin Mettler
In order to find all the words in a text, you need to tokenize it first.
The rest is a matter of calling the count method on the list of
tokenized words. For tokenization look here:
http://nltk.sourceforge.net/lite/doc/en/words.html
A little bit of warning: depending on what exactly you need to do, the
seemingly trivial taks of tokenizing a text can become quite complex.

Enjoy,

Maël

Neil Cerutti schrieb:
> On 2007-02-10, Johny <[EMAIL PROTECTED]> wrote:
>> I need to find all the same words in a text .
>> What would be the best idea  to do that?
>> I used string.find but it does not work properly for the words.
>> Let suppose I want to find a number 324 in the  text
>>
>> '45  324 45324'
>>
>> there is only one occurrence  of 324 word but string.find()   finds 2
>> occurrences  ( in 45324 too)
>>
>> Must I use regex?
>> Thanks for help
> 
> The first thing to do is to answer the question: What is a word?
> 
> The second thing to do is to design some code that can find
> words in strings.
> 
> The last thing to do is to search those actual words for the word
> you're looking for.
> 

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


Re: How to access an absolute address through Python?

2007-02-11 Thread Steve Holden
volcano wrote:
> On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
[...]
>> What's your goal?  What do you expect at the memory address you want to
>> access?
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> My goal is to sync program with external equipment through a register
> defined as an absolute physical address. I know how to do it from C -
> was curious if it may be done from Python. Can it be done?
> 
No. You'd have to use a compiled extension.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: How to access an absolute address through Python?

2007-02-11 Thread Fred of UrlBit.Us
volcano wrote:

> On Feb 11, 2:46 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
...
> My goal is to sync program with external equipment through a register
> defined as an absolute physical address. I know how to do it from C -
> was curious if it may be done from Python. Can it be done?
> 
> Thanks, Mark

Your best bet will be to create a C library callable from Python to do it
for you. There may be such a beast in existence already, but it should not
be hard at all to do, given the simplicity of the requirements.

-- 
-- Fred of UrlBit.Us
-- http://UrlBit.Us - Bite those URLs down to size!


 Posted Via Usenet.com Premium Usenet Newsgroup Services
--
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
--
http://www.usenet.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find all the same words in a text?

2007-02-11 Thread Neil Cerutti
On 2007-02-10, Johny <[EMAIL PROTECTED]> wrote:
> I need to find all the same words in a text .
> What would be the best idea  to do that?
> I used string.find but it does not work properly for the words.
> Let suppose I want to find a number 324 in the  text
>
> '45  324 45324'
>
> there is only one occurrence  of 324 word but string.find()   finds 2
> occurrences  ( in 45324 too)
>
> Must I use regex?
> Thanks for help

The first thing to do is to answer the question: What is a word?

The second thing to do is to design some code that can find
words in strings.

The last thing to do is to search those actual words for the word
you're looking for.

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


morpholgy toolbox

2007-02-11 Thread azrael
does any one have any expirience with mmorph module. At first i was
unable to run it because some file was missing (instalation problem),
but i managed it. but, did anyone manage to save the new mask, or
anything created with it.

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


Re: Shed Skin Optimizing Python-to-C++ Compiler 0.0.19

2007-02-11 Thread Michael
Mark Dufour wrote:

> This
> latest release adds basic support for iterators and generators

Oooh, I may try our miniaxon tutorial against shed skin in that case. 
(ie http://kamaelia.sourceforge.net/MiniAxon/)

Great to see you're plowing through this BTW !


Michael.
--
Kamaelia Project Lead
http://kamaelia.sourceforge.net/Home
http://yeoldeclue.com/blog

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


  1   2   >