sending executable data over network..

2008-06-24 Thread Piyush Anonymous
hi,
i wish to change the way the function definition at run time in a running
server. new function code which is to be executed is provided by a client at
different location.
i am getting it by reading a file and sending it using makefile() with
server/client connected using sockets.

how can make the lines received in a string array as new function
definition? or should i receive it in a different way?

is there any better way to do the entire thing?
--
http://mail.python.org/mailman/listinfo/python-list

Sending information to a website

2008-06-24 Thread Alex Bryan
Okay, so what I want to do is connect to dictionary.com and send the  
website a word, and later receive the definition. But for now, I want  
to focus on sending the word. A good guy from this mailing list said I  
should look into the code and then figure out what the word you want  
to be defined is called by the website. In other words, what is the  
name of the word the user inputs. Okay, so using the firebug extension  
I got the code that the search field on the website uses. here is that  
code.



	name="search_form">
		value="" name="q"/>


Anyway, not to get to complicated. How would any of you suggest I send  
this word to the site. While bearing in mind that I will need to  
return it if it matters for this step.


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


Re: Is there any way to find out sizeof an object

2008-06-24 Thread Paddy
On Jun 24, 6:00 am, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:
> Hi,
> I have written a class which has some attributes. I want to know how do i 
> find out the size of an instance of this class??
> class T(object):
>     def __init__(self, fn_name, *args, **kwds):
>         self.fn_name = fn_name
>         self.args = args
>         self.kwds = kwds
> Thanks,
> Srini
>
>       Bollywood, fun, friendship, sports and more. You name it, we have it 
> onhttp://in.promos.yahoo.com/groups/bestofyahoo/

Check memory
Create a million
Check memory
Do maths!

;-)

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread cokofreedom
On Jun 24, 8:20 am, "Corey G." <[EMAIL PROTECTED]> wrote:
> If Perl 6 ever does get on its feet and get released, how does it
> compare to Python 3000?  Is Perl 6 more like Java now with Parrot?  I
> just want to make sure that Python is staying competitive.
>
> If this is the wrong mailing list, just let me know.  Thanks!

Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k
will (when out of beta) will have a speed similar to what it has
currently in 2.5, possibly with speed ups in some locations. But
competitive-wise I think the point is Python 3k tries to remove warts
from the Python Language to make it even more friendly to readers and
writers alike. In that way it should/will stay competitive.

However towards overall usage, the general advice is to stay with the
2.x series for now, trying to ensure your code style is moving towards
the Py3k style, and then make the jump to the 3.x series when it is
finialised.

Another point, is Perl 6 ever going to get released :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: String question

2008-06-24 Thread cokofreedom
On Jun 24, 5:38 am, "Mark Tolonen" <[EMAIL PROTECTED]> wrote:
> "Andreu" <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]
> > Yes, ... don't ask me why, but in fact  v1,v2,v3 = str1.split()
> > does not seem to work. My original problem was I forgot about
> > the parenthesis as Tim point out. So I ended up converting to a
> > list as in:  v = str1.split() and accessing the elements using
> > v[0] v[1] ect...it is working now. Thanks.
>
> > Andreu.
>
> v1,v2,v3 = str1.split() will only work if there are exactly three things in
> str1.
>
> >>> s = 'this is a test'
> >>> v1,v2,v3 = s.split()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: too many values to unpack>>> v1,v2,v3 = s.split(' ',2)# limit 
> to two splits maximum
> >>> v1
> 'this'
> >>> v2
> 'is'
> >>> v3
>
> 'a test'
>
> -Mark

In Python 3k I believe you can put a * next to one of the variables to
hold multiple arguments. That'll be aidful!
--
http://mail.python.org/mailman/listinfo/python-list


binary representation of an integer

2008-06-24 Thread eliben
Hello,

I'm interested in converting integers to a binary representation,
string. I.e. a desired function would produce:

dec2bin(13) => "1101"

The other way is easily done in Python with the int() function.

Perl has a very efficient way to do dec2bin, because its pack/unpack
have a B format for binary representations, so it's done with:

sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
return $str;
}

Python's pack/unpack don't have the binary format for some reason, so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286
However, it is very general and thus inefficient.

What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.

What do you think?
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread Maric Michaud
Le Tuesday 24 June 2008 10:03:58 eliben, vous avez écrit :
> Hello,
>
> I'm interested in converting integers to a binary representation,
> string. I.e. a desired function would produce:
>
> dec2bin(13) => "1101"
>
> The other way is easily done in Python with the int() function.
>
> Perl has a very efficient way to do dec2bin, because its pack/unpack
> have a B format for binary representations, so it's done with:
>
> sub dec2bin {
> my $str = unpack("B32", pack("N", shift));
> $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
> return $str;
> }
>
> Python's pack/unpack don't have the binary format for some reason,

Yes, but I think the %b format specifier has been added to p3k but will not in 
python 2.x.

> so 
> custom solutions have to be developed. One suggested in the ASPN
> cookbook is:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286
> However, it is very general and thus inefficient.
>
> What would be the quickest way to do this ? I think that for dec2bin
> conversion, using hex() and then looping with a hex->bin lookup table
> would be probably much faster than the general baseconvert from the
> recipe.
>
> What do you think?


Something like that, less typing with octal conversion :)

>>>[8]: oct2bin = 
{'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', 
'7':'111'}

>>>[9]: ''.join(oct2bin[e] for e in "%o"%35).lstrip('0')
...[9]: '100011'



-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21
--
http://mail.python.org/mailman/listinfo/python-list


Re: MD5 hash for url and utf unicode converting to ascii

2008-06-24 Thread Nick Craig-Wood
joe shoemaker <[EMAIL PROTECTED]> wrote:
>  I would like to convert url into md5 hash. My question is that md5
>  hash will create collision at 2^64. If you do long(value,16), where
>  value is the md5 hash string, would value returned from long(value,
>  16) be unique as long as md5 hashed string is unique? when you move
>  md5 hashed string to long, where will the collision occur, at anything
> >= 2^64?
> 
>hash = md5.new()
>hash.update("some_url_")
>value = hash.digest()
>value_in_int = long(value, 16) #would this be unique as long as
>  hashed string is unique(i.e < 2^64)
>hash = md5.new() hash.update("some_url_") value = hash.digest()
>  value_in_int = long(value, 16) #would this be unique as long as hashed
>  string is unique(i.e < 2^64)

MD5 Sums don't guarantee uniqueness for any length of string.

If your hash had as many or more bits in as the input string then
there are hashes which are guaranteed unique, but MD5 isn't one of
them.  You could (lets say) AES encrypt the string instead.

>  Do I need to also convert the value to base64.encodestring(value)?
>  What is the purpose of base64.encodestring?

To turn the buffer into printable characters.  You can do it like this also...

>>> import md5
>>> hash = md5.new()
>>> hash.update("some_url_")
>>> value = hash.digest()
>>> value
'\xc9\x11}\x8f?64\x83\xf3\xcaPz\x1d!\xddd'
>>> value.encode("hex")
'c9117d8f3f363483f3ca507a1d21dd64'
>>> long(value.encode("hex"), 16)
267265642849753964132104960801656397156L
>>>

>  For unicode encoding, I can do, md5.update(value.encode('utf-8')) to
>  give me ascii values.

Yes that would be fine

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread Corey G.
What I meant, in terms of dealing with accurate or non-accurate rumors  
is with speed, yes.  There are plenty of comparisons where Perl is  
4-15x faster then Python for 'some' operations regarding regular  
expressions, etc.


For me personally, this means absolutely nothing because if I spend  
50x more time comprehending spaghetti, obfuscated Perl code it's  
irrelevant.  The main concern (my concern) is whether or not Perl 6 is  
more like Java with pre-compiled byte code (did I say that right) and  
whether or not individuals without the ability to see past the surface  
will begin to migrate towards Perl 6 for its seemingly faster  
capabilities.


With Perl 6 taking 10+ years, if/when it actually gets released, will  
it be technically ahead of Python 3000?  Is Parrot worth the extra  
wait the Perl 6 project is enduring?  My own answer would be a  
resounding no, but I am curious as to what others think. :)


-Thanks!





On Jun 24, 2008, at 2:52 AM, [EMAIL PROTECTED] wrote:


On Jun 24, 8:20 am, "Corey G." <[EMAIL PROTECTED]> wrote:

If Perl 6 ever does get on its feet and get released, how does it
compare to Python 3000?  Is Perl 6 more like Java now with Parrot?  I
just want to make sure that Python is staying competitive.

If this is the wrong mailing list, just let me know.  Thanks!


Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k
will (when out of beta) will have a speed similar to what it has
currently in 2.5, possibly with speed ups in some locations. But
competitive-wise I think the point is Python 3k tries to remove warts
from the Python Language to make it even more friendly to readers and
writers alike. In that way it should/will stay competitive.

However towards overall usage, the general advice is to stay with the
2.x series for now, trying to ensure your code style is moving towards
the Py3k style, and then make the jump to the 3.x series when it is
finialised.

Another point, is Perl 6 ever going to get released :P
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: binary representation of an integer

2008-06-24 Thread Mark Dickinson
On Jun 24, 9:03 am, eliben <[EMAIL PROTECTED]> wrote:
> What would be the quickest way to do this ? I think that for dec2bin
> conversion, using hex() and then looping with a hex->bin lookup table
> would be probably much faster than the general baseconvert from the
> recipe.

I suspect you're right, but it would be easy to find out:  just
code up the hex->bin method and use the timeit module to do some
timings.  Don't forget to strip the trailing 'L' from hex(n) if n
is a long.

If you're prepared to wait for Python 2.6, or work with the beta
version, then the conversion is already there:

Macintosh-3:trunk dickinsm$ ./python.exe
Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bin(13)
'0b1101'

Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:

>>> bin(13L)
'0b1101'

I wonder whether this is a bug...

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


Re: poplib - retr() getting stuck

2008-06-24 Thread Gabriel Genellina
En Fri, 20 Jun 2008 04:37:32 -0300, Roopesh <[EMAIL PROTECTED]>  
escribió:



I am using poplib's retr() to fetch mails from my gmail account. It
works fine, in some cases it gets stuck inside the retr() method and
does not come out.


Probably the server stopped responding. By default, sockets have no  
timeout value set - that is, a recv() call may block forever.
Try using socket.setdefaulttimeout  
 before creating the  
connection, or search this group for past responses to this same problem.


--
Gabriel Genellina

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


String split with " and/or ' and/or \

2008-06-24 Thread Kurt Mueller

How to (super)split a string (literal) containing " and/or ' and/or \.

example:

' a  "  b b   "  c\ c '.supersplit(' ')
->
['a', '  b b   ', 'c c']


Thanks and Grüessli
--
Kurt Müller:
[EMAIL PROTECTED]

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread cokofreedom
On Jun 24, 10:36 am, "Corey G." <[EMAIL PROTECTED]> wrote:
> What I meant, in terms of dealing with accurate or non-accurate rumors
> is with speed, yes.  There are plenty of comparisons where Perl is
> 4-15x faster then Python for 'some' operations regarding regular
> expressions, etc.
>
> For me personally, this means absolutely nothing because if I spend
> 50x more time comprehending spaghetti, obfuscated Perl code it's
> irrelevant.  The main concern (my concern) is whether or not Perl 6 is
> more like Java with pre-compiled byte code (did I say that right) and
> whether or not individuals without the ability to see past the surface
> will begin to migrate towards Perl 6 for its seemingly faster
> capabilities.
>
> With Perl 6 taking 10+ years, if/when it actually gets released, will
> it be technically ahead of Python 3000?  Is Parrot worth the extra
> wait the Perl 6 project is enduring?  My own answer would be a
> resounding no, but I am curious as to what others think. :)
>
> -Thanks!
>

>From a quick read of the Parrot Wiki page it would appear they hope to
one day allow the compilation of BOTH Perl 6 and Python, which could
be interesting.

Towards the speed, 
http://shootout.alioth.debian.org/debian/benchmark.php?test=all&lang=all
puts Python ahead of perl, and Python Psyco ahead of Parrot PIR.
Though I haven't looked at each benchmark comparison so it is hard to
tell.

Towards what Perl 6 offers, the Wiki on it seems to indicate it will
be a clean up of Perl 5 as well as adding of many features from other
languages. It seems like Lary has gone for the TAKE IT ALL approach
which could work out well in providing practically any format for
creating Perl scripts. Or it could cause huge confusion as users ask
for help and received a 1001 different approaches...

Towards it being more advanced than Python 3k, time will tell. Both
are still active and getting updated. So while I personally will stay
with Python, others may move, or use both.
--
http://mail.python.org/mailman/listinfo/python-list


Re: string.Template.delimiter cannot be overriden?

2008-06-24 Thread Gabriel Genellina
En Tue, 17 Jun 2008 02:20:23 -0300, Raymond Hettinger <[EMAIL PROTECTED]>  
escribió:

On Jun 16, 9:53 pm, kretik <[EMAIL PROTECTED]> wrote:



I've been trying to coax this class to use something other than the
default '$' but it seems setting it to something else has no discernible
effect. Is it necessary to inherit from the class to do this?


Yes, subclassing is the intended way to produce variants of Template
with a different delimiter.


Just out of curiosity, why was it done that way?
I'd say the "obvious" way to change the default delimiter would be to set  
an instance attribute - so I guess this was a deliberate decision, but I  
can't figure out why it is better this way...


--
Gabriel Genellina

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


Re: String split with " and/or ' and/or \

2008-06-24 Thread Paul McGuire
On Jun 24, 3:56 am, Kurt Mueller <[EMAIL PROTECTED]> wrote:
> How to (super)split a string (literal) containing " and/or ' and/or \.
>
> example:
>
> ' a  "  b b   "  c\ c '.supersplit(' ')
> ->
> ['a', '  b b   ', 'c c']
>
> Thanks and Grüessli
> --
> Kurt Müller:
> [EMAIL PROTECTED]

>>> re.split(r'''['"\\]''',' a  "  b b   "  c\ c ')
[' a  ', '  b b   ', '  c', ' c ']
--
http://mail.python.org/mailman/listinfo/python-list


Re: String split with " and/or ' and/or \

2008-06-24 Thread Paul McGuire
On Jun 24, 3:56 am, Kurt Mueller <[EMAIL PROTECTED]> wrote:
> How to (super)split a string (literal) containing " and/or ' and/or \.
>
> example:
>
> ' a  "  b b   "  c\ c '.supersplit(' ')
> ->
> ['a', '  b b   ', 'c c']
>
> Thanks and Grüessli
> --
> Kurt Müller:
> [EMAIL PROTECTED]

Or did you mean this?

>>> re.split(r'''['"]|\\ ''',' a  "  b b   "  c\ c ')
[' a  ', '  b b   ', '  c', 'c ']

(In your example, you should prefix you quoted string literal with an
r, as in:

r' a  "  b b   "  c\ c '.supersplit(' ')

That way, the '\' character will be treated as just any other
character.

-- Paul

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread Michele Simionato
On Jun 24, 11:16 am, [EMAIL PROTECTED] wrote:
> Towards it being more advanced than Python 3k, time will tell.

It is worth reminding that, in more than one sense, the most advanced
language is the one with less features ...

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


Re: very large graph

2008-06-24 Thread MRAB
On Jun 24, 1:26 am, [EMAIL PROTECTED] wrote:
> I need to represent the hyperlinks between a large number of HTML
> files as a graph.  My non-directed graph will have about 63,000 nodes
> and and probably close to 500,000 edges.
>
> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/
> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for
> generating a file to store the graph, and I have also looked into
> Graphviz for visualization.  I'm just not sure which modules are
> best.  I need to be able to do the following:
>
> 1)  The names of my nodes are not known ahead of time, so I will
> extract the title from all the HTML files to name the nodes prior to
> parsing the files for hyperlinks (edges).
>
> 2) Every file will be parsed for links and nondirectional connections
> will be drawn between the two nodes.
>
> 3)  The files might link to each other so the graph package needs to
> be able to check to see if an edge between two nodes already exists,
> or at least not double draw connections between the two nodes when
> adding edges.
>
> I'm relatively new to graph theory so I would greatly appreciate any
> suggestions for filetypes.  I imagine doing this as a python
> dictionary with a list for the edges and a node:list paring is out of
> the question for such a large graph?

Perhaps a dictionary where the key is a node and the value is a set of
destination nodes?
--
http://mail.python.org/mailman/listinfo/python-list


Re: String split with " and/or ' and/or \

2008-06-24 Thread Peter Otten
Kurt Mueller wrote:

> How to (super)split a string (literal) containing " and/or ' and/or
> \.
> 
> example:
> 
> ' a  "  b b   "  c\ c '.supersplit(' ')
> ->
> ['a', '  b b   ', 'c c']
> 
> 
> Thanks and Grüessli

>>> import shlex
>>> shlex.split(' a  "  b b   "  c\ c ')
['a', '  b b   ', 'c c']

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

calling a .exe from Python

2008-06-24 Thread yoevidentemente
Hi, i am trying to call a .exe from my .py file, i have found the exec
function, but i'm not sure of how to use it:S

would it be f.e.:

execl (mypath/myfile.exe,myfile,arg1,arg2,...)



Another question is, when i call my .exe with exec, i understand that
my .py file will stop running, and instead the new process will be
launched instead of it. Is it true?
Is there a way to launch my .exe without finishing my .py file??

thank you very much:)

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


calling a .exe from Python

2008-06-24 Thread evidentemente.yo
Hi, i am trying to call a .exe from my .py file, i have found the exec
function, but i'm not sure of how to use it:S

would it be f.e.:

execl (mypath/myfile.exe,myfile,arg1,arg2,...)



Another question is, when i call my .exe with exec, i understand that
my .py file will stop running, and instead the new process will be
launched instead of it. Is it true?
Is there a way to launch my .exe without finishing my .py file??

thank you very much:)
--
http://mail.python.org/mailman/listinfo/python-list


How to import filenames with special characters?

2008-06-24 Thread inhahe
How would I import a python file whose name contains characters like .'s or 
!'s?

Is there really _no_ way to do that?  I have to use plain jane letters and 
numbers for everything?


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


Difference between two dates

2008-06-24 Thread sniipe
Hi!

I am new in Python, so I count for your help. I need to get difference
in months between two dates. How to do it in python? I am substracting
two dates, for example date1 - date2 and I got result in days, how to
change it?

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


Re: Difference between two dates

2008-06-24 Thread Cédric Lucantis
Le Tuesday 24 June 2008 12:11:03 [EMAIL PROTECTED], vous avez écrit :
> Hi!
>
> I am new in Python, so I count for your help. I need to get difference
> in months between two dates. How to do it in python? I am substracting
> two dates, for example date1 - date2 and I got result in days, how to
> change it?
>

Maybe the datetime and calendar modules may help too, but a simple solution is 
to get your dates in number of months (tm1 and tm2 being struct_time objects 
returned by time.localtime/gmtime) :

m1 = tm1.tm_year * 12 + (tm1.tm_mon - 1)
m2 = tm2.tm_year * 12 + (tm2.tm_mon - 1)

then (m1 - m2) gives the difference in months

(see the time modules docs for more infos)

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread Nick Craig-Wood
eliben <[EMAIL PROTECTED]> wrote:
>  I'm interested in converting integers to a binary representation,
>  string. I.e. a desired function would produce:
> 
>  dec2bin(13) => "1101"
> 
>  The other way is easily done in Python with the int() function.
> 
>  Perl has a very efficient way to do dec2bin, because its pack/unpack
>  have a B format for binary representations, so it's done with:
> 
>  sub dec2bin {
>  my $str = unpack("B32", pack("N", shift));
>  $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
>  return $str;
>  }
> 
>  Python's pack/unpack don't have the binary format for some reason, so
>  custom solutions have to be developed. One suggested in the ASPN
>  cookbook is:
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286
>  However, it is very general and thus inefficient.
> 
>  What would be the quickest way to do this ? I think that for dec2bin
>  conversion, using hex() and then looping with a hex->bin lookup table
>  would be probably much faster than the general baseconvert from the
>  recipe.
> 
>  What do you think?

Something like this...

>>> hex_to_binary = {
... "0" : "",
... "1" : "0001",
... "2" : "0010",
... "3" : "0011",
... "4" : "0100",
... "5" : "0101",
... "6" : "0110",
... "7" : "0111",
... "8" : "1000",
... "9" : "1001",
... "a" : "1010",
... "b" : "1011",
... "c" : "1100",
... "d" : "1101",
... "e" : "1110",
... "f" : "",
... }

>>> def to_binary(inp):
... out = []
... for hex_digit in ("%x" % inp):
... out.append(hex_to_binary[hex_digit])
... out = "".join(out).lstrip("0")
... if out == "":
... out = "0"
... return out
...
>>> to_binary(0)
'0'
>>> to_binary(10)
'1010'
>>> to_binary(100)
'1100100'
>>> to_binary(1000)
'101000'
>>> to_binary(1000)
'1000101011000111001000110100100010001000'

But don't try this ;-)

>>> to_binary(-1)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in to_binary
KeyError: '-'

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


Re: sending executable data over network..

2008-06-24 Thread Cédric Lucantis
Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez écrit :
> hi,
> i wish to change the way the function definition at run time in a running
> server. new function code which is to be executed is provided by a client
> at different location.
> i am getting it by reading a file and sending it using makefile() with
> server/client connected using sockets.
>
> how can make the lines received in a string array as new function
> definition? or should i receive it in a different way?
>
> is there any better way to do the entire thing?

One way is to transmit the code as a string and compile it on server-side with 
the 'compile' builtin function. Another is to compile it on client-side and 
transmit the resulting code object with the marshal module but there are many 
restrictions on it (specially the fact that the client and server will have 
to run the same python version) so carefully read the docs first. I'd choose 
the first solution, eventually using the pickle module to avoid encoding 
problems.

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list

Re: very large graph

2008-06-24 Thread A.T.Hofkamp
On 2008-06-24, MRAB <[EMAIL PROTECTED]> wrote:
> On Jun 24, 1:26 am, [EMAIL PROTECTED] wrote:
>> I need to represent the hyperlinks between a large number of HTML
>> files as a graph.  My non-directed graph will have about 63,000 nodes
>> and and probably close to 500,000 edges.
>>
>> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/
>> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for
>> generating a file to store the graph, and I have also looked into
>> Graphviz for visualization.  I'm just not sure which modules are
>> best.  I need to be able to do the following:

Afaik Graphviz is not good at abstracting the graph, which you may need here.
A page with 63,000 circles on it, and 500,000 edges will probably come out of
the printer as a black sheet of paper.
(8"x11" paper, 1 circle is 1/5", then you have only 2200 circles at one sheet.
You need a factor 28 more circles which leads to a circle of about 0.007".)

Even when actual paper format would not be a problem, you will need some
abstraction and/or tools, as you will not find anything manually in an ocean of
63,000 elements.

One area you may want to start looking for tools is in state graphs, where the
set of possible states of an entire system is unfolded. These things go up to
over a million states, so you only have a 'small' problem there...

>> 1)  The names of my nodes are not known ahead of time, so I will
>> extract the title from all the HTML files to name the nodes prior to
>> parsing the files for hyperlinks (edges).
>>
>> 2) Every file will be parsed for links and nondirectional connections
>> will be drawn between the two nodes.
>>
>> 3)  The files might link to each other so the graph package needs to
>> be able to check to see if an edge between two nodes already exists,
>> or at least not double draw connections between the two nodes when
>> adding edges.
>>
>> I'm relatively new to graph theory so I would greatly appreciate any
>> suggestions for filetypes.  I imagine doing this as a python
>> dictionary with a list for the edges and a node:list paring is out of
>> the question for such a large graph?
>
> Perhaps a dictionary where the key is a node and the value is a set of
> destination nodes?

For undirected edges, you could make an Edge class and have a set of Edge's
(where two Edge objects are equal when they connect the same nodes).
I don't expect 500,000 elements in a set to be a problem.

Sincerely,
Albert

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


Re: Difference between two dates

2008-06-24 Thread A.T.Hofkamp
On 2008-06-24, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I am new in Python, so I count for your help. I need to get difference
> in months between two dates. How to do it in python? I am substracting
> two dates, for example date1 - date2 and I got result in days, how to
> change it?

Check the 'datetime' module.

(in general, for any given problem you have a 70% chance that somebody has
written a module for it. Check the standard library, or else PyPI.)

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling a .exe from Python

2008-06-24 Thread MRAB
On Jun 24, 10:50 am, "evidentemente.yo" <[EMAIL PROTECTED]>
wrote:
> Hi, i am trying to call a .exe from my .py file, i have found the exec
> function, but i'm not sure of how to use it:S
>
> would it be f.e.:
>
> execl (mypath/myfile.exe,myfile,arg1,arg2,...)
>
> 
>
> Another question is, when i call my .exe with exec, i understand that
> my .py file will stop running, and instead the new process will be
> launched instead of it. Is it true?
> Is there a way to launch my .exe without finishing my .py file??
>
> thank you very much:)

The exec function is for executing Python code. Have a look at the
subprocess module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread bearophileHUGS
[EMAIL PROTECTED]:
> I believe Python 3k will (when out of beta) will have a speed
> similar to what it has currently in 2.5, possibly with speed ups
> in some locations.

Python 3 uses by default unicode strings and multiprecision integers,
so a little slowdown is possible.


Michele Simionato:
> It is worth reminding that, in more than one sense, the most advanced
> language is the one with less features ...

I don't agree, Scheme or Brainfuck may have less features, but this
doesn't make them more advanced, it just makes programming with them
slower and more difficult. An advanced language is one that already
contains the most useful abstractions. For example Python has
generators and other things that are possible if you use Assembly too,
but having them pre-built in Python avoids me to use my limited brain
power to re-implement them from scratch, and I can focus on the
complex algorithm I am trying to implement. Once the Python program
works, I am then able to translate it to D/C too.
If you want to see an advanced language, you may take a look at
PyMeta, that's a bit of the future of the computer science:
http://washort.twistedmatrix.com/

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread Nick Craig-Wood
Corey G. <[EMAIL PROTECTED]> wrote:
>  The main concern (my concern) is whether or not Perl 6 is  
>  more like Java with pre-compiled byte code (did I say that right)

See below for some python VM comments

>  and whether or not individuals without the ability to see past the
>  surface will begin to migrate towards Perl 6 for its seemingly
>  faster capabilities.

I doubt it but you never know!

>  With Perl 6 taking 10+ years, if/when it actually gets released, will  
>  it be technically ahead of Python 3000? 

Perl 6 was a major reason for me to switch to using python.  To make
that radical a change in the language seemed reckless.  The fact that
it still hasn't been released after 8 years of development (Larry
announced it in his State of the Onion speech in 2000 I think) makes
me think that I made the right choice.

Python 3.0 is a very gentle change to python in comparison.  You won't
have to change much of your code and when you do you'll think - that
looks better!

>  Is Parrot worth the extra wait the Perl 6 project is enduring?  My
>  own answer would be a resounding no, but I am curious as to what
>  others think. :)

Another VM to run python would be nice of course, but we already have
jython, ironpython and pypy.

Both jython and ironpython use JIT, pypy can compile to native code
and you can use psyco for JIT code also in normal python.

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


Bit substring search

2008-06-24 Thread Kris Kennaway
I am trying to parse a bit-stream file format (bzip2) that does not have 
byte-aligned record boundaries, so I need to do efficient matching of 
bit substrings at arbitrary bit offsets.


Is there a package that can do this?  This one comes close:

http://ilan.schnell-web.net/prog/bitarray/

but it only supports single bit substring match.

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


Re: Bit substring search

2008-06-24 Thread bearophileHUGS
Kris Kennaway:
> I am trying to parse a bit-stream file format (bzip2) that does not have
> byte-aligned record boundaries, so I need to do efficient matching of
> bit substrings at arbitrary bit offsets.
> Is there a package that can do this?

You may take a look at Hachoir or some other modules:
http://hachoir.org/wiki/hachoir-core
http://pypi.python.org/pypi/construct/2.00
http://pypi.python.org/pypi/FmtRW/20040603
Etc. More:
http://pypi.python.org/pypi?%3Aaction=search&term=binary

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Terminating processes on Windows (handles and IDs)

2008-06-24 Thread geoffbache

Thanks for the tip. This does seem rather overkill to introduce all
these dependencies just to be able to
kill a process though...

I've discovered that subprocess.Popen objects have a member "_handle"
which is undocumented but
appears to work, so I'm using that for now. Better suggestions
gratefully received...

Geoff

> My way to do it is using excellent wmi module by Tim Golden, which
> relies on Mark Hammond's pywin32 and Windows native wmi functionality.
> Here is the link -http://tgolden.sc.sabren.com/python/wmi.html
> Maybe, there is a more elegant way of doing that, but it works for me,
> and i feel nice with wmi.

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


Re: binary representation of an integer

2008-06-24 Thread cokofreedom
On Jun 24, 10:38 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Jun 24, 9:03 am, eliben <[EMAIL PROTECTED]> wrote:
>
> > What would be the quickest way to do this ? I think that for dec2bin
> > conversion, using hex() and then looping with a hex->bin lookup table
> > would be probably much faster than the general baseconvert from the
> > recipe.
>
> I suspect you're right, but it would be easy to find out:  just
> code up the hex->bin method and use the timeit module to do some
> timings.  Don't forget to strip the trailing 'L' from hex(n) if n
> is a long.
>
> If you're prepared to wait for Python 2.6, or work with the beta
> version, then the conversion is already there:
>
> Macintosh-3:trunk dickinsm$ ./python.exe
> Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> bin(13)
>
> '0b1101'
>
> Interestingly, unlike hex and oct, bin doesn't add a trailing
> 'L' for longs:
>
> >>> bin(13L)
>
> '0b1101'
>
> I wonder whether this is a bug...
>
> Mark

Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread cokofreedom
And:

# return as a string
def itob_string(integer, count = 8):
return "".join(str((integer >> i) & 1) for i in range(count - 1,
-1, -1))

# return as an iterator (i.e [0, 0, 0, 0, 1, 0, 1, 0])
def itob_list(integer, count = 8):
return [(integer >> i) & 1 for i in range(count - 1, -1, -1)]

# return as a generator
def itob_generator(integer, count = 8):
return ((integer >> i) & 1 for i in range(count - 1, -1, -1))
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling a .exe from Python

2008-06-24 Thread Nick Craig-Wood
evidentemente.yo <[EMAIL PROTECTED]> wrote:
>  Hi, i am trying to call a .exe from my .py file, i have found the exec
>  function, but i'm not sure of how to use it:S
> 
>  would it be f.e.:
> 
>  execl (mypath/myfile.exe,myfile,arg1,arg2,...)
> 
>  
> 
>  Another question is, when i call my .exe with exec, i understand that
>  my .py file will stop running, and instead the new process will be
>  launched instead of it. Is it true?
>  Is there a way to launch my .exe without finishing my .py file??
> 
>  thank you very much:)

Probably what you want is this...

from subprocess import call

rc = call(["mypath/myfile.exe",arg1,arg2])

rc will contain the exit status

See the subprocess module for more things you can do

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


Re: sending executable data over network..

2008-06-24 Thread Piyush Anonymous
any idea or pointer how i could link it to running code in server?
for example, i get a new method definition for a method and i wish to change
it.
client sent new definition, i compile it in server. how can i link it to old
code?
if it will running in same environment, i would write
objectA.getdata()=getdatanew()

here?

On Tue, Jun 24, 2008 at 4:15 PM, Cédric Lucantis <[EMAIL PROTECTED]> wrote:

> Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez écrit :
> > hi,
> > i wish to change the way the function definition at run time in a running
> > server. new function code which is to be executed is provided by a client
> > at different location.
> > i am getting it by reading a file and sending it using makefile() with
> > server/client connected using sockets.
> >
> > how can make the lines received in a string array as new function
> > definition? or should i receive it in a different way?
> >
> > is there any better way to do the entire thing?
>
> One way is to transmit the code as a string and compile it on server-side
> with
> the 'compile' builtin function. Another is to compile it on client-side and
> transmit the resulting code object with the marshal module but there are
> many
> restrictions on it (specially the fact that the client and server will have
> to run the same python version) so carefully read the docs first. I'd
> choose
> the first solution, eventually using the pickle module to avoid encoding
> problems.
>
> --
> Cédric Lucantis
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list

Re: Terminating processes on Windows (handles and IDs)

2008-06-24 Thread Tim Golden

Val-Amart wrote:

On Jun 23, 6:33 pm, geoffbache <[EMAIL PROTECTED]> wrote:

Hi all,

I've always wondered why os.kill isn't supported on Windows. I found a
discussion somewhere from 2006 about this so it seems others have
wanted it, but still nothing. So I have a half-baked solution
involving calling "taskkill" on Windows Vista or "tskill" on Windows
XP via the shell. I feel there has to be a better way.

I'm also fairly confused about when I've got an ID and when I've got a
handle. The subprocess module gives me IDs which the above programs
accept, but other ways of spawning processes give me process handles
(while referring to them as process IDs in the docs...) and I don't
know how to kill a process with these. Besides, I've found an
amazingly useful PyGTK method, gobject.child_watch_add, which does
exactly what I want on UNIX but wants process handles on Windows. So I
can't use it in conjunction with subprocess there, and if I use some
other way of spawning processes I can't clean them up later.

Is there any way to convert one of these numbers to the other? Or to
get a process handle out of subprocess?
(There must be one down there somewhere, surely?)

Sorry for rambling a bit, am confused.

Regards,
Geoff Bache


My way to do it is using excellent wmi module by Tim Golden, which
relies on Mark Hammond's pywin32 and Windows native wmi functionality.
Here is the link - http://tgolden.sc.sabren.com/python/wmi.html
Maybe, there is a more elegant way of doing that, but it works for me,
and i feel nice with wmi.


While I'm always happy to see WMI promoted  this is one of
these occasions when there *are* other solutions. A few points to respond
to the OP:

1) In the trunk versions of Python (2.6 & 3.0, both in beta), the 
subprocess.Popen
objects have grown a .kill method:



Python 2.6b1+ (trunk:64424, Jun 20 2008, 15:32:22) [MSC v.1500 32 bit (Intel)] 
on win32
Type "help", "copyright", "credits" or "license" for more information.

import subprocess
p = subprocess.Popen (["notepad.exe"])
p.kill ()






so maybe some of the problem has gone away in any case.

2) The Popen objects have an internal _handle attribute which,
prior to 2.6, is used to pass along to the TerminateProcess
function of the Windows API. Here's a recipe illustrating
various techniques:

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


3) Under the covers, subprocess calls the CreateProcess Windows API:

http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx

This passes back out four params: the process handle, the thread
handle, the process id and the thread id. The process handle is
kept in the _handle attribute of the Popen object; the process id
is kept in the pid attribute. You can pass whichever of these makes
sense to other routines which require them.

4) (In case it helps). The getpid function of the OS works perfectly
well under windows to return the Process Id of the current process
(*not* the handle).

5) If you *do* use WMI, then be aware that the Win32_Process object
has two likely-looking attributes: Handle and ProcessId. They *both*
contain the process id.

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


Re: binary representation of an integer

2008-06-24 Thread bearophileHUGS
eliben:
> Python's pack/unpack don't have the binary format for some reason, so
> custom solutions have to be developed. One suggested in the ASPN
> cookbook is:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286
> However, it is very general and thus inefficient.

Try mine, it may be fast enough for your purposes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between two dates

2008-06-24 Thread sniipe
Thank you for answers.

I used Cédric Lucantis's way to resolve this problem and it works :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between two dates

2008-06-24 Thread sniipe
Thank you for answers :)

I used Cédric Lucantis's way to resolve this problem and it works :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

> The fact that
> it still hasn't been released after 8 years of development (Larry
> announced it in his State of the Onion speech in 2000 I think) makes
> me think that I made the right choice.

Sometimes you gotta be patient.  Wine took 15 years 
(http://www.winehq.org/?announce=1.0).  Not that I'm supporting Perl 6, 
just saying that gestation time is not always an indicator of value :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread Michele Simionato
On Jun 24, 1:19 pm, [EMAIL PROTECTED] wrote:
> Michele Simionato:
>
> > It is worth reminding that, in more than one sense, the most advanced
> > language is the one with less features ...
>
> I don't agree, Scheme or Brainfuck may have less features, but this
> doesn't make them more advanced, it just makes programming with them
> slower and more difficult. An advanced language is one that already
> contains the most useful abstractions. For example Python has
> generators and other things that are possible if you use Assembly too,
> but having them pre-built in Python avoids me to use my limited brain
> power to re-implement them from scratch, and I can focus on the
> complex algorithm I am trying to implement.

Oh, you are taking my words too literally, relax and take them in the
context of
the thread. Also consider the famous Clinger's maxim
“Programming languages should be designed not by piling feature
on top of feature, but by removing the weaknesses and restrictions
that make additional
features appear necessary.”

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


Re: Bit substring search

2008-06-24 Thread Kris Kennaway

[EMAIL PROTECTED] wrote:

Kris Kennaway:

I am trying to parse a bit-stream file format (bzip2) that does not have
byte-aligned record boundaries, so I need to do efficient matching of
bit substrings at arbitrary bit offsets.
Is there a package that can do this?


You may take a look at Hachoir or some other modules:
http://hachoir.org/wiki/hachoir-core
http://pypi.python.org/pypi/construct/2.00


Thanks.  hachoir also comes close, but it also doesnt seem to be able to 
match substrings at a bit level (e.g. the included bzip2 parser just 
reads the header and hands the entire file off to libbzip2 to extract 
data from).


construct exports a bit stream but it's again pure python and matching 
substrings will be slow.  It will need C support to do that efficiently.



http://pypi.python.org/pypi/FmtRW/20040603
Etc. More:
http://pypi.python.org/pypi?%3Aaction=search&term=binary


Unfortunately I didnt find anything else useful here yet :(

Kris

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


Re: Sending information to a website

2008-06-24 Thread Jim
One way is to use a package that allows you to simulate being a
browser:
  http://wwwsearch.sourceforge.net/mechanize/
.

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


Re: Sending information to a website

2008-06-24 Thread Jeff McNeil
On Jun 24, 12:13 am, Alex Bryan <[EMAIL PROTECTED]> wrote:
> Okay, so what I want to do is connect to dictionary.com and send the
> website a word, and later receive the definition. But for now, I want
> to focus on sending the word. A good guy from this mailing list said I
> should look into the code and then figure out what the word you want
> to be defined is called by the website. In other words, what is the
> name of the word the user inputs. Okay, so using the firebug extension
> I got the code that the search field on the website uses. here is that
> code.
>
> 
>  name="search_form">
>  maxlength="256"
> value="" name="q"/>
>
> Anyway, not to get to complicated. How would any of you suggest I send
> this word to the site. While bearing in mind that I will need to
> return it if it matters for this step.

You should be able to automate the submission via urllib.urlopen.  On
success, that call will return a file-like object that contains the
response HTML code. You do need to be a bit careful when 'screen
scraping' as many sites have terms of service agreements that
explicitly deny automating requests.

Once you've got the HTML back, you'll need to pull the definition out.
Look at BeautifulSoup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: String split with " and/or ' and/or \

2008-06-24 Thread Kurt Mueller

Peter Otten schrieb:

Kurt Mueller wrote:

How to (super)split a string (literal) containing " and/or ' and/or
\.
example:

' a  "  b b   "  c\ c '.supersplit(' ')
->
['a', '  b b   ', 'c c']



import shlex
shlex.split(' a  "  b b   "  c\ c ')

['a', '  b b   ', 'c c']


Thanks Peter
Thanks Paul

shlex is what I was looking for.


Grüessli
--
Kurt Müller, [EMAIL PROTECTED]

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

Re: Bit substring search

2008-06-24 Thread bearophileHUGS
Kris Kennaway:
> Unfortunately I didnt find anything else useful here yet :(

I see, I'm sorry, I have found hachoir quite nice in the past. Maybe
there's no really efficient way to do it with Python, but you can
create a compiled extension, so you can see if it's fast enough for
your purposes.
To create such extension you can:
- One thing that requires very little time is to create an extension
with ShedSkin, once installed it just needs Python code.
- Cython (ex-Pyrex) too may be okay, but it's a bit trikier on Windows
machines.
- Using Pyd to create a D extension for Python is often the faster way
I have found to create extensions. I need just few minutes to create
them this way. But you need to know a bit of D.
- Then, if you want you can write a C extension, but if you have not
done it before you may need some hours to make it work.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread bearophileHUGS
Michele Simionato:
Also consider the famous Clinger's maxim
> “Programming languages should be designed not by piling feature
> on top of feature, but by removing the weaknesses and restrictions
> that make additional features appear necessary.”

I'm relaxed, don't worry :-)
I know that maxim, but after learning Python, Scheme (and lot of other
things) I think it's often wrong.
Well chosen restrictions sometimes are very useful, they may act like
a scaffolding, you can build higher constructions on them (Python has
no macros, this is a restriction. But this restriction has some
advantages. One of the main advantages is that it makes the Python
code more uniform across different programmers, this is one of the
thinks that makes the Python world so full of pre-made modules to do
most of the things you may want to do).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: python script for tortoise cvs

2008-06-24 Thread sandeep
On Jun 20, 2:54 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 19 Jun 2008 10:26:09 -0300, Simon Brunning <[EMAIL PROTECTED]> 
> escribió:
>
>
>
> > On Thu, Jun 19, 2008 at 2:14 PM, sandeep <[EMAIL PROTECTED]> wrote:
> >> hi
>
> >> we are using tortoise cvs and putty. i want to write a python script
> >> to whom i can provide a tag and module.now what this script will do is
> >> look for this specific tag and checks for whether its a individual tag
> >> or its inside a branch.if its inside a branch then find out what is
> >> the branch tag and then check out that branch for me else it checks
> >> out that module with that tag.
>
> >> Actually the thing is i am not able to find the way how i will do it
> >> and for where i have to look for the info.so any help will be
> >> appreciated.
>
> > I don't know if Tortoise is scriptable, but Subversion certainly is -
> >  - and nothing you mention is Tortoise
> > specific.
>
> (Note that he said Tortoise CVS - not Tortoise SVN)
> To Sandeep: You should divide the question in two parts:
> - how to obtain the info you want from cvs. This has nothing to do with 
> Python; better ask in a CVS group related to your server. Suppose the answer 
> is "use the status command with the -lv options", then you'll be able to 
> obtain the info you want "by hand", executing said cvs command from the cmd 
> prompt.
> - the next task is to automate the execution using Python. You have to run 
> the command, capture its output and extract the info you want. How to do that 
> *is* a Python question, but you'll have to formulate it very precisely: "I 
> want to read the output coming from this command, locate the line that 
> contains the word XXX starting at column 12, and take the last word on the 
> third line below it"
> For that second part you can get some help here, but first you have to know 
> *what* to execute and *what* to look for in the output.
>
> (Anyway, I think the question is not well formulated - what is an "individual 
> tag", as opposed to "inside a branch"? Every tag applied on a file marks a 
> certain revision in a certain branch, - if you consider the trunk as a branch 
> too. Do you want to know if the tag was applied directly over a file on the 
> trunk? Or do you want to know if the tag is a "branch tag"?)
>
> --
> Gabriel Genellina


thanks Gabriel

i think ur suggestions do formulate my problem.now since i know some
commands i wanted to know how can i execute cvs commands from python
or we can say how can i capture the output from the cvs command ?.

thanks and regards
sandeep kumar sharma

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


Re: string.Template.delimiter cannot be overriden?

2008-06-24 Thread Raymond Hettinger
[kretik]
>> I've been trying to coax this class to use something other than the
> >> default '$' but it seems setting it to something else has no discernible
> >> effect. Is it necessary to inherit from the class to do this?

[raymond]
> > Yes, subclassing is the intended way to produce variants of Template
> > with a different delimiter.

[gabriel]
> Just out of curiosity, why was it done that way?
> I'd say the "obvious" way to change the default delimiter would be to set  
> an instance attribute - so I guess this was a deliberate decision, but I  
> can't figure out why it is better this way...

IIRC, Barry and Tim came-up with the metaclass because the delimiter
and
pattern decisions are less granular than the creating of individual
templates.
Typically, the former decision is made once per application, but there
may
be thousands of template instances.

An earlier version of the API looked like this:

   s = Template('Move %piece to %position', delimiter='%')
   t = Template('%source takes %target', delimiter='%')

The repeated need to set the delimiter for every template was slow and
error-prone.

The newer API is:

class PercentTemplate(string.Template):
delimiter = '%'
s = PercentTemplate('Move %piece to %position')
t = PercentTemplate('%source takes %target')

So, basically it was just a factoring decision.

Instead of using a metaclass, one other possible choice would have
been to use a factory function:

PercentTemplate = template_maker(delimiter='%')
s = PercentTemplate('Move %piece to %position')
t = PercentTemplate('%source takes %target')

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


Re: Bit substring search

2008-06-24 Thread Kris Kennaway

[EMAIL PROTECTED] wrote:

Kris Kennaway:

Unfortunately I didnt find anything else useful here yet :(


I see, I'm sorry, I have found hachoir quite nice in the past. Maybe
there's no really efficient way to do it with Python, but you can
create a compiled extension, so you can see if it's fast enough for
your purposes.
To create such extension you can:
- One thing that requires very little time is to create an extension
with ShedSkin, once installed it just needs Python code.
- Cython (ex-Pyrex) too may be okay, but it's a bit trikier on Windows
machines.
- Using Pyd to create a D extension for Python is often the faster way
I have found to create extensions. I need just few minutes to create
them this way. But you need to know a bit of D.
- Then, if you want you can write a C extension, but if you have not
done it before you may need some hours to make it work.


Thanks for the pointers, I think a C extension will end up being the way 
to go, unless someone has beaten me to it and I just haven't found it yet.


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


Re: How to import filenames with special characters?

2008-06-24 Thread Gary Herron

inhahe wrote:
How would I import a python file whose name contains characters like .'s or 
!'s?


Is there really _no_ way to do that?  I have to use plain jane letters and 
numbers for everything?
  


The import statement can't help you, but take a look at the __import__ 
builtin function and the standard module named "imp".


Gary Herron
*
*


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


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


Re: Python 3000 vs Perl 6

2008-06-24 Thread Kay Schluehr
On 24 Jun., 13:19, [EMAIL PROTECTED] wrote:

> If you want to see an advanced language, you may take a look at
> PyMeta, that's a bit of the future of the computer 
> science:http://washort.twistedmatrix.com/

Er, no. The future of CS is also its past i.e. EBNF ;)

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


percent string replacement with index

2008-06-24 Thread Ulrich Eckhardt
Hi!

I'm still mostly learning Python and there is one thing that puzzles me
about string formatting. Typical string formatting has these syntaxes:

  "%s is %s" % ("GNU", "not Unix")
  "%(1)s %(2)s" % ("1":"one", "2":"two")

What I'm surprised is that this isn't supported:

  "%(1)s %(2)s" % ("zero", "one", "two")

i.e. specifying the index in a sequence instead of the key into a map (maybe
I would use [1] instead of (1) though). Further, the key can't be a simple
number it seems, which makes this even more inconvenient to me.

Can anyone explain this to me?

Also, why isn't the 's' conversion (i.e. to a string) the default? I
personally would like to just write something like this:

  "%1 is not %2" % ("zero", "one", "two")

or maybe

  "%[1] is not %[2]" % ("zero", "one", "two")


greetings!

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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

Re: very large graph

2008-06-24 Thread castironpi
On Jun 24, 5:58 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-06-24, MRAB <[EMAIL PROTECTED]> wrote:
>
> > On Jun 24, 1:26 am, [EMAIL PROTECTED] wrote:
> >> I need to represent the hyperlinks between a large number of HTML
> >> files as a graph.  My non-directed graph will have about 63,000 nodes
> >> and and probably close to 500,000 edges.
>
> >> I have looked into igraph (http://cneurocvs.rmki.kfki.hu/igraph/doc/
> >> python/index.html) and networkX (https://networkx.lanl.gov/wiki) for
> >> generating a file to store the graph, and I have also looked into
> >> Graphviz for visualization.  I'm just not sure which modules are
> >> best.  I need to be able to do the following:
>
> Afaik Graphviz is not good at abstracting the graph, which you may need here.
> A page with 63,000 circles on it, and 500,000 edges will probably come out of
> the printer as a black sheet of paper.
> (8"x11" paper, 1 circle is 1/5", then you have only 2200 circles at one sheet.
> You need a factor 28 more circles which leads to a circle of about 0.007".)
>
> Even when actual paper format would not be a problem, you will need some
> abstraction and/or tools, as you will not find anything manually in an ocean 
> of
> 63,000 elements.
>
> One area you may want to start looking for tools is in state graphs, where the
> set of possible states of an entire system is unfolded. These things go up to
> over a million states, so you only have a 'small' problem there...
>
>
>
>
>
> >> 1)  The names of my nodes are not known ahead of time, so I will
> >> extract the title from all the HTML files to name the nodes prior to
> >> parsing the files for hyperlinks (edges).
>
> >> 2) Every file will be parsed for links and nondirectional connections
> >> will be drawn between the two nodes.
>
> >> 3)  The files might link to each other so the graph package needs to
> >> be able to check to see if an edge between two nodes already exists,
> >> or at least not double draw connections between the two nodes when
> >> adding edges.
>
> >> I'm relatively new to graph theory so I would greatly appreciate any
> >> suggestions for filetypes.  I imagine doing this as a python
> >> dictionary with a list for the edges and a node:list paring is out of
> >> the question for such a large graph?
>
> > Perhaps a dictionary where the key is a node and the value is a set of
> > destination nodes?
>
> For undirected edges, you could make an Edge class and have a set of Edge's
> (where two Edge objects are equal when they connect the same nodes).
> I don't expect 500,000 elements in a set to be a problem.
>
> Sincerely,
> Albert- Hide quoted text -
>
> - Show quoted text -

Readability counts: Do you need to be able to examine the datafile by
hand?  If not, investigate the 'shelve' module.  You can go two ways.
One is to map each node to a list of nodes.  It's probably more
intuitive, but it needs repeated code:

shelf['pageA'].add( pageB )
shelf['pageB']= pageB
shelf['pageB'].add( pageA )

Which is incorrect as is anyway-- updates to shelved objects aren't
committed automatically.

a= shelf['pageA']
a.add( pageB )
shelf['pageA']= a
b= shelf['pageB']
b.add( pageA )
shelf['pageB']= b

is closer.  Otherwise, two is to store a 2-tuple of node keys in a
secondary file.

shelfEdges[ frozenset(
shelfVerts[ 'pageA' ], shelfVerts[ 'pageB' ]
) ]= True

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread Kay Schluehr
On 24 Jun., 13:19, [EMAIL PROTECTED] wrote:

> If you want to see an advanced language, you may take a look at
> PyMeta, that's a bit of the future of the computer 
> science:http://washort.twistedmatrix.com/

Er, no. The future of CS is also its past i.e. EBNF ;)

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


Re: Fwd: xml to mysql (vice versa ) too

2008-06-24 Thread Stefan Behnel
> Le Tuesday 24 June 2008 07:08:46 swapna mudavath, vous avez écrit :
>> can anybody help me in this
>>
>> -swapna
>>
>> -- Forwarded message --
>> From: swapna mudavath <[EMAIL PROTECTED]>
>> Date: Mon, Jun 23, 2008 at 5:27 PM
>> Subject: xml to mysql (vice versa ) too
>> To: Python-list@python.org
>>
>>
>> Hi,
>>
>> I need to write a python script to store data which is in XML to MYSQL and
>> even vice versa
>> what should be the approach?
>> i am able to establish a connection,create tables and insert data .
>> but how to read an xml file and store in MYSQL
>> my XML structure is like
>>
>> 
>> 
>> 
>> 
>> 
>>.
>>
>>...
>> 
> 
> This is not valid xml, there is no commas in attribute list in xml.

Yes, so maybe you should tell us where you got this from and if you are in the
position to change this?


>> can somebody please help me..i am really confused!!

Try lxml.objectify. It lets you work with XML as it if were simple Python 
objects.

http://codespeak.net/lxml/objectify.html

That should allow you to easily extract data from the XML and to generate XML
from the data you get from MySQL.

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


Re: Python 3000 vs Perl 6

2008-06-24 Thread Eric Wertman
Flaming Thunder FTW!!!


thank you, I'm here all week.
--
http://mail.python.org/mailman/listinfo/python-list


Connecting through another program

2008-06-24 Thread animefanfive
I am attempting to make an addon to a game. The game developers allow
what I want to do but in order to comply with the rules I must allow
the user to connect with the default client and then I can close it if
I don't need it. How would I call the client and take it's connection
so I can close it once I am done with it?
--
http://mail.python.org/mailman/listinfo/python-list


NameError: name 'maketrans' is not defined, pythonchallenge

2008-06-24 Thread cirfu
im doing the python challenge and well, i solved this problem with
ruby :)
phrase = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq
ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr
gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc
spj."
puts phrase .tr('A-XY-Za-xy-z','C-ZA-Bc-za-b')

the answer says to use maketrans but i cant get it to work:

>>> pat = maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')

Traceback (most recent call last):
  File "", line 1, in 
pat = maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')
NameError: name 'maketrans' is not defined

>>> "hej tjena tjenixen".maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')

Traceback (most recent call last):
  File "", line 1, in 
"hej ditt fetto".maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')
AttributeError: 'str' object has no attribute 'maketrans'

http://docs.python.org/lib/node41.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread Michele Simionato
On Jun 24, 5:11 pm, [EMAIL PROTECTED] wrote:
> Well chosen restrictions sometimes are very useful, they may act like
> a scaffolding, you can build higher constructions on them (Python has
> no macros, this is a restriction. But this restriction has some
> advantages. One of the main advantages is that it makes the Python
> code more uniform across different programmers, this is one of the
> thinks that makes the Python world so full of pre-made modules to do
> most of the things you may want to do).

I am all in favor of *well chosen* restrictions.
However the meaning of "well chosen" depends on the context. For
instance, just today I was reading this
very interesting paper on PLT Scheme object system:
http://www.cs.utah.edu/plt/publications/aplas06-fff.pdf
The interesting thing is that the whole system
is built in pure Scheme on top of macros, and still
it has an acceptable performance. In Python I could never
do the same, I would need to resort to C. So, while
I agree that for the common use cases of the enterprise
programmer Python is much more productive than Scheme,
a computer scientists experimenting with object systems
will probably find Scheme more suitable then Python.
But I am digressing. The point is that a language
with very few well chosen features (say Scheme)
allows you to build everything else on top of it
(say an object system) without needing to resort
to a different implementation language.
I program in Python much more than in Scheme for many reasons, but not
because I think that Clinger's maxin is wrong.

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


Python-URL! - weekly Python news and links (Jun 24)

2008-06-24 Thread Gabriel Genellina
QOTW:  "I find that eloquent Python speakers often tend to write a for loop
when mere good ones will try to stick a list comprehension in!" - Arnaud
Delobelle
http://groups.google.com/group/comp.lang.python/msg/dfc72ea32f1f9c91


The first beta release of Python 3.0 is out (jointly with 2.6b1):

http://groups.google.com/group/comp.lang.python/browse_thread/thread/baed11a52a011db3/

A case where generating Python source code may be the right answer:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/646169e4558bf5cd/

Jump to a specific line number in a text file:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/256642d6e9d7abe4/

Problem: how to break out of multiple threads when some are waiting for I/O:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/59fa6ebbeefc62cc/

Several ways (very different!) to split complex comma-separated
expressions:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/deba5d550991a3bd/

Martin v. L=F6wis explains why it's difficult to compute the size
of an object accurately:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/28a66f81876f286c/

A proposal for ordered dictionaries:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/311037a19055442c/

Launching a Ruby script and getting data back:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/5e6dbcabc4f7459f/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://www.synd

Re: NameError: name 'maketrans' is not defined, pythonchallenge

2008-06-24 Thread cirfu
from string import maketrans

ok but how can i write:
pattern = maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')
pattern = maketrans('A-Za-z', 'C-Bc-b')
none works
--
http://mail.python.org/mailman/listinfo/python-list


Re: NameError: name 'maketrans' is not defined, pythonchallenge

2008-06-24 Thread cirfu
import string
text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq
ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr
gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc
spj."
table = string.maketrans(string.ascii_lowercase,
string.ascii_lowercase[2:]+string.ascii_lowercase[:2])
print string.translate(text,table)


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


shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread cirfu
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

cant i write something like:
if char in "[A-Za-z]":

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


Re: String question

2008-06-24 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

On Jun 24, 5:38 am, "Mark Tolonen" <[EMAIL PROTECTED]> wrote:




In Python 3k I believe you can put a * next to one of the variables to
hold multiple arguments. That'll be aidful!


IDLE 3.0b1
>>> a,b,*c=[1,2,3,4,5]
>>> c
[3, 4, 5]
>>> a,*b,c = [1,2,3,4,5]
>>> b
[2, 3, 4]
>>> a,b,*c=[1,2]
>>> c
[]

Augmented assignment is quite similar to argument passing:
at most one starred target;
at least as many items as un-starred targets (as now).

tjr

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


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread Brian Victor
cirfu wrote:
> if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> cant i write something like:
> if char in "[A-Za-z]":

Either of the following should do what you want, without resorting to
regular expressions:

import string
if char in string.letters:

or

if char.isalpha():

-- 
Brian

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


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread [EMAIL PROTECTED]
On 24 juin, 20:32, cirfu <[EMAIL PROTECTED]> wrote:
> if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> cant i write something like:
> if char in "[A-Za-z]":
>

Nope. But there are other solutions. Here are two:

# 1
import string

if char in string.letters:
   print "yay"

# 2
import re
exp = re.compile(r'[A-Za-z]')

if exp.match(char):
   print "yay"

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


Re: NameError: name 'maketrans' is not defined, pythonchallenge

2008-06-24 Thread Guilherme Polo
On Tue, Jun 24, 2008 at 3:11 PM, cirfu <[EMAIL PROTECTED]> wrote:
> from string import maketrans
>
> ok but how can i write:
> pattern = maketrans('A-XY-Za-xy-z', 'C-ZA-Bc-za-b')
> pattern = maketrans('A-Za-z', 'C-Bc-b')
> none works

maketrans doesn't work like that, you would need something like this:

sfrom = string.uppercase + string.lowercase
sto = string.uppercase[2:] + string.uppercase[:2] +
string.lowercase[2:] + string.lowercase[:2]
table = string.maketrans(sfrom, sto)

print string.translate(phrase, table)

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: sending executable data over network..

2008-06-24 Thread Terry Reedy



Piyush Anonymous wrote:

any idea or pointer how i could link it to running code in server?
for example, i get a new method definition for a method and i wish to 
change it.
client sent new definition, i compile it in server. how can i link it to 
old code?


Code to be hot-updated (while running) must have update capability 
builtin.  But please consider security.  If a remote system can log in 
and *push* code, an attacker can potentially do the same.  Notice that 
self-updating programs and systems generally log out to a hardwired 
location, ask if there are updates, and *pull* the new code.


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


Re: Using Python and MS-SQL Server

2008-06-24 Thread Ed Leafe

On Jun 23, 2008, at 11:10 AM, [EMAIL PROTECTED] wrote:


The current script that I am working on requires pulling in some
information from a Microsoft SQL Server.

I was wondering if anyone could suggest the best way of doing this?  I
have looked at the different modules that are specific to SQL server,
but none of them seem to be active or up to date.



	Dabo may be what you need. It is a 3-tier framework for developing  
desktop applications, so even if you are doing web apps, the data  
access layer is fully usable by itself. We support MS SQL Server, as  
well as several other database backends.


-- Ed Leafe
-- http://dabodev.com



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


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread Guilherme Polo
On Tue, Jun 24, 2008 at 3:47 PM, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> On 24 juin, 20:32, cirfu <[EMAIL PROTECTED]> wrote:
>> if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>>
>> cant i write something like:
>> if char in "[A-Za-z]":
>>
>
> Nope. But there are other solutions. Here are two:
>
> # 1
> import string
>
> if char in string.letters:
>   print "yay"
>
> # 2
> import re
> exp = re.compile(r'[A-Za-z]')
>
> if exp.match(char):
>   print "yay"
>

Let me post another one, and longer:

if ord(somechar) in range(ord('A'), ord('Z') + 1) + range(ord('a'),
ord('z') + 1):
...


-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread Terry Reedy



[EMAIL PROTECTED] wrote:

On Jun 24, 10:38 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:



Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:


bin(13L)

'0b1101'

I wonder whether this is a bug...




Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.


In current 2.x, the trailing L is no longer required for long integer 
input; the lexer decides whether to make an int or long.  Similarly, 
ints are automatically converted to longs as needed instead of raising 
overflow errors (as once happended).  The trailing L on output would 
have been removed already except for backward compatibility.  But there 
was no back-compatibility requirement for 0b strings.


In 3.0, all integers are class 'int'.  The internal representation as 
fixed or extended precision is entirely an internal implementation matter.


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


Python on Gcc llvm

2008-06-24 Thread Marco Bazzani
I would like to point you to this post readed some days ago got from
planet python
I search inside this group but I didn't find anything related (am I
wrong?)
anyway here it is,
http://sayspy.blogspot.com/2008/06/i-cant-build-python-using-llvm.html
I've more or less the same questions reported in the blog
--
http://mail.python.org/mailman/listinfo/python-list


Re: percent string replacement with index

2008-06-24 Thread Terry Reedy



Ulrich Eckhardt wrote:


What I'm surprised is that this isn't supported:

  "%(1)s %(2)s" % ("zero", "one", "two")

i.e. specifying the index in a sequence instead of the key into a map (maybe
I would use [1] instead of (1) though). Further, the key can't be a simple
number it seems, which makes this even more inconvenient to me.

Can anyone explain this to me?


History.  See below.


Also, why isn't the 's' conversion (i.e. to a string) the default? I
personally would like to just write something like this:

  "%1 is not %2" % ("zero", "one", "two")

or maybe

  "%[1] is not %[2]" % ("zero", "one", "two")


In 2.6 (I believe) and 3.0:

>>> "{1} is not {2} or {0}. It is just {1}".format("zero", "one", "two")
'one is not two or zero. It is just one'

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


Re: sending executable data over network..

2008-06-24 Thread Piyush Anonymous
assuming security is not of concern at the moment,

how can i add in update capability? please help me out or show some pointers
to look into.

i wish to change the way the method definition of a class at run time in a
running server (actually i m planning to support many changes at run time).
new code which is to be executed is provided by a client at different
location.
i am receiving the code as a string and compile it on server-side with the
'compile' builtin function or get compiled code using marshal. however i
cannot link it to the running code in server?

for example, i get a new method definition for a method in class and i wish
to change it.
client sent new definition, i compile it in server, getting a code object.
how can i link it to old code?

if it will running in same environment, i could simply write
A.getdata=getdatanew  # A is a class

how should i do it here? should i change the way i am receiving the code?

thanks for help
-piyush

On Wed, Jun 25, 2008 at 12:22 AM, Terry Reedy <[EMAIL PROTECTED]> wrote:

>
>
> Piyush Anonymous wrote:
>
>> any idea or pointer how i could link it to running code in server?
>> for example, i get a new method definition for a method and i wish to
>> change it.
>> client sent new definition, i compile it in server. how can i link it to
>> old code?
>>
>
> Code to be hot-updated (while running) must have update capability builtin.
>  But please consider security.  If a remote system can log in and *push*
> code, an attacker can potentially do the same.  Notice that self-updating
> programs and systems generally log out to a hardwired location, ask if there
> are updates, and *pull* the new code.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread Walter Cruz
another way:

import string

if char in string.ascii_letters:
  print('hello buddy!')

[]'s
- Walter
--
http://mail.python.org/mailman/listinfo/python-list


Wrap Numpy with Cython?

2008-06-24 Thread martin . nordstrom87
Hi! I'm trying to wrap numpy with Cython and I've tried to use this
guide to manage this: http://wiki.cython.org/WrappingNumpy
However when I send an array to mysum() it gives me the right answer
only when dtype of the array is float, otherwise it gives me random
answers. The problem may be that the array is converted to a C double
which is just as long as float for Numpyarrays and therefore it works
only when the dtype is float. How do I make a Numpywrapper that works
with an arbitrary dtype?

I've also tried to convert a tuple or list with only numbers in it to
a C array with Cython but I've failed. Does anyone have an example of
how to do this?

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


Re: Wrap Numpy with Cython?

2008-06-24 Thread Robert Kern

[EMAIL PROTECTED] wrote:

Hi! I'm trying to wrap numpy with Cython and I've tried to use this
guide to manage this: http://wiki.cython.org/WrappingNumpy
However when I send an array to mysum() it gives me the right answer
only when dtype of the array is float, otherwise it gives me random
answers. The problem may be that the array is converted to a C double
which is just as long as float for Numpyarrays and therefore it works
only when the dtype is float. How do I make a Numpywrapper that works
with an arbitrary dtype?


You will need a Cython function for each dtype and dispatch based on the dtype.

You will want to ask further numpy questions on the numpy mailing list:

  http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


newb question on strings

2008-06-24 Thread regex_jedi
ok, I have looked a lot of places, and can't seem to get a clear
answer...

I have a string called
   each_theme

Some values of the string may contain a single quote as in -
   Happy
   Sad
   Nice
   Frank's Laundry
   Explosion

Notice that the 4th value has a single quote in it. Well, I need to
make sure that the single quote is escaped before handing it off for
further processing to a class I later call for some other processing.

So I thought, no big deal, I should be able to find a way to escape
the single quote on the string.  I am a perl and PHP guy, so I do a
lot of regex stuff.  I did a quick search and found someone had said
to use this re.sub function, so I tried.  But the following doesn't
work. To be honest, I am a little lost with all the modules and
classes required to do simple math or string functions in Python.
None of it seems built it in.. its all import modules...  Here is what
I am trying...

# escape single quotes in theme name
re.sub('''(['"])''', r'\\\1', each_theme)

you python masters... show me the way please...

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


Re: newb question on strings

2008-06-24 Thread [EMAIL PROTECTED]
Are you trying to escape for a regular expression?

Just do re.escape().

>>> print re.escape('Happy')
Happy
>>> print re.escape("Frank's Diner")
Frank\'s\ Diner

If you're escaping for URLs, there's urllib2.quote(), for a command
line, use subprocess.list2cmdline.

Generally, the module that consumes the string should provide a
function like escape().


On Jun 24, 1:27 pm, regex_jedi <[EMAIL PROTECTED]> wrote:
> ok, I have looked a lot of places, and can't seem to get a clear
> answer...
>
> I have a string called
>    each_theme
>
> Some values of the string may contain a single quote as in -
>    Happy
>    Sad
>    Nice
>    Frank's Laundry
>    Explosion
>
> Notice that the 4th value has a single quote in it. Well, I need to
> make sure that the single quote is escaped before handing it off for
> further processing to a class I later call for some other processing.
>
> So I thought, no big deal, I should be able to find a way to escape
> the single quote on the string.  I am a perl and PHP guy, so I do a
> lot of regex stuff.  I did a quick search and found someone had said
> to use this re.sub function, so I tried.  But the following doesn't
> work. To be honest, I am a little lost with all the modules and
> classes required to do simple math or string functions in Python.
> None of it seems built it in.. its all import modules...  Here is what
> I am trying...
>
>         # escape single quotes in theme name
>         re.sub('''(['"])''', r'\\\1', each_theme)
>
> you python masters... show me the way please...
>
> thanks
> regex_jedi

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


Re: percent string replacement with index

2008-06-24 Thread Matimus
On Jun 24, 12:26 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Ulrich Eckhardt wrote:
> > What I'm surprised is that this isn't supported:
>
> >   "%(1)s %(2)s" % ("zero", "one", "two")
>
> > i.e. specifying the index in a sequence instead of the key into a map (maybe
> > I would use [1] instead of (1) though). Further, the key can't be a simple
> > number it seems, which makes this even more inconvenient to me.
>
> > Can anyone explain this to me?
>
> History.  See below.
>
>
>
> > Also, why isn't the 's' conversion (i.e. to a string) the default? I
> > personally would like to just write something like this:
>
> >   "%1 is not %2" % ("zero", "one", "two")
>
> > or maybe
>
> >   "%[1] is not %[2]" % ("zero", "one", "two")
>
> In 2.6 (I believe) and 3.0:
>
>  >>> "{1} is not {2} or {0}. It is just {1}".format("zero", "one", "two")


Or even:

>>> "{0[1]} is not {0[2]} or {0[0]}. It is just {0[1]}".format(["zero", "one", 
>>> "two"])
'one is not two or zero. It is just one'

Or

>>> "{one} is not {two} or {zero}. It is just {one}".format(zero="zero", 
>>> one="one", two="two")
'one is not two or zero. It is just one'

Or

>>> class C(object):
... def __init__(self, zero, one, two):
... self.zero = zero
... self.one = one
... self.two = two
...
>>> "{0.one} is not {0.two} or {0.zero}. It is just {0.one}".format(C("zero", 
>>> "one", "two"))
'one is not two or zero. It is just one'

More information: http://www.python.org/dev/peps/pep-3101/

Exciting stuff.

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


logging module's documentation lies?

2008-06-24 Thread [EMAIL PROTECTED]
Quote from the docs:

FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset",
extra=d)

would print something like

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem:
connection reset

If we try to run that exact example, which doesn't seem logically
flawed in any way:

>>> import logging
>>> FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
>>> logging.basicConfig(format=FORMAT)
>>> d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
>>> logging.warning("Protocol problem: %s", "connection reset",
extra=d)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/site-packages/logging/__init__.py",
line 1266, in warning
apply(root.warning, (msg,)+args, kwargs)
  File "/usr/lib/python2.5/site-packages/logging/__init__.py",
line 969, in warning
apply(self._log, (WARNING, msg, args), kwargs)
TypeError: _log() got an unexpected keyword argument 'extra'

I tried using **d instead, no show. I tried extra=d in Python 2.4, no
show. I tried **d in Python 2.4, no show.

So, my question unto the lot of you is: Do the docs for the logging
module lie to me?

URL: http://docs.python.org/lib/module-logging.html
--
http://mail.python.org/mailman/listinfo/python-list


Sequence iterators with __index__

2008-06-24 Thread schickb
I think it would be useful if iterators on sequences had the __index__
method so that they could be used to slice sequences. I was writing a
class and wanted to return a list iterator to callers.  I then wanted
to let callers slice from an iterator's position, but that isn't
supported without creating a custom iterator class.

Are there reasons for not supporting this generally? I realize not all
iterators would have the __index__ method, but that seems ok.

In Python 3, maybe this could be called a SequenceIterator

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


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread MRAB
On Jun 24, 7:59 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> On Tue, Jun 24, 2008 at 3:47 PM, [EMAIL PROTECTED]
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On 24 juin, 20:32, cirfu <[EMAIL PROTECTED]> wrote:
> >> if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> >> cant i write something like:
> >> if char in "[A-Za-z]":
>
> > Nope. But there are other solutions. Here are two:
>
> > # 1
> > import string
>
> > if char in string.letters:
> >   print "yay"
>
> > # 2
> > import re
> > exp = re.compile(r'[A-Za-z]')
>
> > if exp.match(char):
> >   print "yay"
>
> Let me post another one, and longer:
>
> if ord(somechar) in range(ord('A'), ord('Z') + 1) + range(ord('a'),
> ord('z') + 1):
>     ...
>
And another:

if 'A' <= somechar <= 'Z' or 'a' <= somechar <= 'z':
...
--
http://mail.python.org/mailman/listinfo/python-list


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread John Machin
On Jun 25, 4:32 am, cirfu <[EMAIL PROTECTED]> wrote:
> if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> cant i write something like:
> if char in "[A-Za-z]":

You can write that if you want to, but it's equivalent to
   if char in "zaZa]-[":
i.e. it doesn't do what you want.

This gives the same reuslt as your original code, unaffected by
locale:

if "A" <= char <= "Z" or "a" <= char <= "z":
--
http://mail.python.org/mailman/listinfo/python-list


Python libraries for log mining and event abstraction? (possibly OT)

2008-06-24 Thread felciano
Hi --

I am trying to do some event abstraction to mine a set of HTTP logs.
We have a pretty clean stateless architecture with user IDs that
allows us to understand what is retrieved on each session, and should
allow us to detect the higher-order user activity from the logs.
Ideally I'd love a python toolkit that has abstracted this out into a
basic set of API calls or even a query language.

An simple example is: find all instances of a search request, followed
by a 2+ search requests with additional words in the search string,
and group these into a higher-order "Iterative Search Refinement"
event (i.e. the user got too many search results to start with, and is
adding additional words to narrow down the results). So what I need is
the ability to select temporally-related events out of the event
stream (e.g. find searches by the same user within 10 second of each
other), further filter based on additional criteria across these event
(e.g. select only search events where there are additional search
criteria relative to the previous search), and a way to annotate, roll-
up or otherwise group matching patterns into a higher-level event.
Some of these patterns may require non-trivial criteria / logic not
supported by COTS log analytics, which is why I'm trying a toolkit
approach that allows customization.

I've been hunting around Google and the usual open source sites for
something like this and haven't found anything (in python or
otherwise). This is surprising to me, as I would think many people
would benefit from something like this, so maybe I'm just describing
the problem wrong or using the wrong keywords. I'm posting this to
this group because it feels somewhat AI-ish (temporal event
abstraction, etc) and that therefore pythonistas may have experience
with (there seems to be a reasonably high correlation there). Further,
if I can't find anything I'm going to have to build it myself, and it
will be in python, so any pointers on elegant design patterns for how
to do this using pythonic functional programming would be appreciated.
Barring anything else I will start from itertools and work from
there.

That said, I'm hoping to use an existing library rather than re-invent
the wheel. Any suggestions on where to look for something like this?

Thanks!

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


Re: The Importance of Terminology's Quality

2008-06-24 Thread John W Kennedy

David Combs wrote:

passing
*unnamed* functions as args (could Algol 60 also do something like that,
via something it maybe termed a "thunk")


No, the "thunks" were necessary at the machine-language level to 
/implement/ ALGOL 60, but they could not be expressed /in/ ALGOL.


--
John W. Kennedy
 "The first effect of not believing in God is to believe in anything"
  -- Emile Cammaerts, "The Laughing Prophet"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sequence iterators with __index__

2008-06-24 Thread Matimus
On Jun 24, 3:29 pm, schickb <[EMAIL PROTECTED]> wrote:
> I think it would be useful if iterators on sequences had the __index__
> method so that they could be used to slice sequences. I was writing a
> class and wanted to return a list iterator to callers.  I then wanted
> to let callers slice from an iterator's position, but that isn't
> supported without creating a custom iterator class.
>
> Are there reasons for not supporting this generally? I realize not all
> iterators would have the __index__ method, but that seems ok.
>
> In Python 3, maybe this could be called a SequenceIterator
>
> -Brad

Could you post an example of what you are talking about? I'm not
getting it. In any case, the first step is writing a PEP.
http://www.python.org/dev/peps/

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


Re: logging module's documentation lies?

2008-06-24 Thread Matimus
On Jun 24, 2:35 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Quote from the docs:
>
>     FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
>     logging.basicConfig(format=FORMAT)
>     d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
>     logging.warning("Protocol problem: %s", "connection reset",
> extra=d)
>
> would print something like
>
>     2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem:
> connection reset
>
> If we try to run that exact example, which doesn't seem logically
> flawed in any way:
>
>     >>> import logging
>     >>> FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
>     >>> logging.basicConfig(format=FORMAT)
>     >>> d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
>     >>> logging.warning("Protocol problem: %s", "connection reset",
> extra=d)
>     Traceback (most recent call last):
>       File "", line 1, in 
>       File "/usr/lib/python2.5/site-packages/logging/__init__.py",
> line 1266, in warning
>         apply(root.warning, (msg,)+args, kwargs)
>       File "/usr/lib/python2.5/site-packages/logging/__init__.py",
> line 969, in warning
>         apply(self._log, (WARNING, msg, args), kwargs)
>     TypeError: _log() got an unexpected keyword argument 'extra'
>
> I tried using **d instead, no show. I tried extra=d in Python 2.4, no
> show. I tried **d in Python 2.4, no show.
>
> So, my question unto the lot of you is: Do the docs for the logging
> module lie to me?
>
> URL:http://docs.python.org/lib/module-logging.html

>From the documentation: `Changed in version 2.5: extra was added.`

Documentation never lies, authors do. Or, in this case, don't.

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


Re: Passing arguments to subclasses

2008-06-24 Thread Michael Mabin
But if you couldn't find readily available confirmation of what you presumed
to be true, weren't the responses showing how you might come that answer
using the interpreter helpful, rather than harsh?
The Python interpreter is the shizzit.

On Mon, Jun 23, 2008 at 12:17 PM, John Dann <[EMAIL PROTECTED]> wrote:

> Thanks for the responses - they're much appreciated. And I understand
> the slight impatience with questions that could possibly be answered
> without recourse to a forum - I'm usually in the opposite position of
> fielding many newbie questions in a forum in a completely different
> field!
>
> But don't be too harsh on this category of questions for a couple of
> reasons. First, newbies don't necessarily yet have the same easy
> familiarity with the Python interpreter that's implied. - personally
> I'd be a little concerned as to whether any significant block of
> test/example code that I'd entered into the interpreter was actually
> addressing the exact question that I had in mind.
>
> And second, the answer might have been of the 'yes, but' kind. In
> other words, it might perhaps have been true in a certain sort of
> simple example, but one that failed to provide the complete picture.
> So sometimes it's reassuring to be able to get an authoritative
> answer.
>
> Thanks again for taking the time to answer.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
--
http://mail.python.org/mailman/listinfo/python-list

Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread s0suk3
On Jun 24, 5:36 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Jun 25, 4:32 am, cirfu <[EMAIL PROTECTED]> wrote:
>
> > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> > cant i write something like:
> > if char in "[A-Za-z]":
>
> You can write that if you want to, but it's equivalent to
>if char in "zaZa]-[":
> i.e. it doesn't do what you want.
>
> This gives the same reuslt as your original code, unaffected by
> locale:
>
> if "A" <= char <= "Z" or "a" <= char <= "z":

But doesn't that rely on the underlying character set? It's like
performing math on C char's (maybe that's what the interpreter does
internally?). If that's the case, using 'char.isalpha()' or 'char in
string.letters' or regex's would be better.

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


Re: Sequence iterators with __index__

2008-06-24 Thread schickb
On Jun 24, 3:45 pm, Matimus <[EMAIL PROTECTED]> wrote:
>
> > I think it would be useful if iterators on sequences had the __index__
> > method so that they could be used to slice sequences. I was writing a
> > class and wanted to return a list iterator to callers.  I then wanted
> > to let callers slice from an iterator's position, but that isn't
> > supported without creating a custom iterator class.
>
> Could you post an example of what you are talking about? I'm not
> getting it.

Interactive mock-up:

>>> a = ['x','y','z']
>>> it = iter(a)
>>> a[it:]
['x', 'y', 'z']
>>> it.next()
'x'
>>> a[it:]
['y', 'z']
>>> a[:it]
['x']
>>> it.next()
'y'
>>> a[it:]
['z']

This lets you use sequence iterators more general position indicators.
Currently if you want to track a position and slice from a tracked
position you must do it manually with an integer index. It's not
difficult, but given that sequence iterators already do that already
it seems redundant (and of course more error prone).


> In any case, the first step is writing a PEP.http://www.python.org/dev/peps/
>

Ok thanks, but I do want some idea of interest level before spending a
bunch of time on this.

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


Porn Addiction

2008-06-24 Thread Hughjar700
Help, I'm addicted to porn. I've been downloading porn online and
masturbating to it for a few years... Lately it's gotten even worse, I
spend hours and hours surfing and masturbating to it. It's taking over
my life and ruining everything.. I even missed days from work because
of this addiction.

I'm going to the porn as a way to avoid unwanted feelings or
procrastination and then it just takes over.

What can I do to end this horrible addiction?

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


Re: Porn Addiction

2008-06-24 Thread mikecdj
On Jun 24, 7:24 pm, [EMAIL PROTECTED] wrote:
> Help, I'm addicted to porn. I've been downloading porn online and
> masturbating to it for a few years... Lately it's gotten even worse, I
> spend hours and hours surfing and masturbating to it. It's taking over
> my life and ruining everything.. I even missed days from work because
> of this addiction.
>
> I'm going to the porn as a way to avoid unwanted feelings or
> procrastination and then it just takes over.
>
> What can I do to end this horrible addiction?
>
> -Hugh

Install a porn filter immediately.

This will block explicit sexual material from entering your computer.

Download the Optenet porn filter at http://www.optenetpc.com/

You can beat this thing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: shorten this: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":

2008-06-24 Thread John Machin
On Jun 25, 9:06 am, [EMAIL PROTECTED] wrote:
> On Jun 24, 5:36 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > On Jun 25, 4:32 am, cirfu <[EMAIL PROTECTED]> wrote:
>
> > > if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
>
> > > cant i write something like:
> > > if char in "[A-Za-z]":
>
> > You can write that if you want to, but it's equivalent to
> >if char in "zaZa]-[":
> > i.e. it doesn't do what you want.
>
> > This gives the same reuslt as your original code, unaffected by
> > locale:
>
> > if "A" <= char <= "Z" or "a" <= char <= "z":
>
> But doesn't that rely on the underlying character set?

Unless there is a Python implementation using EBCDIC, different
underlying character set that differs from ASCII in A..Z and a..z is
*not* a practical concern.

> It's like
> performing math on C char's (maybe that's what the interpreter does
> internally?). If that's the case, using 'char.isalpha()' or 'char in
> string.letters' or regex's would be better.

You should be asking the OP what he really wants ... precisely those
letters? alphabetic, in what locale?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sequence iterators with __index__

2008-06-24 Thread Terry Reedy



schickb wrote:

On Jun 24, 3:45 pm, Matimus <[EMAIL PROTECTED]> wrote:

I think it would be useful if iterators on sequences had the __index__
method so that they could be used to slice sequences. I was writing a
class and wanted to return a list iterator to callers.  I then wanted
to let callers slice from an iterator's position, but that isn't
supported without creating a custom iterator class.


Creating custom classes is what the class statement is for.  See below.


Could you post an example of what you are talking about? I'm not
getting it.


Interactive mock-up:


a = ['x','y','z']
it = iter(a)
a[it:]

['x', 'y', 'z']

it.next()

'x'

a[it:]

['y', 'z']

a[:it]

['x']

it.next()

'y'

a[it:]

['z']

This lets you use sequence iterators more general position indicators.
Currently if you want to track a position and slice from a tracked
position you must do it manually with an integer index. It's not
difficult, but given that sequence iterators already do that already
it seems redundant (and of course more error prone).


Python's iterator protocol is intentionally simple and general.
Wanting to slice while iterating is a *very* specialized usage.
In any case:
A. If the iterator uses in incrementing index to iterate, you want access.
B. Using an iterator as an integer will strike most people as 
conceptually bizarre; it will never be accepted.
C. Doing so is unnecessary since the internal index can just as easily 
be exposed as an integer attribute called 'index' or, more generally, 
'count'.

a[it.count:] looks *much* better.
D. You can easily add .index or .count to any iterator you write.  The 
iterator protocol is a minimum rather than maximum specification.
E. You can easily wrap any iterable/iterator in an iterator class that 
provides .count for *any* iteration process.  Slicing is not the only 
possible use of such an attribute.


class indexerator():
  def __inti__(self, iterable):
self.it = iter(iterable)
self.count = 0
  def __iter__(self): return self
  def __next__(self): # 3.0
tem = self.it.next()
self.count += 1
return tem

.count is always the number of items returned.  It is also the index of 
the next item to be returned if (but only if() the base iterable exists 
and is an indexable sequence.
F. Even this should be unnecessary for most usages.  Built-in function 
enumerate(iterable) generates count,item pairs in much the same manner:



In any case, the first step is writing a PEP.http://www.python.org/dev/peps/


Discussion usually comes first.


Ok thanks, but I do want some idea of interest level before spending a
bunch of time on this.


Even the developers sometimes take this precaution.  Many ideas never 
make it to the PEP stage.  I see no need for a change in Python here.


Terry Jan Reedy

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


how to convert '8868' to u'\u8868'

2008-06-24 Thread CodeHunter
a = '8868'
b = u'\u8868'

I want to convert a to b

who can help me ?

thank you very much!
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >