Problem using Optional pyparsing

2007-08-16 Thread Nathan Harmston
Hi,

I know this isnt the pyparsing list, but it doesnt seem like there is
one. I m trying to use pyparsing to parse a file however I cant get
the Optional keyword to work. My file generally looks like this:

ALIGNMENT  1020  YS2-10a02.q1k chr09 1295   42141045
142297   C1254 95.06 1295 reject_bad_break 0

or this:

ALIGNMENT  36YS2-10a08.q1k chrm  208  165 10745
10788   C  44 95.45 593 reject_low 10,14

and my grammar work well for these lines, however somethings the row looks like:
ALIGNMENT  53YS2-10b03.p1k chr12  180  125   1067465
1067520   C  56 98.21 532|5,2 reject_low 25

So I try to parse the 532 using

from pyparsing import *

integer = Word( nums )
float = Word( nums+".")
identifier = Word( alphanums+"-_." )

alignment = Literal("ALIGNMENT ").suppress()
row_1 = integer.setResultsName("row_1")#.setParseAction(make_int)
src_id = identifier.setResultsName("src_id")
dest_id = identifier.setResultsName("dest_id")
src_start = integer.setResultsName("src_start")#.setParseAction(make_int)
src_stop = integer.setResultsName("src_stop")#.setParseAction(make_int)
dest_start = integer.setResultsName("dest_start")#.setParseAction(make_int)
dest_stop = integer.setResultsName("dest_stop")#.setParseAction(make_int)
row_8 = oneOf("F C").setResultsName("row_8")
length = integer.setResultsName("length")#.setParseAction(make_int)
percent_id = float.setResultsName("percent_id")#.setParseAction(make_float)
row_11 = integer + Optional(Literal("|") + commaSeparatedList )
)#.setResultsName("row_11")#.setParseAction(make_int)
result = Word(alphas+"_").setResultsName("result")
row_13 = commaSeparatedList.setResultsName("row_13")

def make_alilines_status_parser():
return alignment + row_1 + src_id + dest_id + src_start + src_stop
+ dest_start + dest_stop + row_8 + length + percent_id + row_11 +
result + row_13

def parse_alilines_status(ifile):
alilines = make_alilines_status_parser()
for l in ifile:
yield alilines.parseString( l )

However my parser always fails on lines of type 3. Does anyone know
why the Optional part is not working.

Many Thanks in advance

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


Re: threads, mutual exclusion, and lists

2007-08-16 Thread Martin v. Löwis
>> My question is -- are python list operations atomic? If they are not,
>> then I assume I need to put some mutual exclusion around the append()
>> and pop() calls ?
> 
> They are not, but there is one included in the standard library:
> http://docs.python.org/dev/lib/module-Queue.html

Why do you think they are not?

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


Re: ElementTree surprise

2007-08-16 Thread Stefan Behnel
Paul Rubin wrote:
> Torsten Bronger <[EMAIL PROTECTED]> writes:
>>> 
>> Technically, text is nodes as all other element nodes.  In the
>> parrot example, there is no empty textnode but no textnode at all.
> 
> That is required by the xml standard?  If yes, elementtree is doing
> the right thing, but it surprises me, I would have expected an empty
> string.  Thanks.

The XML standard defines both as being equivalent, so any XML parser would
handle them exactly the same. Also, as most XML parsers have a SAX(-like)
interface, which always generates events in the "" form, there is
not even a way for applications or libraries to distinguish between the two.

So it's not even an ElementTree thing. ET just doesn't know what exactly was
in the original XML byte stream. A very simple way to make sure you always get
a string back is

>>> text = element.text or ""

BTW, you'd be even more surprised to see that ET can actually /store/ "" as
text if you tell it to, and then returns an empty string when you ask for the
.text property. But any empty text coming from the parser will always be None.

Oh, and lxml.etree behaves exactly the same as ElementTree here. :)

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


twisted.web's xmlrpc with digest authencitation

2007-08-16 Thread exhuma.twn
I recently found a link[1] which demonstrates how to secure a xml-rpc
service with basic HTTP-auth. But this get's send in clear-text over
the net. There's also the HTTP-Digest auth mechanism which is
apparently supported as well by twisted[2].

How do I secure an xml-rpc service using digest-auth then?
If this works, all my troubles are suddenly gon and I am sold for
twisted ;)

[1]: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/526625
[2]: http://twistedmatrix.com/trac/ticket/1475

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


Re: ElementTree surprise

2007-08-16 Thread Paul Rubin
Stefan Behnel <[EMAIL PROTECTED]> writes:
> So it's not even an ElementTree thing. ET just doesn't know what
> exactly was in the original XML byte stream. A very simple way to
> make sure you always get a string back is
> >>> text = element.text or ""

Thanks, I ended up doing something like that.  What I wondered about
the standard was whether it specified that parrot had no text node,
as opposed to having an empty text node.  I guess it doesn't matter,
it just caught me by surprise.
-- 
http://mail.python.org/mailman/listinfo/python-list


python socket usage

2007-08-16 Thread Oğuz Yarımtepe

Is it possible to send a data object like a tuple or a list in socket 
programming? If so how? It seems with socket module it is only possible to 
send strings. 


-- 
Oğuz Yarımtepe
http://www.yarimtepe.com/en
-- 
http://mail.python.org/mailman/listinfo/python-list

ploting issues in program

2007-08-16 Thread yadin
hi every one!

can you please help me to fix these polar plot in db's
so that the center is at the minimun negative number in voltagedb
about [-50]
and the maximun is at zero and how can i see values on the axis like
showing that the axes start at -50 -40 -30 .and end at zero
than you
 here is the program
import wx
import os
from wx.lib.colourdb import *
from pylab import*
angteta =  [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001,
9.46841119e-001,
 1.26100038e+000, 1.57515965e+000, 1.88931892e+000,
2.20347818e+000,
 2.51763745e+000, 2.83179671e+000, 3.14595598e+000,
3.46011524e+000,
 3.77427451e+000, 4.08843377e+000, 4.40259304e+000,
4.71675230e+000,
 5.03091157e+000, 5.34507083e+000, 5.65923010e+000,
5.97338936e+000,]

voltage =  [ 0.00363471, 0.26569155, 0.52562334, 0.76330428,
0.93673361, 1.,
 0.93321713, 0.75733232, 0.5185449 , 0.25840091,
0.00363471, 0.26569155,
 0.52562334, 0.76330428, 0.93673361, 1.,
0.93321713, 0.75733232,
 0.5185449 , 0.25840091,]

#voltagedb = 20*log10(voltage)

voltagedb =  [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603,
-0.56767793,  0.,
  -0.60034598, -2.41427014,
-5.7042726 ,-11.75411924,-48.7906044 ,
  -11.51244516, -5.58650713, -2.34604603, -0.56767793,
0.,
  -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,]
polar(angteta,voltagedb)

show()

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


Re: python socket usage

2007-08-16 Thread markacy
On 16 Sie, 09:42, O uz Yar mtepe <[EMAIL PROTECTED]> wrote:
> Is it possible to send a data object like a tuple or a list in socket
> programming? If so how? It seems with socket module it is only possible to
> send strings.
>
> --
> O uz Yar mtepehttp://www.yarimtepe.com/en

Hi Oguz,

   why don't you make a string out of your tuple, or list, send it via
socket and make a tuple/list again?

>>> x = (1,2,3,4,5,6,7,)
>>> type(x)

>>> y = str(x)
>>> type(y)

>>> print y
(1, 2, 3, 4, 5, 6, 7)
>>> z = tuple(y)
>>> type(z)

>>>

Cheers,
Marek

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


Re: Problem using Optional pyparsing

2007-08-16 Thread Peter Otten
Nathan Harmston wrote:

> I know this isnt the pyparsing list, but it doesnt seem like there is
> one. I m trying to use pyparsing to parse a file however I cant get
> the Optional keyword to work. My file generally looks like this:
> 
> ALIGNMENT  1020  YS2-10a02.q1k chr09     1295       42    141045
> 142297   C    1254 95.06 1295 reject_bad_break 0
> 
> or this:
> 
> ALIGNMENT  36    YS2-10a08.q1k chrm      208      165     10745
> 10788   C      44 95.45 593 reject_low 10,14
> 
> and my grammar work well for these lines, however somethings the row looks
like:
> ALIGNMENT  53    YS2-10b03.p1k chr12      180      125   1067465
> 1067520   C      56 98.21 532|5,2 reject_low 25
> 
> So I try to parse the 532 using
> 
> from pyparsing import *
> 
> integer = Word( nums )
> float = Word( nums+".")
> identifier = Word( alphanums+"-_." )
> 
> alignment = Literal("ALIGNMENT ").suppress()
> row_1 = integer.setResultsName("row_1")#.setParseAction(make_int)
> src_id = identifier.setResultsName("src_id")
> dest_id = identifier.setResultsName("dest_id")
> src_start = integer.setResultsName("src_start")#.setParseAction(make_int)
> src_stop = integer.setResultsName("src_stop")#.setParseAction(make_int)
> dest_start =
integer.setResultsName("dest_start")#.setParseAction(make_int)
> dest_stop = integer.setResultsName("dest_stop")#.setParseAction(make_int)
> row_8 = oneOf("F C").setResultsName("row_8")
> length = integer.setResultsName("length")#.setParseAction(make_int)
> percent_id =
float.setResultsName("percent_id")#.setParseAction(make_float)
> row_11 = integer + Optional(Literal("|") + commaSeparatedList )
> )#.setResultsName("row_11")#.setParseAction(make_int)
> result = Word(alphas+"_").setResultsName("result")
> row_13 = commaSeparatedList.setResultsName("row_13")
> 
> def make_alilines_status_parser():
>     return alignment + row_1 + src_id + dest_id + src_start + src_stop
> + dest_start + dest_stop + row_8 + length + percent_id + row_11 +
> result + row_13
> 
> def parse_alilines_status(ifile):
>     alilines = make_alilines_status_parser()
>     for l in ifile:
>         yield alilines.parseString( l )
> 
> However my parser always fails on lines of type 3. Does anyone know
> why the Optional part is not working.

The commaSeparatedList includes the rest of the line into its last item:

>>> commaSeparatedList.parseString("a,bc")
(['a', 'bc'], {})

You can fix this by defining your own delimitedList that doesnt accept
whitespace, e. g.:

>>> delimitedList(Word(alphanums)).parseString("a,b c")
(['a', 'b'], {})

Peter

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


Re: ploting issues in program

2007-08-16 Thread Peter Otten
yadin wrote:

> can you please help me to fix these polar plot in db's
> so that the center is at the minimun negative number in voltagedb
> about [-50]
> and the maximun is at zero and how can i see values on the axis like
> showing that the axes start at -50 -40 -30 .and end at zero

You posted this question several times now and got no response that you
liked enough to abstain from reposting.

Now your options are:

- Try another forum (the matplotlib mailing list would be a good candidate)
- Show some initiative: add 50 to the dB values and be done

>  here is the program

[...]

> voltagedb =  [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603,
> -0.56767793,  0.,
>   -0.60034598, -2.41427014,
> -5.7042726 ,-11.75411924,-48.7906044 ,
>   -11.51244516, -5.58650713, -2.34604603, -0.56767793,
> 0.,
>   -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,]

voltagedb = [v+50 for v in voltagedb]

> polar(angteta,voltagedb)
> 
> show()

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


Re: python socket usage

2007-08-16 Thread Paul Rubin
O¿uz YarÑmtepe <[EMAIL PROTECTED]> writes:
> Is it possible to send a data object like a tuple or a list in socket 
> programming? If so how? It seems with socket module it is only possible to 
> send strings. 

Look into something like pyro or JSON.  Whatever you do, don't use eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who told str() to round my int()'s!!!

2007-08-16 Thread baby's happy
I saw your article is very good, I like it very much. I will continue
to pay attention to your article, the following are the points I hope
that I have similar concerns.
http://www.game-win.com http://www.game-win.com/wow-powerleveling.html
http://www.game-win.com/faq.html http://www.game-win.com/power-leveling.html
http://www.game-win.com/World-of-Warcraft-power-leveling.html
http://www.game-win.com/about.html 
http://www.paper-cup-machine.com/cn/index.html
http://www.sinceremachine.com http://www.clickra.com
http://www.clickra.com/NewsList_2.htm http://www.east163.com
http://www.ruian2machine.cn http://www.rajayj.cn http://www.mycvcv.com
http://www.dgajm.com http://www.icansee.cn http://www.icansee.cn/chanpin.htm
http://www.icansee.cn/8.htm http://www.pjwsdyb.com http://www.shdyf.com
http://www.shdyf.com/nbdy.htm http://www.nonwoven-bags.cn

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


Re: python socket usage

2007-08-16 Thread Gary Herron
markacy wrote:
> On 16 Sie, 09:42, O uz Yar mtepe <[EMAIL PROTECTED]> wrote:
>   
>> Is it possible to send a data object like a tuple or a list in socket
>> programming? If so how? It seems with socket module it is only possible to
>> send strings.
>>
>> --
>> O uz Yar mtepehttp://www.yarimtepe.com/en
>> 
>
> Hi Oguz,
>
>why don't you make a string out of your tuple, or list, send it via
> socket and make a tuple/list again?
>
>   
 x = (1,2,3,4,5,6,7,)
 type(x)
 
> 
>   
 y = str(x)
 type(y)
 
> 
>   
 print y
 
> (1, 2, 3, 4, 5, 6, 7)
>   
 z = tuple(y)
 type(z)
 
> 
>   
Sure it's a tuple, but did you look at it?  Turning a sequence (which is
what a string is after all) into a tuple is an easy operation, but it's
surely not what you want here.

>>> x = (1,2,3,4,5,6,7)
>>> s = str(x)
>>> t = tuple(s)
>>> t
('(', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5',
',', ' ', '6', ',', ' ', '7', ')')

If you want to turn a string representation of an object back into an
object, you must eval the string. 
Moreover, if the tuple contains things other than simple integers (float
of strings of whatever) the string represtnataion of the object may not
be able to recover the original object accurately.  Worse yet, an eval
of an arbitrary string is a HUGE security hole.

If you really want to send any Python object through a socket, look up
the Pickle and cPickle modules.  These will marshal (as it's called) any
Python object of any type and complexity into a byte string which can be
sent across a socket.  On the receiving end of the socket, the byte
string can be turned back into an equivalent Python object.

Gary Herron



>
> Cheers,
> Marek
>
>   

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


Changing button preferences after beeing pressed

2007-08-16 Thread thomas . lidebrandt
Hello

I'm using wxPython to consruct a GUI and want to change a button label
and event handler to change after the button have been pressed. The
only thing I can think of is a global variable that contrls the state
of the program and constructs the button in accordance to the defined
state. Is there a better solution to this problem?

/Thomas

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


about: informtion computer...

2007-08-16 Thread angga_cute
To All Members :

I have some information for you

I would like you to invite to visiting my web, may be you need some
information about newest information about computer, laptop, and than
printer. I have little bit information on my web http://www.komputer -
djogja.blogspot .com/  and http://www.notebook stor.blogspot. com/

I hope my web can give you alot of information. ..

Thanks for you attention...


regards

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


Re: python socket usage

2007-08-16 Thread Paul Rubin
Gary Herron <[EMAIL PROTECTED]> writes:
> be able to recover the original object accurately.  Worse yet, an eval
> of an arbitrary string is a HUGE security hole.
> 
> If you really want to send any Python object through a socket, look up
> the Pickle and cPickle modules.

These are also security holes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python socket usage

2007-08-16 Thread Oğuz Yarımtepe
On Thursday 16 August 2007 11:20:38 Gary Herron wrote:
> If you really want to send any Python object through a socket, look up
> the Pickle and cPickle modules.  These will marshal (as it's called) any
> Python object of any type and complexity into a byte string which can be
> sent across a socket.  On the receiving end of the socket, the byte
> string can be turned back into an equivalent Python object.
>
> Gary Herron

As i read pickle module is Python-spesific. I need to talk with a Java 
application and get the infortion that it will send. What i do right now is 
listening a socket and reding the string that is sent by the java 
application. So the java application is sending a string and i am reading and 
parsing it and getting the related infortion i need. A more professional way 
may be the reading the object itself. Is it possible to get the array for ex. 
object that is sent from the Java application with sockets?

-- 
Oğuz Yarımtepe
http://www.yarimtepe.com/en
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Combinatorial of elements in Python?

2007-08-16 Thread Mikael Olofsson
Sebastian Bassi wrote:
> On 8/15/07, Mikael Olofsson <[EMAIL PROTECTED]> wrote:
>   
>> What is unclear here is in what order the keys should be visited. The
>> following assumes that the keys should be considered in alphanumeric order.
>> 
>
> Yes, my fault. The orden should be given by a string, like:
>
> DCDBA
> Using this dictionay.
> A={'A':['1','2'],'B':['4','5'],'C':['6','7','8'],'D':['9']}
>
> Should return:
>
> '96941'
> '97941'
> '97942'
> '96942'
> '98941'
> '98942'
> '96951'
> '97951'
> '97952'
> '96952'
> '98951'
> '98952'

OK, seems like you need to add a second argument to the function 
specifying this order. I leave that to you.

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


Re: Changing button preferences after beeing pressed

2007-08-16 Thread Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:
> I'm using wxPython to consruct a GUI and want to change a button
> label 

=> wx.Button.SetLabel (also have a look at the button examples)

> and event handler to change after the button have been 
> pressed. 

I'm not sure if those bindings can easily be changed at runtime.
Another solution is creating two buttons and only show one at a
time.

> The only thing I can think of is a global variable that 
> contrls the state of the program and constructs the button in
> accordance to the defined state. 

Better keep the state as frame attribute and use a frame method to
change it.

Regards,


Björn

-- 
BOFH excuse #61:

not approved by the FCC

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


clarification

2007-08-16 Thread Beema shafreen
hi every body,
i have compared two files:
code:

fh = open('HPRD_MAIN_20.txt','r')
for line in fh.readlines():
data = line.strip().split('#')
fh1 = open('NOMENCLATURE_MAIN_20.txt','r')
for line1 in fh1.readlines():
data1 = line1.strip().split('#')
if  data1[0] == data[0]:
result = data[0] +'#'+data[3]+'|'+
data[4]+'|'+data[9]+'|'+ data1[3]
print result
the result was as given below:


00017#ACTG1|actin, gamma 1|Actin gamma 1|ACTG
00017#ACTG1|actin, gamma 1|Actin gamma 1|Actin gamma
00017#ACTG1|actin, gamma 1|Actin gamma 1|Cytoskeletal gamma actin


but i need the result to be like this :


00017#ACTG1|actin, gamma 1|Actin gamma 1|ACTG,Actin gamma,Cytoskeletal
gamma, actin


with out redundancy and the name in the same line separated by commas..
please suggest what should i do for this to get the result like this.


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

Re: Coroutines and argument tupling

2007-08-16 Thread Bjoern Schliessmann
Marshall T. Vandegrift wrote:
> Without the decorator that becomes:
> 
> gen = nextn(2)
> print gen.next()  # => [0, 1]
> print gen.send(3) # => [2, 3, 4]
> print gen.send(1) # => [5]
> 
> The former is just that smidgen nicer, and allows you to continue
> to make use of argument defaults and varadic arguments if so
> desired.

The solution I'd use is a decorator that calls next automatically
one time after instantiation. Then you can use send normally, and
don't have to care about any initial parameters, which makes the
code clearer (initial parameters should be used for setup purposes,
but not for the first iteration, IMHO). It'd look like this (from
PEP 342, http://www.python.org/dev/peps/pep-0342/):

def consumer(func):
def wrapper(*args,**kw):
gen = func(*args, **kw)
gen.next()
return gen
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__  = func.__doc__
return wrapper

@consumer
def nextn():
...

gen = nextn()
print gen.send(2) # => [0, 1]
print gen.send(3) # => [2, 3, 4]
print gen.send(1) # => [5]

Regards,


Björn

-- 
BOFH excuse #60:

system has been recalled

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


Re: python socket usage

2007-08-16 Thread Gary Herron
Oğuz Yarımtepe wrote:
> On Thursday 16 August 2007 11:20:38 Gary Herron wrote:
>   
>> If you really want to send any Python object through a socket, look up
>> the Pickle and cPickle modules.  These will marshal (as it's called) any
>> Python object of any type and complexity into a byte string which can be
>> sent across a socket.  On the receiving end of the socket, the byte
>> string can be turned back into an equivalent Python object.
>>
>> Gary Herron
>> 
>
> As i read pickle module is Python-spesific. I need to talk with a Java 
> application and get the infortion that it will send. What i do right now is 
> listening a socket and reding the string that is sent by the java 
> application. So the java application is sending a string and i am reading and 
> parsing it and getting the related infortion i need. A more professional way 
> may be the reading the object itself. Is it possible to get the array for ex. 
> object that is sent from the Java application with sockets?
>
>   
Then consider XMLRPC.  It is a language/platform independent way of
making a call to a remote procedure (with parameters).   Your Python
program would implement a XMLRPC server listening for calls to a single
procedure, and your Java program would make a connection to the XMLRPC
server and make a call to the procedure.

The XMLRPC package in JAVA (don't know what it's called, but it's gotta
exist) will package up the procedure being called and its parameters as
an XML document, and  send it to the server.  The  Python  XMLRPC server
package will decipher the XML document, extracting the procedure name
and its arguments, make the call, and package up any return value (again
as an XML document) and send it back on the socket.  The calling JAVA
program will receive the return value, just as in any normal procedure
call, and continue on it's merry way.

The XMLRPC protocol can only pass simple arguments, and (I think) arrays
of simple arguments.   But that's sufficient for a tuple of integers as
you had in your example.

Hope that helps,
Gary Herron

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

Re: Hijack! Different book: (was: Opinions about this new Python book?

2007-08-16 Thread Paul Boddie
On 15 Aug, 19:52, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
> Hopefully it isn't quite as annoying as some of what I've found in
> the Turbogears book that recently arrived from Amazon. (Rapid Web
> Applications with TurboGears)

Is this the book that came out before TurboGears even reached 1.0,
probably having diminished relevance now that there are 1.1 and 2.0
releases being worked on? I'm very much in favour of book
availability, and I pity the people writing Python books given
continuous changes to the language and the associated recommended
development practices as new features go in, but tracking a target
prior to any kind of stable release seems a bit too ambitious,
especially for a book in print.

Paul

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


Re: ploting issues in program

2007-08-16 Thread Steve Holden
Peter Otten wrote:
> yadin wrote:
> 
>> can you please help me to fix these polar plot in db's
>> so that the center is at the minimun negative number in voltagedb
>> about [-50]
>> and the maximun is at zero and how can i see values on the axis like
>> showing that the axes start at -50 -40 -30 .and end at zero
> 
> You posted this question several times now and got no response that you
> liked enough to abstain from reposting.
> 
> Now your options are:
> 
> - Try another forum (the matplotlib mailing list would be a good candidate)
> - Show some initiative: add 50 to the dB values and be done
> 
>>  here is the program
> 
> [...]
> 
>> voltagedb =  [-48.7906044 ,-11.51244516, -5.58650713, -2.34604603,
>> -0.56767793,  0.,
>>   -0.60034598, -2.41427014,
>> -5.7042726 ,-11.75411924,-48.7906044 ,
>>   -11.51244516, -5.58650713, -2.34604603, -0.56767793,
>> 0.,
>>   -0.60034598, -2.41427014, -5.7042726 ,-11.75411924,]
> 
> voltagedb = [v+50 for v in voltagedb]
> 
>> polar(angteta,voltagedb)
>>
>> show()
> 
The better the advice the worse it's wasted ...

I might ask just exactly what is being plotted to give those answers. It 
sounds like field strength, but I am having difficulty envisaging a 
field that is weakest at its center - is this some sort of alternative 
universe you are plotting :-) ?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Coroutines and argument tupling

2007-08-16 Thread Marshall T. Vandegrift
Bjoern Schliessmann <[EMAIL PROTECTED]> writes:

> The solution I'd use is a decorator that calls next automatically one
> time after instantiation. Then you can use send normally, and don't
> have to care about any initial parameters, which makes the code
> clearer (initial parameters should be used for setup purposes, but not
> for the first iteration, IMHO). It'd look like this (from PEP 342,
> http://www.python.org/dev/peps/pep-0342/):

I'd seen the consumer decorator, and it certainly is cleaner than just
using a generator.  I don't like how it hides the parameter signature in
the middle of the consumer function though, and it also doesn't provide
for argument default values.  It's the difference between:

...
def __init__(self, ...):
...
self.consumer = self._function(value)
...

def function(self, first, second=3, *args, **kwargs):
self.consumer.send((first, second, args, kwargs))

@consumer
def _function(self, setup):
...
first, second, args, kwargs = yield # initial 'next'
while condition:
...
first, second, args, kwargs = yield retval

Versus just:

@coroutine
def function(self, first, second=3, *args, **kwargs):
...
while condition:
...
first, second, args, kwargs = yield retval

Thanks in any case for the replies!  Since I've apparently decided my
ArgPacker is worth it, the complete code for my coroutine decorator
follows.

-Marshall


import inspect
import types
import functools
from itertools import izip

__all__ = [ 'coroutine' ]

class ArgPacker(object):
def __init__(self, function):
args, varargs, varkw, defaults = inspect.getargspec(function)
self.args = args or []
self.varargs = (varargs is not None) and 1 or 0
self.varkw = (varkw is not None) and 1 or 0
self.nargs = len(self.args) + self.varargs + self.varkw
defaults = defaults or []
defargs = self.args[len(self.args) - len(defaults):]
self.defaults = dict([(k, v) for k, v in izip(defargs, defaults)])

def pack(self, *args, **kwargs):
args = list(args)
result = [None] * self.nargs
for i, arg in izip(xrange(len(self.args)), self.args):
if args:
result[i] = args.pop(0)
elif arg in kwargs:
result[i] = kwargs[arg]
del kwargs[arg]
elif arg in self.defaults:
result[i] = self.defaults[arg]
else:
return None
if self.varargs:
result[len(self.args)] = args
elif args:
return None
if self.varkw:
result[-1] = kwargs
elif kwargs:
return None
return tuple(result)

class coroutine(object):
"""Convert a function to be a simple coroutine.

A simple coroutine is a generator bound to act as much as possible like a
normal function.  Callers call the function as usual while the coroutine
produces new return values and receives new arguments with `yield'.
"""
def __init__(self, function):
self.function = function
self.gname = ''.join(['__', function.__name__, '_generator'])
self.packer = ArgPacker(function)
coroutine = self
def method(self, *args, **kwargs):
return coroutine.generate(self, self, *args, **kwargs)
self.method = method
functools.update_wrapper(self, function)
functools.update_wrapper(method, function)

def __get__(self, obj, objtype=None):
return types.MethodType(self.method, obj, objtype)

def __call__(self, *args, **kwargs):
return self.generate(self, *args, **kwargs)

def generate(self, obj, *args, **kwargs):
try:
generator = getattr(obj, self.gname)
except AttributeError:
generator = self.function(*args, **kwargs)
setattr(obj, self.gname, generator)
retval = generator.next()
else:
packed = self.packer.pack(*args, **kwargs)
if packed is None:
self.function(*args, **kwargs) # Should raise TypeError
raise RuntimeError("ArgPacker reported spurious error")
retval = generator.send(packed)
return retval

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


Re: Changing button preferences after beeing pressed

2007-08-16 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hello
> 
> I'm using wxPython to consruct a GUI and want to change a button label
> and event handler to change after the button have been pressed. The
> only thing I can think of is a global variable that contrls the state
> of the program and constructs the button in accordance to the defined
> state. Is there a better solution to this problem?
> 
It would be difficult to think of a worse one! ;-)

Since the button is probably in some sort of window, you should at least 
be saving the state as an instance variable of the window. The event 
handler should start with an "if" statement that calls one or other of 
the routines you have in mind depending on state. Here's a button 
event-handlerI use in a time recording program:

 def OnPauseRestart(self, event):
 """Stops/restarts the clock: allows for non-recordable 
activities."""
 if self.Running:
 self.stopTimer()
 else:
 self.startTimer()

 def startTimer(self):
 """Starts the timer and returns the time to black."""
 if not self.currentTask:
 msg("Please select a task before starting the timer", 
caption="No current task")
 return
 self.timer.Start(1000)
 self.Time().SetForegroundColour(wx.BLACK)
 self.Time().Refresh()
 self.Pause().SetLabel("&Pause")
 self.Running = 1

 def stopTimer(self):
 """Stops the timer and sets the time red - you are not 
chargeable!"""
 self.timer.Stop()
 self.Time().SetForegroundColour(wx.RED)
 self.Time().Refresh()
 self.Pause().SetLabel("&Resume")
 self.Running = 0

Hope this helps.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Layer 2 socket connection

2007-08-16 Thread [EMAIL PROTECTED]
On Aug 15, 7:21 pm, alisonken1 <[EMAIL PROTECTED]> wrote:
> Hello all -
>
> I'm looking at trying to write a python script to connect to a layer 2
> bridge (no IP available).
>
> Looking at the sockets function, it's not clear if I can connect using
> only the mac address - it appears to want either a broadcast address
> or a specific IP address.
>
> Can anyone give me a clue on opening a layer 2 socket in Python?

I use impacket for stuff like that, see 
http://oss.coresecurity.com/projects/impacket.html

Cheers

Rich.

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


ctypes and C99 complex numbers

2007-08-16 Thread Eugen Wintersberger
Hi there
 I want to use ctypes in connection with C functions that use complex
datatypes defined in the C99 standard. Does someone know a simple way
how to implement this? Are there any plans to integrate the C99 complex
data types in the ctypes module?

best regards 
  Eugen Wintersberger
-- 

|  |
| Dipl. Ing. Eugen Wintersberger   |
| Department of semicondutor physics   |
| University of Linz   |
| Altenbergerstrasse 69|
| A-4040 Linz  |
| Austria  |
|  |
| Mobile.: +43 664 3112861 |
| Tel.: +43 732 2468 9605  |
| E-Mail.: [EMAIL PROTECTED]  |
| Skype: eugen20056221 |
| ICQ: 214418739, nickname: thot   |
|  |


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


Re: Hijack! Different book: (was: Opinions about this new Python book?

2007-08-16 Thread Carsten Haese
On Thu, 2007-08-16 at 04:21 -0700, Paul Boddie wrote:
> [...] I pity the people writing Python books given
> continuous changes to the language and the associated recommended
> development practices as new features go in, but tracking a target
> prior to any kind of stable release seems a bit too ambitious,
> especially for a book in print.

The book was co-authored by Kevin Dangoor, who is the principal
developer of TurboGears. He probably had a pretty good idea of what the
stable release was going to look like.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: "Variable variable name" or "variable lvalue"

2007-08-16 Thread mfglinux
The solution with the dictionary worked perfectlly well, my script is
running and even produces data with sense!!!

Thank you very much indeed to all of you answering. Cheers!

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


Re: Coroutines and argument tupling

2007-08-16 Thread Bjoern Schliessmann
Marshall T. Vandegrift wrote:

> I'd seen the consumer decorator, and it certainly is cleaner than
> just using a generator.  I don't like how it hides the parameter
> signature in the middle of the consumer function though, and it
> also doesn't provide for argument default values.  

Mh, that may be. :( I didn't use it much yet.
 
> Thanks in any case for the replies!  Since I've apparently decided
> my ArgPacker is worth it, the complete code for my coroutine
> decorator follows.

Thanks for reporting back, and happy coding.

Regards,


Björn

-- 
BOFH excuse #198:

Post-it Note Sludge leaked into the monitor.

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


Localizing numbers in python

2007-08-16 Thread Heba Farouk
Hello 
i would like to localize numbers in python according to the current selected 
language of the web page (English, french, arabic, ...), is there any options 
in python??

thanks in advance


Yours 

Heba

   
-
Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, 
photos & more. -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Book Recommendations

2007-08-16 Thread 55rebels
On Aug 15, 11:47 pm, Laurent Pointal <[EMAIL PROTECTED]> wrote:
> Azazello a écrit :
>
>
>
> > On Aug 15, 7:47 am, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> >> If I could have only one book, I would buy "Core Python, Second
> >> Edition," by Wesley Chun.
>
> >> For the record, I own:
> >> Core Python, Second Edition (great)
> >> wxPython in Action (haven't used yet)
> >> Beginning Python (barely used)
> >> Python in a Nutshell (use as a reference, although interactive python
> >> dir() is more useful)
> >> Dive into Python (great book)
> >> Python Cookbook (great book)
> >> Python Pocket Reference (not very useful)
> >> Python Phrasebook (I love the Phrasebook series, but this isn't a
> >> necessary book)
>
> > I would like to add:
>
> > Foundations of Python Network Programming
>
> There was a review about this one on 
> slashdot:http://books.slashdot.org/books/04/10/13/1815209.shtml?amp;tid=192&am...
>
>
>
> > I also use the Python Essential Reference.  (although all of the
> > information is probably online it's nice to have a solid paper
> > reference)

Byte of python - online book.
Best I've seen yet, online anyway. Especially great for newbies...
like me.
Wish I could buy a hard copy.

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

Re: (Re)announcing APL 2007

2007-08-16 Thread glarocque
On Aug 10, 12:40 pm, [EMAIL PROTECTED] wrote:
> On Aug 6, 9:20 am, Paul Mansour <[EMAIL PROTECTED]> wrote:
>
> > APL2007 Roll Call: Is anyone going to this?
>
> > I'm thinking about going, but I don't want to the only one to show up,
> > as in San Diego.
>
> Here here.
>
> Sorry to mention the elephant in the room, but this discussion begs
> the obvious question:  what is the rationale for putting on this
> conference?  Perhaps I missed that discussion, and if so, please
> excuse me.
>
> As we know, there are already two well-attended APL vendor conferences
> in the world each year, plus several other more local gatherings.
>
> Speaking as an APL consultant and product distributor, this puts
> people in a tough spot, since we now have at least three events to
> consider travelling to and attending (assuming APL2000 is hosting its
> usual Florida event this year?).
>
> I suppose I should be happy for another opportunity to meet and
> network with potential APL colleagues and customers, but if it's
> mainly the same small audience at each event, the costs are hard to
> justify more than once per year.
>
> I don't have any answers to this dilemma yet, but I think it requires
> a lot more discussion. Just putting on a conference and hoping people
> attend may, at this point I think, be somewhat counterproductive.
>
> ...richard

Richard,

In your comments you were concerned by the fact that the rationale for
APL2007 was not clear. You also mentioned that there was some sort of
a conflict with two APL vendor conferences. When the decision was made
to hold a conference in the fall of 2007, the members of the steering
committee were well aware that there was a potential conflict with APL
vendor workshops. However, we had a discussion about this issue and
finally concluded that it was a good idea to go ahead with APL2007 for
two reasons. First, the idea to hold APL2007 is to have users of
different Array Programming Languages (including APL, J, K, NIAL and
other related languages) attend the conference. SIGAPL, in addition to
fostering the discussion between array programming languages
themselves, aims to promote the array processing paradigm and its
richness in contrast to the scalar one. It is SIGAPL's vision to serve
as a counterpoint in the programming community by facilitating
communications among researchers, developers and users of Array
Programming Languages. APL2007 will be an excellent opportunity to
promote our core values in the mainstream programming community
through our conference agenda, tutorials and discussion panels. This
will benefit APL and all Array Programming Languages. Second, there
was an opportunity to meet jointly with OOPSLA. Thus, APL2007
attendees will have the opportunity to spend a few more days and
attend other presentations on object oriented programming. As far as
APL is concerned, there has been development in object oriented
programming in some APL versions. I am confident that all the APL
vendors and many APL consultants and users will attend the conference,
along with researchers, consultants or users of Array Programming
Languages. So, I am looking forward to meeting you at APL2007.

Guy Larocque
SIGAPL Chairman

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


Re: Python Book Recommendations

2007-08-16 Thread Shawn Milochik
I should add that "Dive Into Python" is also available for free online:

http://www.diveintopython.org/

It's a great book. It is not a linear book -- it doesn't start you off
talking about variable types and structure. It starts you right off
with a piece of working code. If you already have some programming
experience, it's actually a refreshing change from all the others
which basically waste 50 - 100 pages on stuff you already know.
-- 
http://mail.python.org/mailman/listinfo/python-list


How do you guys convert a tuple into a Set in ABAQUS?

2007-08-16 Thread Baisong Du
A function is defined to get a tuple. 

def searchObjectByRange(partObject, objectType, xRange, yRange, zRange): 
"""In the partObject, search objects (edge, face, etc.) within the 
given region""" 
TOLERANCE_GLOBAL = 1.0E-6 
INFINITE_RANGE = (-1.0E309, 1.0E309) 
tolerance = TOLERANCE_GLOBAL 
 
#Convert into list type 
xyzRange = [xRange, yRange, zRange] 
for i in range(len(xyzRange)): 
xyzRange[i] = list(xyzRange[i]) 
if len(xyzRange[i]) == 0: 
xyzRange[i] = INFINITE_RANGE 
else: 
if xyzRange[i][0] == None: 
xyzRange[i][0] = INFINITE_RANGE[0] 
if xyzRange[i][1] == None: 
xyzRange[i][1] = INFINITE_RANGE[1] 
if xyzRange[i][0] == xyzRange[i][1]: 
xyzRange[i][0] = xyzRange[i][0] - tolerance 
xyzRange[i][1] = xyzRange[i][1] + tolerance 
 
myObjects = [] 
 
#Find out the edges within the given region 
if objectType == 'EDGE': 
for edge in partObject.edges: 
ptsList = [] 
flag = 1 
ptsList.append(edge.pointOn[0]) 
#Get the vertices on the edge 
for index in edge.getVertices(): 
ptsList.append(partObject.vertices[index].pointOn[0]) 
for ptCoords in ptsList: 
if (ptCoords[0] < xyzRange[0][0] or ptCoords[0] > 
xyzRange[0][1]): 
flag = 0 
break 
if (ptCoords[1] < xyzRange[1][0] or ptCoords[1] > 
xyzRange[1][1]): 
flag = 0 
break 
if (ptCoords[2] < xyzRange[2][0] or ptCoords[2] > 
xyzRange[2][1]): 
flag = 0 
break 
if flag == 1: 
myObjects.append(edge)  
myObjects= tuple(myObjects)  
return myObjects

sub_1=searchObjectByRange(myModel.parts['Part-1'], 'EDGE', (), (), (0, 0))  
#Getting EDGES has the same z-coordinate, and I 166 edges are obtained.
myModel.parts['Part-1'].Set(edges=sub_1,name='sub_set') #I wish to get the set 
'sub_set', but doen't work.


  The error shows "TypeError: edges; too many arguments; expected 0, got 166". 


Is there somebody can help me with that? Thanks.


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

Re: FM synthesis using Numpy

2007-08-16 Thread Joost Molenaar
Thanks/bedankt Bas for the educative reply. I think I got misleaded by
Max/MSP's tutorial[1], because MSP seems to automatically adjust the
phase when you combine two oscillators in the way that I did.

Joost

[1] page 112 of http://www.cycling74.com/download/MSP45TutorialsAndTopics.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem using Optional pyparsing

2007-08-16 Thread Paul McGuire
On Aug 16, 2:09 am, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I know this isnt the pyparsing list, but it doesnt seem like there is
> one. I m trying to use pyparsing to parse a file however I cant get
> the Optional keyword to work.



Thanks, Peter, your comments are dead-on.

Pyparsing-related posts crop up here every so often, usually with me
as the culprit.  But to address your question, I've added a "Getting
Help" page to the pyparsing wiki, with links to the various mailing
lists and support pages on SourceForge.  Fortunately, I don't think
this group minds an occasional trip down Pyparsing Lane (there've been
no serious complaints so far).

Some other suggestions/comments on your parser:
- Good use of results names.  For debugging, you can print out the
parse results by using the dump() method - this gives you this kind of
output:
[1020, 'YS2-10a02.q1k', 'chr09', 1295, 42, 141045, 142297, 'C',
1254, 95.062, 1295, 'reject_bad_break', '0']
- dest_id: chr09
- dest_start: 141045
- dest_stop: 142297
- length: 1254
- percent_id: 95.06
- result: reject_bad_break
- row_1: 1020
- row_11: [1295]
- row_13: ['0']
- row_8: C
- src_id: YS2-10a02.q1k
- src_start: 1295
- src_stop: 42
This may give you some ideas on some more meaningful names ('row_8'
looks like an obvious candidate for replacement, for instance).

- If you are using pyparsing 1.4.7, you can abbreviate your calls to
setResultsName to just ("name"), that is, this:
src_id = identifier.setResultsName("src_id")
can be written as just:
src_id = identifier("src_id")

- Don't use the name 'float' for the expression for a real number,
since this masks the builtin Python type float, and more importantly,
the builtin Python conversion function float (which you will want to
use in the parse action for this expression).  Perhaps a name like
'real' or 'realNumber' would do.

- There is no need for the trailing space in defining
Literal("ALIGNMENT").

- It is simpler to attach the parse actions to integer and real
themselves, rather than on each line where they are used.  If you end
up with some integer field that you don't want converted, you can
define it in situ, like this:
zipCode = Word(nums) # don't use integer for this, don't want it
converted
or define a intString expression that does not do the conversion.

- With these changes, your grammar section becomes a little more
readable:
make_int   = lambda t: int(t[0])
make_float = lambda t: float(t[0])
integer= Word( nums ).setParseAction(make_int)
real   = Word( nums+".").setParseAction(make_float)
identifier = Word( alphanums+"-_." )

alignment  = Literal("ALIGNMENT").suppress()
row_1  = integer("row_1")
src_id = identifier("src_id")
dest_id= identifier("dest_id")
src_start  = integer("src_start")
src_stop   = integer("src_stop")
dest_start = integer("dest_start")
dest_stop  = integer("dest_stop")
row_8  = oneOf("F C")("row_8")
length = integer("length")
percent_id = real("percent_id")
row_11 = (integer +
 Optional(Literal("|") +
delimitedList(Word(nums))("subItems"))
)("row_11")
result = Word(alphas+"_")("result")
row_13 = commaSeparatedList("row_13")

(although all the ()'s make row_11 a little tough to follow - this
might deserve getting broken up into several lines.)  And yes, I know
that PEP8 says not to align '=' signs on successive assignment
statments, but I truly believe it does help readability at times.

-- Paul



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


Car Air Conditioners

2007-08-16 Thread tunedstyle
All the informations about car air conditioners, how to install,
repair, service all can be found on this website...

http://car-air-conditioning.blogspot.com/

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


A problem with Time

2007-08-16 Thread special_dragonfly
Hello,

I need to return the date yesterday in the form DDMM. I looked through 
the modules: time, datetime and calendar but can't find anything that leaps 
out at me.

The problem I'm having is that although I can use time.localtime and get a 
tuple of the year, month, day and so forth, I don't believe I can just minus 
1 from the day, because I don't think it's cyclic, also, I can't see the 
date being linked in with the month.

So is there any way of getting yesterdays date?

Thank You

Dominic 


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


Re: ctypes and C99 complex numbers

2007-08-16 Thread Thomas Heller
Eugen Wintersberger schrieb:
> Hi there
>  I want to use ctypes in connection with C functions that use complex
> datatypes defined in the C99 standard. Does someone know a simple way
> how to implement this? Are there any plans to integrate the C99 complex
> data types in the ctypes module?

I have investigated the complex data types a bit and came to the conclusion
that libffi (which ctypes is based upon) would have to be extended to
support these complex types.  I have not looked into the newer libffi
sources to find out if this support already has been added, ctypes uses
an older version of libffi.

By experimenting I found out that on some systems (x86 linux and x86_64 linux)
I could 'emulate' the complex type by defining a structure:

class Complex(Structure):
   _fields_ = [("real", c_double), ("imag", c_double)]
   def _get(self):
   
   def _set(self, value):
   
   value = property(_get, _set)

but I'm afraid this is not really portable to other platforms.

Thomas

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


Re: A problem with Time

2007-08-16 Thread Shawn Milochik
import time


oneDay = 60 * 60 * 24 #seconds in one day

date = time.time()

yesterday = date - oneDay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who told str() to round my int()'s!!!

2007-08-16 Thread John Nagle
A.T.Hofkamp wrote:
> On 2007-08-15, Larry Bates <[EMAIL PROTECTED]> wrote:
> 
>>or the mildy
>>amusing "how do I write bytes not characters to a file" questions at least 
>>once
>>a week on this forum.

Actually, that's a reasonable question, and one that Python didn't do
quite right.

Remember, in the beginning, Python had only ASCII strings, which
were equivalent to arrays of bytes.  Then came Unicode strings.  Then
came the restriction of ASCII chars to 0..127.  Except that you can
still store binary bytes in ASCII strings, subject to some limitations.

The next logical step is a complete separation of binary data handling
from text string handling, probably using some type in "numarray" for
arrays of bytes.

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


Re: A problem with Time

2007-08-16 Thread syndrowm
On 8/16/07, special_dragonfly <[EMAIL PROTECTED]> wrote:
>
> Hello,
>
> I need to return the date yesterday in the form DDMM. I looked through
> the modules: time, datetime and calendar but can't find anything that
> leaps
> out at me.
>
> The problem I'm having is that although I can use time.localtime and get a
> tuple of the year, month, day and so forth, I don't believe I can just
> minus
> 1 from the day, because I don't think it's cyclic, also, I can't see the
> date being linked in with the month.
>
> So is there any way of getting yesterdays date?
>
> Thank You
>
> Dominic
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list


The easiest way I have found, is to use epoch, subtract the length of time,
then convert back to whatever format.  24 hours  is 86400 seconds.

>>> import time
>>> time.localtime()
(2007, 8, 16, 9, 41, 28, 3, 228, 1)
>>> time.localtime(time.time() - 86400)
(2007, 8, 15, 9, 41, 21, 2, 227, 1)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A problem with Time

2007-08-16 Thread Diez B. Roggisch
special_dragonfly schrieb:
> Hello,
> 
> I need to return the date yesterday in the form DDMM. I looked through 
> the modules: time, datetime and calendar but can't find anything that leaps 
> out at me.
> 
> The problem I'm having is that although I can use time.localtime and get a 
> tuple of the year, month, day and so forth, I don't believe I can just minus 
> 1 from the day, because I don't think it's cyclic, also, I can't see the 
> date being linked in with the month.
> 
> So is there any way of getting yesterdays date?

RTFM is the answer...

import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
print yesterday


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


Re: A problem with Time

2007-08-16 Thread Neil Cerutti
On 2007-08-16, Shawn Milochik <[EMAIL PROTECTED]> wrote:
> import time
>
>
> oneDay = 60 * 60 * 24 #seconds in one day
>
> date = time.time()
>
> yesterday = date - oneDay

Or use a timedelta.

>>> import datetime
>>> yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
>>> yesterday.strftime('%m%d%Y')
'08152007'

-- 
Neil Cerutti
It might take a season, it might take half a season, it might take a year.
--Elgin Baylor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who told str() to round my int()'s!!!

2007-08-16 Thread Neil Cerutti
On 2007-08-16, John Nagle <[EMAIL PROTECTED]> wrote:
>>>or the mildy amusing "how do I write bytes not characters to a
>>>file" questions at least once a week on this forum.
>
> Actually, that's a reasonable question, and one that Python didn't do
> quite right.
>
> Remember, in the beginning, Python had only ASCII strings, which
> were equivalent to arrays of bytes.  Then came Unicode strings.  Then
> came the restriction of ASCII chars to 0..127.  Except that you can
> still store binary bytes in ASCII strings, subject to some limitations.
>
> The next logical step is a complete separation of binary data handling
> from text string handling, probably using some type in "numarray" for
> arrays of bytes.

Python 3000 makes unicode the standard string type, and ushers in
a new type name for the old str type called, I think, 'bytes'. So
the 3000 devs seem to agree with you to some extent.

-- 
Neil Cerutti
Ushers will eat latecomers. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A problem with Time

2007-08-16 Thread Gary Herron
special_dragonfly wrote:
> Hello,
>
> I need to return the date yesterday in the form DDMM. I looked through 
> the modules: time, datetime and calendar but can't find anything that leaps 
> out at me.
>
> The problem I'm having is that although I can use time.localtime and get a 
> tuple of the year, month, day and so forth, I don't believe I can just minus 
> 1 from the day, because I don't think it's cyclic, also, I can't see the 
> date being linked in with the month.
>
> So is there any way of getting yesterdays date?
>
> Thank You
>
> Dominic 
>
>
>   
Here's how I'd do it:


>>> import time
>>> secondsPerDay = 24*60*60
>>> today = time.time()
>>> yesterday = today - secondsPerDay
>>> print time.strftime("%d%m%Y",time.localtime(today))
16082007
>>> print time.strftime("%d%m%Y",time.localtime(yesterday))
15082007

Gary Herron


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


Re: ploting issues in program

2007-08-16 Thread Gerard Flanagan
On Aug 16, 9:48 am, yadin <[EMAIL PROTECTED]> wrote:
> hi every one!
>
> can you please help me to fix these polar plot in db's
> so that the center is at the minimun negative number in voltagedb
> about [-50]
> and the maximun is at zero and how can i see values on the axis like
> showing that the axes start at -50 -40 -30 .and end at zero
> than you

Just guessing, does plotting the following rectangular coords give you
any insight?
Seems to be a rough figure of eight.


theta =  [ 4.36332313e-003, 3.18522588e-001, 6.32681854e-001,
9.46841119e-001,
 1.26100038e+000, 1.57515965e+000, 1.88931892e+000,
2.20347818e+000,
 2.51763745e+000, 2.83179671e+000, 3.14595598e+000,
3.46011524e+000,
 3.77427451e+000, 4.08843377e+000, 4.40259304e+000,
4.71675230e+000,
 5.03091157e+000, 5.34507083e+000, 5.65923010e+000,
5.97338936e+000,]


voltage =  [ 0.00363471, 0.26569155, 0.52562334, 0.76330428,
0.93673361, 1.,
 0.93321713, 0.75733232, 0.5185449 , 0.25840091,
0.00363471, 0.26569155,
 0.52562334, 0.76330428, 0.93673361, 1.,
0.93321713, 0.75733232,
 0.5185449 , 0.25840091,]


from math import *

#dbvoltage = [20*log10(1/v) for v in voltage]
dbvoltage = [-20*log10(v) for v in voltage]

def mkpoint(m, arg):
return m*sin(arg), m*cos(arg)

graph = [mkpoint(m,arg) for m, arg in zip(dbvoltage, theta)]

for point in graph:
print point

(0.21288849842373814, 48.790140231909419)
(3.6052811402858937, 10.933359102749559)
(3.303355590073223, 4.505208562238618)
(1.903989999253, 1.3706766199218816)
(0.54065408491628131, 0.17306473975245495)
(0.0, 0.0)
(0.57014803194263397, -0.18800662846533356)
(1.9469751572632745, -1.427581247329087)
(3.3327193729963271, -4.6294392863200207)
(3.583411756323, -11.194573773272479)
(-0.21288865846549074, -48.790140231211105)
(-3.6052811229041124, -10.933359108481211)
(-3.3033556009317082, -4.5052085542768472)
(-1.9039899297901561, -1.3706766248528219)
(-0.54065408602566212, -0.17306473628675043)
(0.0, 0.0)
(-0.57014803261753888, 0.18800662641861987)
(-1.9469751623879956, 1.4275812403398493)
(-3.3327193896150562, 4.6294392743562476)
(-3.5834113735618405, 11.194573760408771)

Gerard


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


Re: Who told str() to round my int()'s!!!

2007-08-16 Thread Diez B. Roggisch
John Nagle schrieb:
> A.T.Hofkamp wrote:
>> On 2007-08-15, Larry Bates <[EMAIL PROTECTED]> wrote:
>>
>>> or the mildy
>>> amusing "how do I write bytes not characters to a file" questions at 
>>> least once
>>> a week on this forum.
> 
>Actually, that's a reasonable question, and one that Python didn't do
> quite right.
> 
>Remember, in the beginning, Python had only ASCII strings, which
> were equivalent to arrays of bytes.  Then came Unicode strings.  Then
> came the restriction of ASCII chars to 0..127.  Except that you can
> still store binary bytes in ASCII strings, subject to some limitations.

Sorry, but that's bogus. Python had byte-strings from the beginning. 
Nothing to do with ASCII. Which is an encoding-standard that has ALWAYS 
been limited to the numbers 0..127.

All that changed was the introduction of unicode-objects and due to the 
fact that these need to be serialized to/from bytestrings the 
introduction of ASCII as default-encoding.

So no "still storing" or anything such.

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


Re: threads, mutual exclusion, and lists

2007-08-16 Thread Matt McCredie
> Why do you think they are not?

Because they aren't. You even mentioned that a few operations that
aren't atomic. If operations are atomic it isn't necessarily because
of the design of the list, but the design of CPython. More
specifically the GIL. I don't mean to imply that you can't get a
multi-threaded app to communicate using lists, but the Queue is
explicitly built for it and better suited.

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


Re: Who told str() to round my int()'s!!!

2007-08-16 Thread Chris Mellon
On 8/16/07, John Nagle <[EMAIL PROTECTED]> wrote:
> A.T.Hofkamp wrote:
> > On 2007-08-15, Larry Bates <[EMAIL PROTECTED]> wrote:
> >
> >>or the mildy
> >>amusing "how do I write bytes not characters to a file" questions at least 
> >>once
> >>a week on this forum.
>
> Actually, that's a reasonable question, and one that Python didn't do
> quite right.
>

No it isn't. You can't write anything except bytes to a file (or to a
socket, or, in fact, to any form of IO) and anyone who thinks they can
do anything different is confused.

> Remember, in the beginning, Python had only ASCII strings, which
> were equivalent to arrays of bytes.  Then came Unicode strings.  Then
> came the restriction of ASCII chars to 0..127.  Except that you can
> still store binary bytes in ASCII strings, subject to some limitations.
>

I agree that the name of the string object is a misnomer, because it's
actually a sequence of bytes.

There's no limitation to anything you can stick it - a python 2.x
string object can contain any arbitrary sequence of bytes.

Where you may believe that you see a limitation is in the default
implicit unicode conversion, which assumes non-extended ascii and
errors on values over 127. This is a pragmatic decision which assumes
that being able to print unicode objects without hoop-jumping is
preferable to preventing the errors and confusion caused by implicit
conversion. I am not 100% certain the correct decision was made -
there's a lot of confusion on this list that would be easier to
explain if any attempt to convert unicode to bytes or vice versa
required an explicit encoding.

> The next logical step is a complete separation of binary data handling
> from text string handling, probably using some type in "numarray" for
> arrays of bytes.
>

There are still lots of cases where it's convenient to work with
binary data as if it were ascii text, and overlap between "real"
binary data work and textual data work.

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


Re: threads, mutual exclusion, and lists

2007-08-16 Thread Martin v. Löwis
>> Why do you think they are not?
> 
> Because they aren't. You even mentioned that a few operations that
> aren't atomic. 

OTOH, the OP specifically asked for .append() and .pop(), which are
atomic.

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


Re: Layer 2 socket connection

2007-08-16 Thread alisonken1
On Aug 16, 5:03 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:

> I use impacket for stuff like that, 
> seehttp://oss.coresecurity.com/projects/impacket.html
>
> Cheers
>
> Rich.

Thanks, Rich - I'll have a look

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


Re: ctypes and C99 complex numbers

2007-08-16 Thread Martin v. Löwis
Thomas Heller schrieb:
> Eugen Wintersberger schrieb:
>> Hi there
>>  I want to use ctypes in connection with C functions that use complex
>> datatypes defined in the C99 standard. Does someone know a simple way
>> how to implement this? Are there any plans to integrate the C99 complex
>> data types in the ctypes module?
> 
> I have investigated the complex data types a bit and came to the conclusion
> that libffi (which ctypes is based upon) would have to be extended to
> support these complex types.  

I think that depends on what kind of support you want to provide. For
passing _Complex values as parameters or receiving them as results,
it's certainly necessary to have libffi support.

OTOH, if you only want to support _Complex as the field type of a
struct or an array, you can do so without libffi support. To write
a field at address p with the values r and i, do

  *(double complex*)p = r * i*I;

To fetch the real and imaginary part of a field at address p, do

  creal(*(double complex*)p)
  cimag(*(double complex*)p)

Likewise for float complex values (and long double complex, if you
want to support that).

Whether such a limited version would be of any use (e.g. to the OP),
I don't know.

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


Re: A problem with Time

2007-08-16 Thread BartlebyScrivener
On Aug 16, 10:54 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> RTFM is the answer...

I don't know. I remember scratching my head for a day or two over the
module explanations and instructions until I found a little howto with
a lot of explicite examples.

http://pleac.sourceforge.net/pleac_python/datesandtimes.html

rd

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


Re: Module imports during object instantiation

2007-08-16 Thread Ritesh Raj Sarraf
Steve Holden wrote:

> Ritesh Raj Sarraf wrote:
>> On Aug 16, 12:16 am, Ritesh Raj Sarraf <[EMAIL PROTECTED]> wrote:
>>> On Aug 15, 11:42 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>>
> [...]
>> Oops!!! Looks like I completely missed this. It _did_ print the error
>> message.
>> Apologies to all for not keeping a close eye on the error message.
>> 
> Quite. It was obvious to many readers that you were fooling yourself
> with a false hypothesis. The probability of something so fundamental
> being wrong is vanishingly small.
> 

Yes, and now I realize how I would have got into the stupid assumption that
imports were never executed in a class' __init__() was because:

* I defined an import within a class' __init__()
* It used to get executed.
* Then I used to make an assumption that calling it from one of the methods
would work. But instead the module was never in the Namespace. And that led
me to the mis-understanding that the import never got executed. What a fool
am I.


I think people gave a good reason when they mentioned about top-level
imports. I would move ahead with keeping things simple.

Thanks to all for your time and patience on this thread (At least, no one is
yelling at me ;-)


Ritesh
-- 
If possible, Please CC me when replying. I'm not subscribed to the list.

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


Re: ploting issues in program

2007-08-16 Thread Peter Otten
Steve Holden wrote:

> I might ask just exactly what is being plotted to give those answers. It
> sounds like field strength, but I am having difficulty envisaging a
> field that is weakest at its center - is this some sort of alternative
> universe you are plotting :-) ?

I believe the OP is trying to plot a radiation pattern like Figure 4.5 on
the following page:

http://www.vias.org/wirelessnetw/wndw_06_05_05.html

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


Accessing Windows Network Share?

2007-08-16 Thread frikk
I previously posted about accessing SharePoint over the web. Well I
have since given up any easy means of doing this, since something else
has perked my interest.  Instead of going to http://sharepoint/site,
why not just access \\sharepoint\site\ directly?

So my question is this - How do I access that network share?

If I go to start -> run, and type in "\\SharPointServer\Site\Folder",
windows explorer will pop up with it.  I suppose I could have a little
batch script that python runs to map the drive to a local letter, like
J:, but this does not seem necessary.

Suggestions?

This does not work, for obvious reasons:
>>> import glob.glob
>>> glob.glob("server\\folder\\*")
[]


Thanks guys!
Blaine

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


Tuning - Styling

2007-08-16 Thread [EMAIL PROTECTED]
Cool cars, tuning & styling, modified cars, many upgrades here...

http://tuning-styling.blogspot.com/

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


Re: Accessing Windows Network Share?

2007-08-16 Thread Chris Mellon
On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
> I previously posted about accessing SharePoint over the web. Well I
> have since given up any easy means of doing this, since something else
> has perked my interest.  Instead of going to http://sharepoint/site,
> why not just access \\sharepoint\site\ directly?
>
> So my question is this - How do I access that network share?
>
> If I go to start -> run, and type in "\\SharPointServer\Site\Folder",
> windows explorer will pop up with it.  I suppose I could have a little
> batch script that python runs to map the drive to a local letter, like
> J:, but this does not seem necessary.
>
> Suggestions?
>
> This does not work, for obvious reasons:
> >>> import glob.glob
> >>> glob.glob("server\\folder\\*")
> []
>

I don't see whats "obvious" about this. Access to windows shares is
handled by Windows in a VFS layer, and glob and all other Python file
access works fine over them for me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing Windows Network Share?

2007-08-16 Thread frikk
On Aug 16, 2:43 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > I previously posted about accessing SharePoint over the web. Well I
> > have since given up any easy means of doing this, since something else
> > has perked my interest.  Instead of going tohttp://sharepoint/site,
> > why not just access \\sharepoint\site\ directly?
>
> > So my question is this - How do I access that network share?
>
> > If I go to start -> run, and type in "\\SharPointServer\Site\Folder",
> > windows explorer will pop up with it.  I suppose I could have a little
> > batch script that python runs to map the drive to a local letter, like
> > J:, but this does not seem necessary.
>
> > Suggestions?
>
> > This does not work, for obvious reasons:
> > >>> import glob.glob
> > >>> glob.glob("server\\folder\\*")
> > []
>
> I don't see whats "obvious" about this. Access to windows shares is
> handled by Windows in a VFS layer, and glob and all other Python file
> access works fine over them for me.- Hide quoted text -
>
> - Show quoted text -

Haha ok, you're right its not obvious. Sorry for that.

But that code does not work - should it?

Do you have an example of glob working over a file share, not a
network mapped drive?

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


Re: Accessing Windows Network Share?

2007-08-16 Thread Chris Mellon
On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
> On Aug 16, 2:43 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> > On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> >
> >
> > > I previously posted about accessing SharePoint over the web. Well I
> > > have since given up any easy means of doing this, since something else
> > > has perked my interest.  Instead of going tohttp://sharepoint/site,
> > > why not just access \\sharepoint\site\ directly?
> >
> > > So my question is this - How do I access that network share?
> >
> > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder",
> > > windows explorer will pop up with it.  I suppose I could have a little
> > > batch script that python runs to map the drive to a local letter, like
> > > J:, but this does not seem necessary.
> >
> > > Suggestions?
> >
> > > This does not work, for obvious reasons:
> > > >>> import glob.glob
> > > >>> glob.glob("server\\folder\\*")
> > > []
> >
> > I don't see whats "obvious" about this. Access to windows shares is
> > handled by Windows in a VFS layer, and glob and all other Python file
> > access works fine over them for me.- Hide quoted text -
> >
> > - Show quoted text -
>
> Haha ok, you're right its not obvious. Sorry for that.
>
> But that code does not work - should it?
>
> Do you have an example of glob working over a file share, not a
> network mapped drive?
>

import glob
glob.glob(r"\\localhost\c$\python25\libs\*")
['localhost\\c$\\python25\\libs\\bz2.lib',
'localhost\\c$\\python25\\libs\\libpython25.a',
'localhost\\c$\\python25\\libs\\pyexpat.lib',
'localhost\\c$\\python25\\libs\\python25.lib',
'localhost\\c$\\python25\\libs\\select.lib',
'localhost\\c$\\python25\\libs\\unicodedata.lib',
'localhost\\c$\\python25\\libs\\winsound.lib',
'localhost\\c$\\python25\\libs\\_bsddb.lib',
'localhost\\c$\\python25\\libs\\_ctypes.lib',
'localhost\\c$\\python25\\libs\\_ctypes_test.lib',
'localhost\\c$\\python25\\libs\\_elementtree.lib',
'localhost\\c$\\python25\\libs\\_hashlib.lib',
'localhost\\c$\\python25\\libs\\_msi.lib',
'localhost\\c$\\python25\\libs\\_socket.lib',
'localhost\\c$\\python25\\libs\\_sqlite3.lib',
'localhost\\c$\\python25\\libs\\_ssl.lib',
'localhost\\c$\\python25\\libs\\_testcapi.lib',
'localhost\\c$\\python25\\libs\\_tkinter.lib']



I do it all the time. I'd double check your slash escaping (consider
using r'') and pathnames.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help me!!

2007-08-16 Thread Rohan
I have the following piece of code

a = len(ab_file)
   b= 0
   while(bhttp://mail.python.org/mailman/listinfo/python-list


Idea for joined() builtin

2007-08-16 Thread Rhamphoryncus
I know similar things have been argued before, but little things (like
the joined name implying a copy) can make a big difference.  That and
I'm providing a simple implementation that works right now, so you
don't have to wait for it to ever become a builtin. ;)

>>> joined([], [[1,2,3], [4,5,6]])
[1, 2, 3, 4, 5, 6]
>>> joined(' ', ['hello', 'world'])
'hello world'

def joined(sep, iterable):
if hasattr(sep, 'join'):
return sep.join(iterable)  # string-like interface
else:
output = type(sep)()  # Hopefully an empty container
for i in iterable:
output.extend(i)  # list-like interface
output.extend(sep)
else:
if sep:
del output[-len(sep):]
return output

A little commentary on the intended usage.  There are three common
ways to "combine" objects:

The first is adding numbers together.  This may be accomplished with a
+b or sum([a, b]).  All values affect the output, but their
individuality is lost; you cannot extract the original values[1].

The second is concatenation.  This is usually done with list.extend,
''.join(), or with my joined function.  It can also be done with a+b,
but the performance is substantially worse if done repeatedly.  All
values affect the output and most of their individuality is retained;
given the original lengths of the subsequences, you can extract them
from the combined form.

The third is the "or" operation of a set or integer.  This is done
with a|b.  The values usually have some effect on the output, but as
redundant entries are removed, they lose a significant part of their
individuality.

The important thing to realize is that all of these different ways of
"combining" objects has different conceptual behaviour and different
performance characteristics.  Get them confused or attempt to over-
generalize and you will be bitten.


[1] Math/crypto has some exceptions.  Stop mentally poking holes in my
argument. :)

--
Adam Olsen, aka Rhamphoryncus

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


Re: Help me!!

2007-08-16 Thread beginner
> Some one help me so that
> If ab = [a,b,c,d]
> and cd = [a,c]
> my global list file should be [A,b,C,d]


If there is a lot of entries in the list, I would consider using an
indexed data structure such as dict.

>>> ab=['a','b','c','d']
>>> cd=['a','c']
>>> common=[x.upper() for x in ab if x in cd]
>>> ab_minus_cd=[x for x in ab if x not in cd]
>>> cd_minus_ab=[x for x in ab if x not in cd]
>>> requested_list = common+ab_minus_cd+cd_minus_ab

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


Re: Help me!!

2007-08-16 Thread beginner
On Aug 16, 2:26 pm, beginner <[EMAIL PROTECTED]> wrote:
> > Some one help me so that
> > If ab = [a,b,c,d]
> > and cd = [a,c]
> > my global list file should be [A,b,C,d]

If there is a lot of entries in the list, I would consider using an
indexed data structure such as dict.


ab=['a','b','c','d']
cd=['a','c']
common=[x.upper() for x in ab if x in cd]
ab_minus_cd=[x for x in ab if x not in cd]
cd_minus_ab=[x for x in ab if x not in cd]
requested_list = common+ab_minus_cd+cd_minus_ab- Hide quoted text -

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


wxpython log redirect

2007-08-16 Thread vedrandekovic
Hello,

Why this wx example don't return \nHELLO WORLD and other text in same
window:


import wx
import logging
import sys

def nekaj():
print "\nHELLO WORLD"

class WxLog(logging.Handler):
def __init__(self, ctrl):
logging.Handler.__init__(self)
self.ctrl = ctrl
def emit(self, record):
self.ctrl.AppendText(self.format(record)+"\n")



class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="logging test")
sizer = wx.BoxSizer(wx.VERTICAL)

log = wx.TextCtrl(self, style=wx.TE_MULTILINE)

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
hdlr = WxLog(log)
hdlr.setFormatter(logging.Formatter('%(levelname)s | %(name)s |
%(message)s [@ %(asctime)s in %(filename)s:%(lineno)d]'))
rootLogger.addHandler(hdlr)
rootLogger.debug(str(sys.stdout))
nekaj()  # goes to the function nekaj

if __name__ =="__main__":
app = wx.App(0)
frame = MainFrame()
frame.Show()
app.MainLoop()


Regards,
Vedran

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


Re: (sort of) deterministic timing in Python

2007-08-16 Thread Paul Rubin
[EMAIL PROTECTED] (John Fisher) writes:
> mark start time
> start event
> event finishes
> count time until next interval
> start second event…
> 
> rather than this:
> 
> start event
> event finishes
> sleep for interval
> start second event
> ...
> So how do I accomplish this in Python with a minimum of labour?

Normally I'd use something like:

   from time import time

   t0 = time()
   start event ... event finishes
   t1 = time()
   elapsed = t1 - t0
   sleep(interval - elapsed)
   start second event ...

Am I missing something?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me!!

2007-08-16 Thread Gerardo Herzig
Anhoter HURRA for list comprehensions:
 >>> a = ['a', 'b', 'c', 'd']
 >>> b = ['a','c']
 >>> [x in b and x.upper() or x for x in a]
['A', 'b', 'C', 'd']

Is what you want?
Cheers

Gerardo

>I'm trying to compare the list with another list and if it is there in
>both I'm changing it to upper case and adding to another list and if
>its not there in both I just want to add it to the global list (ie
>files).
>I'm able to do the first part but when I'm doing the second part the
>files which are not there in both are getting repeatedly into the
>global file. Some one help me so that
>If ab = [a,b,c,d]
>and cd = [a,c]
>my global list file should be [A,b,C,d]
>
>  
>

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


Re: A problem with Time

2007-08-16 Thread MRAB
On Aug 16, 4:30 pm, "special_dragonfly" <[EMAIL PROTECTED]>
wrote:
> Hello,
>
> I need to return the date yesterday in the form DDMM. I looked through
> the modules: time, datetime and calendar but can't find anything that leaps
> out at me.
>
> The problem I'm having is that although I can use time.localtime and get a
> tuple of the year, month, day and so forth, I don't believe I can just minus
> 1 from the day, because I don't think it's cyclic, also, I can't see the
> date being linked in with the month.
>
> So is there any way of getting yesterdays date?
>
As well as the other replies, this also works (as far as I can tell!):

import time
today = time.localtime()
yesterday = today[ : 2] + (today[2] - 1, ) + today[3 : ]
yesterday = time.localtime(time.mktime(yesterday))

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


Re: Accessing Windows Network Share?

2007-08-16 Thread frikk
On Aug 16, 3:03 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Aug 16, 2:43 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> > > On 8/16/07, frikk <[EMAIL PROTECTED]> wrote:
>
> > > > I previously posted about accessing SharePoint over the web. Well I
> > > > have since given up any easy means of doing this, since something else
> > > > has perked my interest.  Instead of going tohttp://sharepoint/site,
> > > > why not just access \\sharepoint\site\ directly?
>
> > > > So my question is this - How do I access that network share?
>
> > > > If I go to start -> run, and type in "\\SharPointServer\Site\Folder",
> > > > windows explorer will pop up with it.  I suppose I could have a little
> > > > batch script that python runs to map the drive to a local letter, like
> > > > J:, but this does not seem necessary.
>
> > > > Suggestions?
>
> > > > This does not work, for obvious reasons:
> > > > >>> import glob.glob
> > > > >>> glob.glob("server\\folder\\*")
> > > > []
>
> > > I don't see whats "obvious" about this. Access to windows shares is
> > > handled by Windows in a VFS layer, and glob and all other Python file
> > > access works fine over them for me.- Hide quoted text -
>
> > > - Show quoted text -
>
> > Haha ok, you're right its not obvious. Sorry for that.
>
> > But that code does not work - should it?
>
> > Do you have an example of glob working over a file share, not a
> > network mapped drive?
>
> import glob
> glob.glob(r"\\localhost\c$\python25\libs\*")
> ['localhost\\c$\\python25\\libs\\bz2.lib',
> 'localhost\\c$\\python25\\libs\\libpython25.a',
> 'localhost\\c$\\python25\\libs\\pyexpat.lib',
> 'localhost\\c$\\python25\\libs\\python25.lib',
> 'localhost\\c$\\python25\\libs\\select.lib',
> 'localhost\\c$\\python25\\libs\\unicodedata.lib',
> 'localhost\\c$\\python25\\libs\\winsound.lib',
> 'localhost\\c$\\python25\\libs\\_bsddb.lib',
> 'localhost\\c$\\python25\\libs\\_ctypes.lib',
> 'localhost\\c$\\python25\\libs\\_ctypes_test.lib',
> 'localhost\\c$\\python25\\libs\\_elementtree.lib',
> 'localhost\\c$\\python25\\libs\\_hashlib.lib',
> 'localhost\\c$\\python25\\libs\\_msi.lib',
> 'localhost\\c$\\python25\\libs\\_socket.lib',
> 'localhost\\c$\\python25\\libs\\_sqlite3.lib',
> 'localhost\\c$\\python25\\libs\\_ssl.lib',
> 'localhost\\c$\\python25\\libs\\_testcapi.lib',
> 'localhost\\c$\\python25\\libs\\_tkinter.lib']
>
> I do it all the time. I'd double check your slash escaping (consider
> using r'') and pathnames.- Hide quoted text -
>
> - Show quoted text -

I must have been doing it wrong.  Thanks! That works great!

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


advice about `correct' use of decorator

2007-08-16 Thread Gerardo Herzig
Hi all. I guess i have a conceptual question:
Im planing using a quite simple decorator to be used as a conditional 
for the execution of the function. I mean something like that:

@is_logued_in
def change_pass():
bla
bla

And so on for all the other functions who needs that the user is still 
loged in.

where obviosly the is_logued_in() function will determine if the dude is 
still loged in, and THEN execute change_pass(). If the dude is not loged 
in, change_pass() is NOT executed at all. Instead, it will be redirected 
to the `login' screen.

Something in my mind tells me that this is not the pythonic way...But i 
like the idea, so please tell me that im in the right way :)

Cheers.
Gerardo


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


Re: sub-classing the types in the builtin module datetime

2007-08-16 Thread [EMAIL PROTECTED]
On Aug 15, 5:54 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
> I posted this about 5 hours ago, but it seems to have gone astray.


(snipped)

>  >
>  >> I wish to sub-class (if that's the right word) datetime and to use a
>  >> different signature for the constructor.
>  >>
>  >> The second part has gone smoothly, but it is difficult to access the
>  >> type's methods from the sub-class instance.
>  >>
>  >> I'm beginning to wonder whether it might might be simpler to write my
>  >> own Date class.
>  >>
>  >> Does anyone have any comments please?
>  >>
>  >> Colin W.

(snipped)


> Yes, I should have posted an example, but I thought that others might
> have experienced the problem.
>
> It is illustrated at the bottom of this script:
>
> # subClassing.py
>
> import datetime
> import new
> import sys
> import types
>
> class Date(datetime.datetime):
>''' Date(s) -> a date object.__class__
>  where s is an 8 digit string'''
>
>def __new__(cls, YYmmdd):
>  ''' YYmmdd is a string, in the form mmdd i.e. 8 digits.
>  ora 3-tuple of integers in the form (y, m, d)
>  ora 6-tuple of integers in the form (y, m, d, h, m,
> s) '''


(snipped)

>
> a= datetime.datetime(2007, 7, 31)
> d= Date('20070731')
> tm= datetime.time(1, 2)
> try:
>print a.today()
> #  print d.today()# grief
>print a.now()
> #  print d.now()  # grief
>print a.combine(a, tm)  # OK, but  why not a.combine(tm)?
> #  e= d.combine(d, tm)# grief
>print a.utcnow()
> #  print d.utcnow()   # grief
>print a.ctime()
>print d.ctime()
> except:
>print 'Grief'
>print sys.exc_info()
>
> Colin W.





This problem arises when you change the function signature of __new__.
I'm a little unclear as to why but it seems for the classmethods
(thosed marked with the METH_CLASS flag in the C source code), you
need to arrange to bypass the normal method resolution (I used a
metaclass
to do this):



import datetime

class Date(datetime.datetime):
pass

class FixClassMethods(type):
def __init__(cls, classname, bases, classdict):
# add strptime if using Python 2.5
flagged_as_meth_class = ('today', 'now', 'fromtimestamp',
'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine')
for meth in flagged_as_meth_class:
setattr(cls, meth, getattr(datetime.datetime, meth))

class DateChangesNewSignature(datetime.datetime):
@staticmethod
def str2ymd(strval):
, mm, dd = (int(substr) for substr in (strval[:4],
strval[4:6], strval[6:]))
return , mm, dd

def __new__(cls, strval):
, mm, dd = DateChangesNewSignature.str2ymd(strval)
return super(DateChangesNewSignature,cls).__new__(cls, ,
mm,
dd)
def __init__(self, strval):
, mm, dd = DateChangesNewSignature.str2ymd(strval)
super(DateChangesNewSignature, self).__init__(, mm,
dd)

class DLast(DateChangesNewSignature):
__metaclass__ = FixClassMethods

f = Date(2007,07,07)
print f
print f.today()

f2 = DateChangesNewSignature("20070707")
print f2
try:
print f2.today()
except TypeError, e:
print str(e)
print "Uh?"


f3 = DLast("20070707")
print f3
print f3.today()


I get:

2007-07-07 00:00:00
2007-08-16 12:57:41.480679
2007-07-07 00:00:00
__new__() takes exactly 2 arguments (9 given)
Uh?
2007-07-07 00:00:00
2007-08-16 12:57:41.483104


--
Hope this helps,
Steven

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


Haskell lambdas in python

2007-08-16 Thread Michael Speer
Hello python-list,

I decided to have some fun and altered a copy of python to use a
Haskell-like syntax for declaring lambdas.

>>> filter( \ x -> x == 3 or x > 8 , [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
10 ] )
[3, 9, 10]
>>> ( \-> "Hello World!" )()
'Hello World!'

While doing this I found something interesting while changing the grammar to
:

old_lambdef: ( 'lambda' | '\\' ) [varargslist] ( ':' | '->' ) old_test
...
lambdef: ( 'lambda' | '\\' ) [varargslist] ( ':' | '->' ) test


In Parser/tokenizer.c, instead of needing to change only the PyToken_OneChar
function to have a
case '\\':  return LAMBDAARGS;
option, I also had to add
case '\\':
switch (c2) {
case '\\':  return LAMBDAARGS;
}
to PyToken_TwoChars.

The interactive runtime requires the OneChar definition, and the compilation
process ( specifically pgen ) requires the TwoChar definition.

If anyone wants the changes required to play around with it just email me
and I'll find somewhere to stick them on the web for download.

It seems a waste that whack acts only as an end of line continuance.

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

Re: advice about `correct' use of decorator

2007-08-16 Thread Laszlo Nagy
Gerardo Herzig wrote:
> Hi all. I guess i have a conceptual question:
> Im planing using a quite simple decorator to be used as a conditional 
> for the execution of the function. I mean something like that:
>
> @is_logued_in
> def change_pass():
> bla
> bla
>
> And so on for all the other functions who needs that the user is still 
> loged in.
>
> where obviosly the is_logued_in() function will determine if the dude is 
> still loged in, and THEN execute change_pass(). If the dude is not loged 
> in, change_pass() is NOT executed at all. Instead, it will be redirected 
> to the `login' screen.
>   
Are you developing a website or a GUI program?

   Laszlo

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


Re: A problem with Time

2007-08-16 Thread Roger Miller
On Aug 16, 9:46 am, MRAB <[EMAIL PROTECTED]> wrote:
>
> As well as the other replies, this also works (as far as I can tell!):
>
> import time
> today = time.localtime()
> yesterday = today[ : 2] + (today[2] - 1, ) + today[3 : ]
> yesterday = time.localtime(time.mktime(yesterday))

This is something I have wondered about.  The C library mktime
function is
documented to fix up out of range values,.  For example July 32
becomes
August 1 and August -1 becomes July 31.  Python presumably inherits
this
very useful (and seemingly not well known) behavior, but it is not
documented.  Is this just an oversight, or is it intentional on the
grounds
that it might be platform-dependent?  Any language lawyers out there
that
would care to comment?

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


Re: Hijack! Different book:

2007-08-16 Thread Steve Holden
Dennis Lee Bieber wrote:
> On Thu, 16 Aug 2007 04:21:07 -0700, Paul Boddie <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
>> Is this the book that came out before TurboGears even reached 1.0,
>> probably having diminished relevance now that there are 1.1 and 2.0
> 
>   Not sure -- I'd ordered it in January, but Amazon didn't ship it
> until a week ago; don't know if it was this, or the other book in the
> shipment that held it up.

JANUARY!?? So much for Amazon's customer service. Or is it only 
February where you live?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: ploting issues in program

2007-08-16 Thread Steve Holden
Peter Otten wrote:
> Steve Holden wrote:
> 
>> I might ask just exactly what is being plotted to give those answers. It
>> sounds like field strength, but I am having difficulty envisaging a
>> field that is weakest at its center - is this some sort of alternative
>> universe you are plotting :-) ?
> 
> I believe the OP is trying to plot a radiation pattern like Figure 4.5 on
> the following page:
> 
> http://www.vias.org/wirelessnetw/wndw_06_05_05.html
> 
Right, it's a relative field strength plot. Now I see. Thanks.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Pass by reference or by value?

2007-08-16 Thread Robert Dailey
Hi,

I previously created a topic named "Pass by reference or by value" where I
inquired on how python's function parameters work. I received a lot of nice
responses, however I'm still confused on the topic. Note that I come from a
C++ background to Python, so any comparisons to C++ would be very helpful.

I ran a few tests. There's two tests in particular I wanted to show you
guys:

myvar = []

def changeme( param ):
param.append( "blah" )
print param

changeme( myvar )

print myvar

The above code yields the following output:
['blah']
['blah']

This means that the list passed in was modified by the function.

Now test case 2:

myvar = 4

def changeme( param ):
param = 5
print param

changeme( myvar )

print myvar

The above code yields the following output:
5
4

This means that the integer passed in was NOT modified by the function.


Between these two tests, both types passed in are mutable objects. I'm
having trouble figuring out what mandates an object to be changed from
within a function versus not. What is happening in test case 2 to cause it
to not be modified?

Thanks for reading guys. Hopefully one day I'll understand this lol.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: advice about `correct' use of decorator

2007-08-16 Thread Gerardo Herzig
Gerardo Herzig wrote:

>> Hi all. I guess i have a conceptual question:
>> Im planing using a quite simple decorator to be used as a conditional 
>> for the execution of the function. I mean something like that:
>>
>> @is_logued_in
>> def change_pass():
>> bla
>> bla
>>
>> And so on for all the other functions who needs that the user is 
>> still loged in.
>>
>> where obviosly the is_logued_in() function will determine if the dude 
>> is still loged in, and THEN execute change_pass(). If the dude is not 
>> loged in, change_pass() is NOT executed at all. Instead, it will be 
>> redirected to the `login' screen.
>>   
>
> Are you developing a website or a GUI program?
>
>   Laszlo
>
>
It will be used in a web development. It is an important point?
Gerardo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sub-classing the types in the builtin module datetime

2007-08-16 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
> On Aug 15, 5:54 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
>> I posted this about 5 hours ago, but it seems to have gone astray.
> 
> 
> (snipped)
> 
>>  >
>>  >> I wish to sub-class (if that's the right word) datetime and to use a
>>  >> different signature for the constructor.
>>  >>
>>  >> The second part has gone smoothly, but it is difficult to access the
>>  >> type's methods from the sub-class instance.
>>  >>
>>  >> I'm beginning to wonder whether it might might be simpler to write my
>>  >> own Date class.
>>  >>
>>  >> Does anyone have any comments please?
>>  >>
>>  >> Colin W.
> 
> (snipped)
> 
> 
>> Yes, I should have posted an example, but I thought that others might
>> have experienced the problem.
>>
>> It is illustrated at the bottom of this script:
>>
>> # subClassing.py
>>
>> import datetime
>> import new
>> import sys
>> import types
>>
>> class Date(datetime.datetime):
>>''' Date(s) -> a date object.__class__
>>  where s is an 8 digit string'''
>>
>>def __new__(cls, YYmmdd):
>>  ''' YYmmdd is a string, in the form mmdd i.e. 8 digits.
>>  ora 3-tuple of integers in the form (y, m, d)
>>  ora 6-tuple of integers in the form (y, m, d, h, m,
>> s) '''
> 
> 
> (snipped)
> 
>> a= datetime.datetime(2007, 7, 31)
>> d= Date('20070731')
>> tm= datetime.time(1, 2)
>> try:
>>print a.today()
>> #  print d.today()# grief
>>print a.now()
>> #  print d.now()  # grief
>>print a.combine(a, tm)  # OK, but  why not a.combine(tm)?
>> #  e= d.combine(d, tm)# grief
>>print a.utcnow()
>> #  print d.utcnow()   # grief
>>print a.ctime()
>>print d.ctime()
>> except:
>>print 'Grief'
>>print sys.exc_info()
>>
>> Colin W.
> 
> 
> 
> 
> 
> This problem arises when you change the function signature of __new__.
> I'm a little unclear as to why but it seems for the classmethods
> (thosed marked with the METH_CLASS flag in the C source code), you
> need to arrange to bypass the normal method resolution (I used a
> metaclass
> to do this):
> 
> 
> 
> import datetime
> 
> class Date(datetime.datetime):
> pass
> 
> class FixClassMethods(type):
> def __init__(cls, classname, bases, classdict):
> # add strptime if using Python 2.5
> flagged_as_meth_class = ('today', 'now', 'fromtimestamp',
> 'fromordinal', 'now', 'utcnow', 'utcfromtimestamp', 'combine')
> for meth in flagged_as_meth_class:
> setattr(cls, meth, getattr(datetime.datetime, meth))
> 
> class DateChangesNewSignature(datetime.datetime):
> @staticmethod
> def str2ymd(strval):
> , mm, dd = (int(substr) for substr in (strval[:4],
> strval[4:6], strval[6:]))
> return , mm, dd
> 
> def __new__(cls, strval):
> , mm, dd = DateChangesNewSignature.str2ymd(strval)
> return super(DateChangesNewSignature,cls).__new__(cls, ,
> mm,
> dd)
> def __init__(self, strval):
> , mm, dd = DateChangesNewSignature.str2ymd(strval)
> super(DateChangesNewSignature, self).__init__(, mm,
> dd)
> 
> class DLast(DateChangesNewSignature):
> __metaclass__ = FixClassMethods
> 
> f = Date(2007,07,07)
> print f
> print f.today()
> 
> f2 = DateChangesNewSignature("20070707")
> print f2
> try:
> print f2.today()
> except TypeError, e:
> print str(e)
> print "Uh?"
> 
> 
> f3 = DLast("20070707")
> print f3
> print f3.today()
> 
> 
> I get:
> 
> 2007-07-07 00:00:00
> 2007-08-16 12:57:41.480679
> 2007-07-07 00:00:00
> __new__() takes exactly 2 arguments (9 given)
> Uh?
> 2007-07-07 00:00:00
> 2007-08-16 12:57:41.483104
> 
> 
> --
> Hope this helps,
> Steven
> 
Steven,

Many thanks, I'll try this out tomorrow.

Colin W

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


Re: Pass by reference or by value?

2007-08-16 Thread Steve Holden
Robert Dailey wrote:
> Hi,
> 
> I previously created a topic named "Pass by reference or by value" where 
> I inquired on how python's function parameters work. I received a lot of 
> nice responses, however I'm still confused on the topic. Note that I 
> come from a C++ background to Python, so any comparisons to C++ would be 
> very helpful.
> 
> I ran a few tests. There's two tests in particular I wanted to show you 
> guys:
> 
> myvar = []
> 
> def changeme( param ):
> param.append( "blah" )
> print param
> 
> changeme( myvar )
> 
> print myvar
> 
> The above code yields the following output:
> ['blah']
> ['blah']
> 
> This means that the list passed in was modified by the function.
> 
> Now test case 2:
> 
> myvar = 4
> 
> def changeme( param ):
> param = 5
> print param
> 
> changeme( myvar )
> 
> print myvar
> 
> The above code yields the following output:
> 5
> 4
> 
> This means that the integer passed in was NOT modified by the function.
> 
> 
> Between these two tests, both types passed in are mutable objects. I'm 
> having trouble figuring out what mandates an object to be changed from 
> within a function versus not. What is happening in test case 2 to cause 
> it to not be modified?
> 
> Thanks for reading guys. Hopefully one day I'll understand this lol.
> 
The first thin to realise is that all Python names are just bindings to 
values. In C++ terms you can think of them all as pointers. 
De-referencing is automatic when a value is to be retrieved.


 >>> def changeme( param ):
... param = 3
... print param
...
 >>> myvar = []
 >>> changeme(myvar)
3
 >>> myvar
[]
 >>>

In this case there is no attempt to mutate the argument, the argument 
name is simply bound to another value. Since the argument is a name 
local to the function, this does not result in any change outside the 
function.

In this case the argument is bound to a mutable value, so the call to 
append mutates the object (a list) referenced by the argument.

Unlike C++ and similar languages a variable does not hold a value, it 
holds a pointer to a value. When a list is passed as a function argument 
the reference to the list is copied into the argument. Does this help at 
all?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: advice about `correct' use of decorator

2007-08-16 Thread Steven Bethard
Gerardo Herzig wrote:
> Hi all. I guess i have a conceptual question:
> Im planing using a quite simple decorator to be used as a conditional 
> for the execution of the function. I mean something like that:
> 
> @is_logued_in
> def change_pass():
>bla
>bla
> 
> And so on for all the other functions who needs that the user is still 
> loged in.
> 
> where obviosly the is_logued_in() function will determine if the dude is 
> still loged in, and THEN execute change_pass(). If the dude is not loged 
> in, change_pass() is NOT executed at all. Instead, it will be redirected 
> to the `login' screen.
> 
> Something in my mind tells me that this is not the pythonic way...But i 
> like the idea, so please tell me that im in the right way :)

Django does it almost exactly this way:

http://www.djangoproject.com/documentation/authentication/#the-login-required-decorator

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


Re: Pass by reference or by value?

2007-08-16 Thread Robert Dailey
So immutable objects cannot be modified directly? I guess this means
integers are immutable and the act of assigning to one is a completely new
definition? So if I were to create a class called Integer and give it a
.set() method, this would allow me to create mutable integers, and thus
passing in an object of type class Integer would allow me to modify the
value from inside the function?

On 8/16/07, Steve Holden <[EMAIL PROTECTED]> wrote:
>
> Robert Dailey wrote:
> > Hi,
> >
> > I previously created a topic named "Pass by reference or by value" where
> > I inquired on how python's function parameters work. I received a lot of
> > nice responses, however I'm still confused on the topic. Note that I
> > come from a C++ background to Python, so any comparisons to C++ would be
> > very helpful.
> >
> > I ran a few tests. There's two tests in particular I wanted to show you
> > guys:
> >
> 
> > myvar = []
> >
> > def changeme( param ):
> > param.append( "blah" )
> > print param
> >
> > changeme( myvar )
> >
> > print myvar
> >
> > The above code yields the following output:
> > ['blah']
> > ['blah']
> >
> > This means that the list passed in was modified by the function.
> >
> 
> > Now test case 2:
> >
> > myvar = 4
> >
> > def changeme( param ):
> > param = 5
> > print param
> >
> > changeme( myvar )
> >
> > print myvar
> >
> > The above code yields the following output:
> > 5
> > 4
> >
> > This means that the integer passed in was NOT modified by the function.
> >
> 
> >
> > Between these two tests, both types passed in are mutable objects. I'm
> > having trouble figuring out what mandates an object to be changed from
> > within a function versus not. What is happening in test case 2 to cause
> > it to not be modified?
> >
> > Thanks for reading guys. Hopefully one day I'll understand this lol.
> >
> The first thin to realise is that all Python names are just bindings to
> values. In C++ terms you can think of them all as pointers.
> De-referencing is automatic when a value is to be retrieved.
>
>
> >>> def changeme( param ):
> ... param = 3
> ... print param
> ...
> >>> myvar = []
> >>> changeme(myvar)
> 3
> >>> myvar
> []
> >>>
>
> In this case there is no attempt to mutate the argument, the argument
> name is simply bound to another value. Since the argument is a name
> local to the function, this does not result in any change outside the
> function.
>
> In this case the argument is bound to a mutable value, so the call to
> append mutates the object (a list) referenced by the argument.
>
> Unlike C++ and similar languages a variable does not hold a value, it
> holds a pointer to a value. When a list is passed as a function argument
> the reference to the list is copied into the argument. Does this help at
> all?
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd   http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: advice about `correct' use of decorator

2007-08-16 Thread Gerardo Herzig
Steven Bethard wrote:

>Gerardo Herzig wrote:
>  
>
>>Hi all. I guess i have a conceptual question:
>>Im planing using a quite simple decorator to be used as a conditional 
>>for the execution of the function. I mean something like that:
>>
>>@is_logued_in
>>def change_pass():
>>   bla
>>   bla
>>
>>And so on for all the other functions who needs that the user is still 
>>loged in.
>>
>>where obviosly the is_logued_in() function will determine if the dude is 
>>still loged in, and THEN execute change_pass(). If the dude is not loged 
>>in, change_pass() is NOT executed at all. Instead, it will be redirected 
>>to the `login' screen.
>>
>>Something in my mind tells me that this is not the pythonic way...But i 
>>like the idea, so please tell me that im in the right way :)
>>
>>
>
>Django does it almost exactly this way:
>
>http://www.djangoproject.com/documentation/authentication/#the-login-required-decorator
>
>STeVe
>  
>
Great! So from now on, my idea is labeled as `djangothic' :)
Thanks a lot!

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


Re: Pass by reference or by value?

2007-08-16 Thread Steve Holden
Robert Dailey wrote:
> So immutable objects cannot be modified directly? I guess this means 
> integers are immutable and the act of assigning to one is a completely 
> new definition? 

Correct. A new value is bound to the name or item on the left-hand side 
- remember, all variables are pointers to values, there's no way to 
replace the value of a variable because of the automatic dereferencing. 
And yes, immutable objects can't be modified. At all, period. Hence the 
name.

> So if I were to create a class called Integer and give 
> it a .set() method, this would allow me to create mutable integers, and 
> thus passing in an object of type class Integer would allow me to modify 
> the value from inside the function?
> 
Well, the .set() method wouldn't be called automatically on an 
assignment statement but yes, if you passed an Integer object into your 
function and called its .set() method from inside then it should work.

As long as you get your mutable integer implementation correct, of 
course ;-). I'd suggest delegating everything except the .set() method 
to the underlying integer value.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


Canceling events from COM objects

2007-08-16 Thread Oliver Nelson
I have MapPoint working in Python, and I'm trying to cancel events on 
the map, but I can't seem to make that happen.  I'm responding to the 
events successfully in my panel object.  My code is like this:

global MapPointMod
MapPointMod = 
win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 
0, 1, 0)

class MyPanel(wx.Panel):
 def __init__(self, *args, **kwds):
 # begin wxGlade: MyPanel.__init__
 kwds["style"] = wx.TAB_TRAVERSAL
 wx.Panel.__init__(self, *args, **kwds)
 self.frame = args[0]

 MyMap = MakeActiveXClass(MapPointMod.MappointControl, 
eventObj=self)
 self.window_1 = MyMap(self, -1)
 self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt")
...
...
 def OnBeforeClick(self, Button, Shift, X, Y, Cancel):
 print "tada"


My event fires just fine, but I can't seem to figure out how to cancel 
the event so that mappoint doesn't do its stuff with it...I've tried 
setting Cancel based on the mappoint specs, but it doesn't seem to get 
sent back anywhere...

Any ideas please?

Thanx,

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


Canceling events from COM Objects

2007-08-16 Thread Oliver Nelson
I have MapPoint working in Python, and I'm trying to cancel events on 
the map, but I can't seem to make that happen.  I'm responding to the 
events successfully in my panel object.  My code is like this:

global MapPointMod
MapPointMod = 
win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 
0, 1, 0)

class MyPanel(wx.Panel):
 def __init__(self, *args, **kwds):
 # begin wxGlade: MyPanel.__init__
 kwds["style"] = wx.TAB_TRAVERSAL
 wx.Panel.__init__(self, *args, **kwds)
 self.frame = args[0]

 MyMap = MakeActiveXClass(MapPointMod.MappointControl, 
eventObj=self)
 self.window_1 = MyMap(self, -1)
 self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt")
...
...
 def OnBeforeClick(self, Button, Shift, X, Y, Cancel):
 print "tada"


My event fires just fine, but I can't seem to figure out how to cancel 
the event so that mappoint doesn't do its stuff with it...I've tried 
setting Cancel based on the mappoint specs, but it doesn't seem to get 
sent back anywhere...

Any ideas please?

Thanx,

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


Re: Pass by reference or by value?

2007-08-16 Thread Robert Dailey
Thanks Steve for your explanation. It was very helpful. I think I understand
it now. By the way, by the .set method I meant:

class Integer:
def __init__( self, number=0 ):
   self._int = number

def set( self, number ):
   self._int = number


# later on

mutableInt = Integer( 5 )
def change_me( var ):
var.set( 6 )


Of course, I'd probably use overloaded operators in a more realized example.


On 8/16/07, Steve Holden <[EMAIL PROTECTED]> wrote:
>
> Robert Dailey wrote:
> > So immutable objects cannot be modified directly? I guess this means
> > integers are immutable and the act of assigning to one is a completely
> > new definition?
>
> Correct. A new value is bound to the name or item on the left-hand side
> - remember, all variables are pointers to values, there's no way to
> replace the value of a variable because of the automatic dereferencing.
> And yes, immutable objects can't be modified. At all, period. Hence the
> name.
>
> > So if I were to create a class called Integer and give
> > it a .set() method, this would allow me to create mutable integers, and
> > thus passing in an object of type class Integer would allow me to modify
> > the value from inside the function?
> >
> Well, the .set() method wouldn't be called automatically on an
> assignment statement but yes, if you passed an Integer object into your
> function and called its .set() method from inside then it should work.
>
> As long as you get your mutable integer implementation correct, of
> course ;-). I'd suggest delegating everything except the .set() method
> to the underlying integer value.
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd   http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Canceling events from COM Objects

2007-08-16 Thread Oliver Nelson
I have MapPoint working in Python, and I'm trying to cancel events on 
the map, but I can't seem to make that happen.  I'm responding to the 
events successfully in my panel object.  My code is like this:

global MapPointMod
MapPointMod = 
win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 
0, 1, 0)

class MyPanel(wx.Panel):
 def __init__(self, *args, **kwds):
 # begin wxGlade: MyPanel.__init__
 kwds["style"] = wx.TAB_TRAVERSAL
 wx.Panel.__init__(self, *args, **kwds)
 self.frame = args[0]

 MyMap = MakeActiveXClass(MapPointMod.MappointControl, 
eventObj=self)
 self.window_1 = MyMap(self, -1)
 self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt")
...
...
 def OnBeforeClick(self, Button, Shift, X, Y, Cancel):
 print "tada"


My event fires just fine, but I can't seem to figure out how to cancel 
the event so that mappoint doesn't do its stuff with it...I've tried 
setting Cancel based on the mappoint specs, but it doesn't seem to get 
sent back anywhere...

Any ideas please?

Thanx,

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


How to say $a=$b->{"A"} ||={} in Python?

2007-08-16 Thread beginner
Hi All.

I'd like to do the following in more succint code:

if k in b:
a=b[k]
else:
a={}
b[k]=a

a['A']=1


In perl it is just one line: $a=$b->{"A"} ||={}.

Thanks,
Geoffrey

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


Re: How to say $a=$b->{"A"} ||={} in Python?

2007-08-16 Thread Lawrence Oluyede
beginner <[EMAIL PROTECTED]> wrote:
> I'd like to do the following in more succint code:
> 
> if k in b:
> a=b[k]
> else:
> a={}
> b[k]=a

b.setdefault(k, a)

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to say $a=$b->{"A"} ||={} in Python?

2007-08-16 Thread beginner
On Aug 16, 5:43 pm, [EMAIL PROTECTED] (Lawrence Oluyede) wrote:
> beginner <[EMAIL PROTECTED]> wrote:
> > I'd like to do the following in more succint code:
>
> > if k in b:
> > a=b[k]
> > else:
> > a={}
> > b[k]=a
>
> b.setdefault(k, a)
>
> --
> Lawrence, oluyede.org - neropercaso.it
> "It is difficult to get a man to understand
> something when his salary depends on not
> understanding it" - Upton Sinclair

I am afraid it is not the same. b.setdefault(k, {}) will always create
an empty dict, even if k is in b, as demonstrated in the below code.

b={}
def f(i):
print "I am evaluated %d" % i
return i

b.setdefault('A', f(1))
b.setdefault('A', f(2))
b


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


Re: How to say $a=$b->{"A"} ||={} in Python?

2007-08-16 Thread Carl Banks
On Aug 16, 6:35 pm, beginner <[EMAIL PROTECTED]> wrote:
> Hi All.
>
> I'd like to do the following in more succint code:
>
> if k in b:
> a=b[k]
> else:
> a={}
> b[k]=a
>
> a['A']=1
>
> In perl it is just one line: $a=$b->{"A"} ||={}.
>
> Thanks,
> Geoffrey

Define b as a default dict:

b = defaultdict(dict)
b[k]['A'] = l



Carl Banks

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


Re: Pass by reference or by value?

2007-08-16 Thread Thomas Jollans
On Thursday 16 August 2007, Robert Dailey wrote:
> Hi,
>
> I previously created a topic named "Pass by reference or by value" where I
> inquired on how python's function parameters work. I received a lot of nice
> responses, however I'm still confused on the topic. Note that I come from a
> C++ background to Python, so any comparisons to C++ would be very helpful.

Very short answer:

Think of normal objects as always-pointers. There are no references. param = 5 
sets the local variable "param" (be that of imaginary type int* or int, I 
don't care) to whatever 5 is. This does not call an operator=, this plain 
overwrites the variable.

If you want to change arguments in that way, you can use a list as an ugly 
hack:

def foo(param):
param[0] = 5
print param[0]

a = [4]

foo(a)

yeah, I said ugly. That hack makes sure that a method of the passed object is 
called instead of of the local namespace dict. (please note that I'm throwing 
around abstract concepts without caring about an implementation).

-- 
  Regards,   Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key :
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6


signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to say $a=$b->{"A"} ||={} in Python?

2007-08-16 Thread James Stroud
beginner wrote:
> Hi All.
> 
> I'd like to do the following in more succint code:
> 
> if k in b:
> a=b[k]
> else:
> a={}
> b[k]=a
> 
> a['A']=1
> 
> 
> In perl it is just one line: $a=$b->{"A"} ||={}.


I'm afraid you've asked a non sequiter:

euler 40% cat test.pl

$a=$b->{"A"} ||={} ;
print "$a\n" ;

$b->{"B"} = 0 ;
$a=$b->{"B"} ||={} ;
print "$a\n" ;

$b->{"X"} = 15 ;
$a=$b->{"X"} ||={} ;
print "$a\n" ;

euler 41% perl test.pl
HASH(0x92662a0)
HASH(0x926609c)
15


James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Events in Com Object for Python

2007-08-16 Thread Oliver Nelson
I have MapPoint working in Python, and I'm trying to cancel events on 
the map, but I can't seem to make that happen.  I'm responding to the 
events successfully in my panel object.  My code is like this:

global MapPointMod
MapPointMod = 
win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 
0, 1, 0)

class MyPanel(wx.Panel):
 def __init__(self, *args, **kwds):
 # begin wxGlade: MyPanel.__init__
 kwds["style"] = wx.TAB_TRAVERSAL
 wx.Panel.__init__(self, *args, **kwds)
 self.frame = args[0]

 MyMap = MakeActiveXClass(MapPointMod.MappointControl, 
eventObj=self)
 self.window_1 = MyMap(self, -1)
 self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt")
...
...
 def OnBeforeClick(self, Button, Shift, X, Y, Cancel):
 print "tada"


My event fires just fine, but I can't seem to figure out how to cancel 
the event so that mappoint doesn't do its stuff with it...I've tried 
setting Cancel based on the mappoint specs, but it doesn't seem to get 
sent back anywhere...

Any ideas please?

Thanx,

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


Cancelling events on a COM Object

2007-08-16 Thread Oliver Nelson
I have MapPoint working in Python, and I'm trying to cancel events on 
the map, but I can't seem to make that happen.  I'm responding to the 
events successfully in my panel object.  My code is like this:

global MapPointMod
MapPointMod = 
win32com.client.gencache.EnsureModule("{51C0A9CA-F7B7-4F5A-96F4-43927C6FA50F}", 
0, 1, 0)

class MyPanel(wx.Panel):
 def __init__(self, *args, **kwds):
 # begin wxGlade: MyPanel.__init__
 kwds["style"] = wx.TAB_TRAVERSAL
 wx.Panel.__init__(self, *args, **kwds)
 self.frame = args[0]

 MyMap = MakeActiveXClass(MapPointMod.MappointControl, 
eventObj=self)
 self.window_1 = MyMap(self, -1)
 self.window_1.OpenMap("C:\\TEMP\\GPS_ON.ptt")
...
...
 def OnBeforeClick(self, Button, Shift, X, Y, Cancel):
 print "tada"


My event fires just fine, but I can't seem to figure out how to cancel 
the event so that mappoint doesn't do its stuff with it...I've tried 
setting Cancel based on the mappoint specs, but it doesn't seem to get 
sent back anywhere...

Any ideas please?

Thanx,

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


Re: Cancelling events on a COM Object

2007-08-16 Thread James Stroud
Oliver, wait a while before you panic about your post not getting through!

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >