Re: sum function

2012-10-04 Thread Mike
I get below error

NameError: name 'functools' is not defined

Thanks

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


Re: sum function

2012-10-04 Thread Mike
Thanks Ian for the quick reply.

I get the below error.

NameError: name 'itertools' is not defined

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


Re: sum function

2012-10-04 Thread Mike
On Thursday, October 4, 2012 5:40:26 PM UTC-4, Dave Angel wrote:
> On 10/04/2012 05:29 PM, Mike wrote:
> 
> > I get below error
> 
> >
> 
> > NameError: name 'functools' is not defined
> 
> >
> 
> 
> 
> functools is a module in the standard library. You need to import it.
> 
> 
> 
> import functools
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

I imported functools. Now I get the below error please.


Traceback (most recent call last):
  File "test.py", line 16, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r.itervalues()) 
  File "test.py", line 16, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r.itervalues()) 
AttributeError: 'list' object has no attribute 'itervalues'

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


Re: sum function

2012-10-04 Thread Mike

I agree with you, Ian. Thanks for all the help.  Now I get the below error.

  File "test.py", line 17, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r[0].columns.itervalues())
  File "test.py", line 17, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r[0].columns.itervalues())

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


Re: sum function

2012-10-05 Thread Mike
On Thursday, October 4, 2012 4:52:50 PM UTC-4, Mike wrote:
> Hi All,
> 
> 
> 
> I am new to python and am getting the data from hbase. 
> 
> I am trying to do sum on the column as below
> 
> 
> 
> 
> 
> scanner = client.scannerOpenWithStop("tab", "10", "1000", ["cf:col1"])
> 
> total = 0.0
> 
> r = client.scannerGet(scanner)
> 
> while r:
> 
>   for k in (r[0].columns):
> 
> total += float(r[0].columns[k].value)
> 
>   r = client.scannerGet(scanner)
> 
> 
> 
> print total
> 
> 
> 
> Do you know of better (faster) way to do sum?
> 
> 
> 
> Any thoughts please?
> 
> 
> 
> Thanks

Sorry about that. Here you go

Traceback (most recent call last):
  File "test.py", line 17, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r[0].columns.itervalues())
  File "test.py", line 17, in 
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r[0].columns.itervalues())
IndexError: list index out of range
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum function

2012-10-05 Thread Mike
On Friday, October 5, 2012 9:41:44 AM UTC-4, Ramchandra Apte wrote:
> On Friday, 5 October 2012 19:09:15 UTC+5:30, Mike  wrote:
> 
> > On Thursday, October 4, 2012 4:52:50 PM UTC-4, Mike wrote:
> 
> > 
> 
> > > Hi All,
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > I am new to python and am getting the data from hbase. 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > I am trying to do sum on the column as below
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > scanner = client.scannerOpenWithStop("tab", "10", "1000", ["cf:col1"])
> 
> > 
> 
> > > 
> 
> > 
> 
> > > total = 0.0
> 
> > 
> 
> > > 
> 
> > 
> 
> > > r = client.scannerGet(scanner)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > while r:
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   for k in (r[0].columns):
> 
> > 
> 
> > > 
> 
> > 
> 
> > > total += float(r[0].columns[k].value)
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   r = client.scannerGet(scanner)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print total
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > Do you know of better (faster) way to do sum?
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > Any thoughts please?
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > Thanks
> 
> > 
> 
> > 
> 
> > 
> 
> > Sorry about that. Here you go
> 
> > 
> 
> > 
> 
> > 
> 
> > Traceback (most recent call last):
> 
> > 
> 
> >   File "test.py", line 17, in 
> 
> > 
> 
> > total = sum(float(col.value) for r in iter(next_r, None) for col in 
> > r[0].columns.itervalues())
> 
> > 
> 
> >   File "test.py", line 17, in 
> 
> > 
> 
> > total = sum(float(col.value) for r in iter(next_r, None) for col in 
> > r[0].columns.itervalues())
> 
> > 
> 
> > IndexError: list index out of range
> 
> 
> 
> the variable "r" is an empty list

Here is the actual code.

scanner = client.scannerOpenWithStop("tab", "10", "1000", ["cf:col1"]) 
next_r = functools.partial(client.scannerGet, scanner)
total = sum(float(col.value) for r in iter(next_r, None) for col in 
r[0].columns.itervalues())


Scanner does have rows.

Are we missing something please?

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


Re: sum function

2012-10-05 Thread Mike
I added the print command.

It prints [] when there is no data.

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


Re: sum function

2012-10-05 Thread Mike
Terry,

I am not using the mail client. I am just posting on the site.

Something wrong with this site. When you do individual reply, it does the 
double posting which it shouldn't. See "Ramachandra Apte's" reply. It is posted 
twice too.

Thanks



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


Re: sum function

2012-10-05 Thread Mike
That worked, Ian.

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


Print value from array

2012-11-22 Thread Mike
Hello,
I am noob en python programing,  i wrote a perl script for read from csv but 
now i wish print value but the value must be within double quote and I can not 
do this. 

For example now the output is:

ma user@domain displayName Name SecondName givenName Name sn SecondName cn Name

and i wish

ma "user@domain" displayName "Name Lastname" givenName "Name" sn "SecondName" 
cn "Name"

My script is

#!/usr/bin/python
import csv

with open ('file.csv', 'rb') as f:
reader = csv.reader (f, delimiter=';' )
for row in reader:
mail = row [0]
name = row [1]
lastname = row [2]
name2  = row [1] + ' ' + row [2]

print  'ma ' + mail + ' displayName ' +  name2.title() + ' 
givenName ' + name.title() + ' sn ' + lastname.title() + ' cn ' + name.title()  

#   print '\n'

f.close() 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print value from array

2012-11-22 Thread Mike
El jueves, 22 de noviembre de 2012 16:02:30 UTC-3, Alister  escribió:
> On Thu, 22 Nov 2012 10:44:02 -0800, Mike wrote:
> 
> 
> 
> > Hello,
> 
> > I am noob en python programing,  i wrote a perl script for read from csv
> 
> > but now i wish print value but the value must be within double quote and
> 
> > I can not do this.
> 
> > 
> 
> > For example now the output is:
> 
> > 
> 
> > ma user@domain displayName Name SecondName givenName Name sn SecondName
> 
> > cn Name
> 
> > 
> 
> > and i wish
> 
> > 
> 
> > ma "user@domain" displayName "Name Lastname" givenName "Name" sn
> 
> > "SecondName" cn "Name"
> 
> > 
> 
> > My script is
> 
> > 
> 
> > #!/usr/bin/python import csv
> 
> > 
> 
> > with open ('file.csv', 'rb') as f:
> 
> > reader = csv.reader (f, delimiter=';' )
> 
> > for row in reader:
> 
> > mail = row [0]
> 
> > name = row [1]
> 
> > lastname = row [2]
> 
> > name2  = row [1] + ' ' + row [2]
> 
> > 
> 
> > print  'ma ' + mail + ' displayName ' +  name2.title() + 
> 
> ' givenName '
> 
> > + name.title() + ' sn ' + lastname.title() + ' cn ' + 
> 
> name.title()
> 
> > 
> 
> > #   print '\n'
> 
> > 
> 
> > f.close()
> 
> 
> 
> concatenation is not the python way to build strings
> 
> double quotes can be included in single quoted strings ( & vice Versa)
> 
> try using the string formatting options, something like
> 
> 
> 
> 
> 
> print 'ma "{}" display name "{}" Given Name "{}" sn "{}" cn "{}"'.format
> 
> ((mail,name2.title(),name.title(),lastname.title(),name.title()))
> 
> 
> 
> 
> 
> -- 
> 
> "Plan to throw one away.  You will anyway."
> 
> - Fred Brooks, "The Mythical Man Month"

Thanks Alister , i modify the print structure with your recommendation and is 
solved

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


Problem with print and output to screen

2012-12-11 Thread Mike
Hello, I am learning python and i have the next problem and i not understand 
how fix.
The script is very simple, shows in the terminal the command but, the row is 
divided in two:
Example:
 

/opt/zimbra/bin/zmprov ga u...@example.com
|egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" 
/opt/zimbra/bin/zmprov ga us...@example.com
|egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"

And the correct is: 
/opt/zimbra/bin/zmprov ga u...@example.com |egrep 
"(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"


The script is:

#!/usr/bin/python
import os

for user in open ("email"):
print '/opt/zimbra/bin/zmprov ga ' + user + '|egrep 
"(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" '



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


Re: Problem with print and output to screen

2012-12-11 Thread Mike
El martes, 11 de diciembre de 2012 20:07:09 UTC-3, Joel Goldstick  escribió:
> On Tue, Dec 11, 2012 at 6:00 PM, Dave Angel  wrote:
> 
> 
> On 12/11/2012 05:53 PM, Joel Goldstick wrote:
> 
> > When you read the file line by line the end of line character is included
> 
> > in the result
> 
> >
> 
> > try user[:-1] instead to strip the return from your printed text
> 
> >
> 
> 
> 
> The catch to that is the last line in the file might not have a
> 
> newline.  In that case, we'd be ignoring the last character of the line.
> 
> 
> 
> The .rstrip() method is easy, and for most purposes equivalent.  Few
> 
> text files have trailing whitespace, but many are missing the final
> 
> linefeed.
> 
> 
> 
> Point taken.  Brain freeze.  I forgot about .rstrip.  That is the way to go
> 
> 
> 
> --
> 
> 
> 
> DaveA
> 
> 
> 
> 
> 
> 
> -- 
> Joel Goldstick

Thank you very much, i used  "user.rstrip" and the output is correct . 

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


ElementTree XML parsing problem

2011-04-27 Thread Mike
I'm using ElementTree to parse an XML file, but it stops at the second 
record (id = 002), which contains a non-standard ascii character, ä. 
Here's the XML:











The complaint offered up by the parser is

Unexpected error opening simple_fail.xml: not well-formed (invalid 
token): line 5, column 40


and if I change the line to eliminate the ä, everything is wonderful. 
The parser is perfectly happy with this modification:




I can't find anything in the ElementTree docs about allowing additional 
text characters or coercing strange ascii to Unicode.


Is there a way to coerce the text so it doesn't cause the parser to 
raise an exception?


Here's my test script (simple_fail contains the offending line, and 
simple_pass contains the line that passes).


import sys
import xml.etree.ElementTree as ET

def main():

xml_files = ['simple_fail.xml', 'simple_pass.xml']
for xml_file in xml_files:

print
print 'XML file: %s' % (xml_file)

try:
tree = ET.parse(xml_file)
except Exception, inst:
print "Unexpected error opening %s: %s" % (xml_file, inst)
continue

root = tree.getroot()
records = root.find('records')
for record in records:
print record.attrib['id'], record.attrib['education']

if __name__ == "__main__":
main()


Thanks,

-- Mike --

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


Re: ElementTree XML parsing problem

2011-04-27 Thread Mike

On 4/27/2011 12:33 PM, Hegedüs Ervin wrote:

hello,


I'm using ElementTree to parse an XML file, but it stops at the
second record (id = 002), which contains a non-standard ascii
character, ä. Here's the XML:










The complaint offered up by the parser is


I've checked this xml with your script, I think your locales
settings are not good.

$ ./parse.py

XML file: test.xml
001 High School
002 Universität Bremen
003 River College

(name of xml file is "test.xml")

So, I started change the codepage mark of xml:

  - same result
  - same result
  - same result

and then:
  - gives same error as you
described.

Try to change XML encoding.


a.


Thanks, Hegedüs and everyone else who responded. That is exactly it - 
I'm afraid I probably missed it in the docs because I was searching for 
terms like "unicode" and "coerce." In any event, that solves the 
problem. Thanks!


-- Mike --


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


Re: ElementTree XML parsing problem

2011-04-27 Thread Mike

On 4/27/2011 12:24 PM, Neil Cerutti wrote:

On 2011-04-27, Mike  wrote:

I'm using ElementTree to parse an XML file, but it stops at the
second record (id = 002), which contains a non-standard ascii
character, ?. Here's the XML:










The complaint offered up by the parser is

Unexpected error opening simple_fail.xml: not well-formed
(invalid token): line 5, column 40


It seems to be an invalid XML document, as another poster
indicated.


and if I change the line to eliminate the ?, everything is
wonderful. The parser is perfectly happy with this
modification:



I can't find anything in the ElementTree docs about allowing
additional text characters or coercing strange ascii to
Unicode.


If you're not the one generating that bogus file, then you can
specify the encoding yourself instead by declaring an XMLParser.

   import xml.etree.ElementTree as etree
   with open('file.xml') as xml_file:
 parser = etree.XMLParser(encoding='ISO-8859-1')
 root = etree.parse(xml_file, parser=parser).getroot()



Thanks, Neil. I'm not generating the file, just trying to parse it. Your 
solution is precisely what I was looking for, even if I didn't quite ask 
correctly. I appreciate the help!


-- Mike --

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


nosend missing in suds 0.4?

2011-05-31 Thread Mike
Looks like the nosend attribute is not available in 0.4. Any reason
for this? Any plans to add it back and what is the most recent release
that does have the nosend option?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: good way to avoid recomputations?

2016-04-15 Thread Mike
On Tuesday, April 5, 2016 at 4:54:50 PM UTC-4, Maurice wrote:
> Hi. I working on a project where I have 5 scripts loading the same file at 
> the very beginning so I would like to know the best way I can get this file 
> without having to compute it 5 times.
> 
> I also perform, in all the scripts, a list comprehension using this file that 
> takes 30s to run. Would be cool to always have access to it as well.
> 
> Cheers

You can load the file and then fork ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Any better way for this removal?

2020-11-07 Thread Mike
Use .split() to split the string on the character and then use .join() to 
rejoin the first 2 tokens

tokens = text.split(“,”)
new_string = “,”.join(tokens[:2])

On Sat, Nov 7, 2020, at 1:46 PM, Bischoop wrote:
> 
> 
> So I was training with slicing. 
> Came to idea to remove text after second occurence of character, below
> is how I've figured it out, I know if it works it good but how you
> guys would made it in more pythonic way?
> 
> text = "This is string, remove text after second comma, to be removed."
> 
> k=  (text.find(",")) #find "," in a string
> m = (text.find(",", k+1)) #Find second "," in a string
> new_string = text[:m]
> 
> print(new_string)
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Telephony project

2005-09-27 Thread Mike

I was able to do something like this in Python a while back. You'll need one 
of:
(a) A telephone line dialer/monitor & DTMF I/O board that works through the 
serial port, and a phone audio tap that mixes the soundcard I/O to the phone
(b) A TAPI-compliant modem that does everything you need
(c) A digital POTS phone that is controllable through serial, USB or your 
LAN, or a TAPI interface.
(d) VOIP software and service than uses SIP, etc. (I found this I found 
this: 
http://softphones.globaliptel.com/(c50kru45yksjek55xr2b5g45)/_Pages/NoFrames/PageBuilder.aspx?content=4214134c0c4f416982e844bcd86b2955,
 
but am in no way endorsing it. Also check out http://www.sipfoundry.org/)

I used method (a) -- (b) tends to be a pain (as most OEM TAPI modems have 
some fatal flaw or three...) and (c/d) may be more possible now that before. 
I used voice reco on the input side rather then DTMF, but I was doing it 
from local phone exensions on the same loop, not for outside calls, and not 
for the elderly, so DTMF is probably better anyway. (If you need to know the 
exact hardware I used, I can find out.)

The other option is to not have your own hardware at all and use a 
service -- there are companies provide web services that let you 
write/generate markup (VoiceXML or other) to make the calls, wait for DTMF 
or voice input, etc. (Though I had trouble Googling one at the moment - 
there were more a few years ago...)

m



"Roger" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>  "CheckOn" is the working name for my project.  Our church
> community has many elderly who are at home but close to assisted living
> placements.  Many do not have family and rely on  volunteer caretakers
> and lunch providers for their socialization.  We are trying to make
> phone contact with these members to check on their needs, wellbeing,
> and ability to take care of themselves.  In sharing that information
> with other denominations in our city, we discovered that others were
> having identical issues.  The numbers are larger than we anticipated.
> Thus the project.  Thanks for your interest.
> 


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


Re: Perl's documentation come of age

2005-09-27 Thread Mike

"Steve Holden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Mike wrote:
>> "Steve Holden" <[EMAIL PROTECTED]> wrote in message 
>> news:[EMAIL PROTECTED]
>>
>>>Jim Hugunin's keynote speech at this year's PyCon was accompanied by a 
>>>projection if his interactive interpreter session, and I know I wasn't 
>>>alone in finding this a convincing example of Microsoft's (well, Jim's, 
>>>really) full integration of Python into the .net framework.
>>>Steve Holden   +44 150 684nin 7255  +1 800 494 3119
>>>Holden Web LLC www.holdenweb.com
>>>PyCon TX 2006  www.pycon.org
>>
>>
>> Which .Net integreation technology are you speaking of?
>> BTW, PyCon.org seems to be down (at least not reachable from here at the 
>> moment.)
>>
>> thanks
>>
>>
> I spoke of IronPython, which generates CLR code.
>
> I believe pycon.org will shortly re-emerge as a redirect to a subdirectory 
> of the python.org domain, but I'm no longer in charge, so this may not be 
> accurate. RSN ...

Glad to see this cool project is still up and running. I downloaded it and 
ran some examples without incident.

Looks like I'm having a bad week w/these URLs, because now I'm not able to 
access http://lists.ironpython.com/listinfo.cgi/users-ironpython.com .
I was hoping to get at the archives to see if I can glean more info before I 
asked too many questions...

Is there any way at the moment to get all the "niceities" w.r.t. development 
w/I.P.? (E.g., code completion, source debugging, etc.)
I assume a Visual Studio plug-in would be natural, but I'm not sure it's 
around yet.

thanks,
m




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


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


Re: Perl's documentation come of age

2005-09-27 Thread Mike

"Mike" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Looks like I'm having a bad week w/these URLs, because now I'm not able to 
> access http://lists.ironpython.com/listinfo.cgi/users-ironpython.com .
> I was hoping to get at the archives to see if I can glean more info before 
> I asked too many questions...

It's back up... 


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


Replacing utf-8 characters

2005-10-05 Thread Mike
Hi, I am using Python to scrape web pages and I do not have problem 
unless I run into a site that is utf-8.  It seems & is changed to & 
when the site is utf-8.

If I try to replace it with .replace('&','&') it for some reason 
does not replace it.

For example: http://today.reuters.co.uk/news/default.aspx

The url in the page looks like this

http://today.reuters.co.uk/news/NewsArticle.aspx?type=topNews&storyID=2005-10-05T140937Z_01_MCC423599_RTRUKOC_0_UK-BRITAIN-CONSERVATIVES.xml

However when I pull it into python the URL ends up looking like this 
(notice the & instead of just & in the URL)

http://today.reuters.co.uk/news/newsArticle.aspx?type=businessNews&storyID=2005-10-05T094354Z_01_MOL530411_RTRUKOC_0_UK-CONSTRUCTION-BPB-STGOBAIN.xml

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


Re: Replacing utf-8 characters

2005-10-05 Thread Mike
For example this is what I am trying to do that is not working.

The contents of link is the reuters web page, containing

"/news/newsArticle.aspx?type=businessNews&amp;storyID=2005-10-05T151245Z_01_HO548006_RTRUKOC_0_UK-AIRLINES-BA.xml"

link = link.replace('&amp;','&')

But if I now view the the contents link it shows it the same as when it 
was assigned.




Richard Brodie wrote:
> "Mike" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> 
> 
>>However when I pull it into python the URL ends up looking like this
>>(notice the & instead of just & in the URL)
>>
>>Any ideas?
> 
> 
> Some code would be helpful: the "&" is in the page source to start
> with (which is as it ought to be). What are you using to parse the HTML?
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing utf-8 characters

2005-10-05 Thread Mike
Steve Holden wrote:

>>>
> You must be doing *something* wrong:
> 
>  >>> link = 
> "/news/newsArticle.aspx?type=businessNews&storyID=2005-10-05T151245Z_01_HO548006_RTRUKOC_0_UK-AIRLINES-BA.xml"
>  
> 
>  >>> link = link.replace('&','&')
>  >>> link
> '/news/newsArticle.aspx?type=businessNews&storyID=2005-10-05T151245Z_01_HO548006_RTRUKOC_0_UK-AIRLINES-BA.xml'
>  
> 
>  >>>
> 
> regards
>  Steve

What you and I typed was ascii. The value of link came from importing 
that utf-8 web page into that variable.  That is why I think it is not 
working.  But not sure what the solution is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing utf-8 characters

2005-10-05 Thread Mike
In playing with this I found link.replace does work but when I use

link.replace('&','&')

it replaces it with & instead of just &.  link.replace is working 
for me since if I changed the second option from & to something else I 
see the change.

So it seems link.replace() function reads whether the first option is 
utf-8 and converts the second option automatically to utf-8?  How do I 
prevent that?

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


os.access with wildcards

2005-10-06 Thread mike
i'd like to use

   os.access(path,mode)

where path may contain linux style wildcards.
i've failed so far.
my workaround is the bash command.

   os.system('[ -e %s ]' % fn )

any suggestions?

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


Re: os.access with wildcards

2005-10-07 Thread mike
thanks Leif.  poor question on my part.

I had been using

glob.glob(path)==[]

and was looking for something more readable, hence

os.system('[ -e %s ]' % path )

but that doesn't seem like a good idiom for crossplatform.

I thought there may either be a way to escape the wildcards, or an
alternative to os.access, or 

any othr ideas?

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


Re: os.access with wildcards

2005-10-07 Thread mike
thanks Leif.  poor question on my part.

I had been using

glob.glob(path)==[]

and was looking for something more readable, hence

os.system('[ -e %s ]' % path )

but that doesn't seem like a good idiom for crossplatform.

I thought there may either be a way to escape the wildcards, or an
alternative to os.access, or 

any other ideas?

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


Re: os.access with wildcards

2005-10-07 Thread mike
Test for the existence of one or more matches of the wildcard
expression.

For example:

Are there any files that begin with 2005?

This doesn't work (wish it did):

 os.access('2005*',os.F_OK)

However, these work arounds do the job:

glob.glob('2005*')==[]

as does this bash command:

os.system('[ -e %s ]' % path )

The 1st is not very readable and the 2nd has portability issues.

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


Re: os.access with wildcards

2005-10-07 Thread mike
Test for the existence of one or more matches of the wildcard
expression.

For example:

Are there any files that begin with 2005?

This doesn't work (wish it did):

 os.access('2005*',os.F_OK)

However, these work arounds do the job:

glob.glob('2005*')==[]

as does this bash command:

os.system('[ -e  2005* ]' )

The 1st is not very readable and the 2nd has portability issues.

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


Re: os.access with wildcards

2005-10-07 Thread mike
dude, you are the sap that wrote "it's not clear". get a life.

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


Re: os.access with wildcards

2005-10-07 Thread mike
No need to apologize for continuing to waste your
time, self.plonk.  Get a life, though, and you'll be happier.

As to your question, well, not before you apologize for
thread crapping.

As for your possible solutions, if you consider any
of yours to be "readable", then i have no interest in
coding with you.

And for

if glob.glob(path): 

I had already posted that work around.

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


Re: os.access with wildcards

2005-10-07 Thread mike
Thanks Mike.  Would there be an idiom using "is"?
somethng like

glob.glob('2005*) is not Empty

I have not figured out what to put on the right hand
side of "is"

I guess, for readability, nothing has come up that
seems _great_.  One last effort would be to hide
the code behind a method, and use something
readable to name the method.

Thanks also for the link to amaya.  The compile is 
running now :)

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


Re: os.access with wildcards

2005-10-07 Thread mike
Hi Dan,

It works, it's elegant, and it uses python strengths.

I guess I have to settle the question of who my audience is. That is
who do I want to make it readable for.

All the solutions so far require some python specific knowledge, and
there are some which are horendous even at that.  Perhaps less
dependency in this reagrd, the better.  Perhaps not.

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


Re: os.access with wildcards

2005-10-08 Thread mike
ugly. i guess this thread shows that you are clueless regarding your
thread crapping.

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


Re: os.access with wildcards

2005-10-16 Thread mike






 os.path.exists()







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


several interpreters and suspend script

2005-10-24 Thread Mike
Hello All,

I'm working ( and a beginner ) with mixing Python scripting and C++.

And I need some little help.  :)
I've searched on the net, but found no answer. So I ask you directly.

Globally, I'd like to do 2 things.

The first, when I'm in the program, I call a script, which call a function 
to open a window.
And when the window is opened the script should stop / wait, until the 
window closes, and then continue.
Does any function exists to do this ?

#-
import MyModule

def ok_cb():
global w
MyModule.Warning_All( "closing window" )
w.Close() #after here, the script should continue

#create the window
w = MyModule.cPythonWindow( "win", U"win", 0 )

#add some buttons, and when we push one, the function ok_cb is called
w.AddActionButton( "ok", "OK", ok_cb )
w.AddIntegerButton( "int", "Nb", 2541, ok_cb )

#open the window
w.Open() #we should stay here until the callback ends (when we push a 
button) and the window close

#it should show this message when the window closes and not directly 
after the window is created
MyModule.Warning_All( "exiting script" )
#-

The second problem ( which is in relation with the first ) is when we have 2 
non-modal windows, at the same time.
If the 2 scripts stops/are suspended, all the variables in the scripts must 
be totally independent.
So, I'd like that the 2 "spaces" of these scripts are independent.
I wanted to use the Py_NewInterpreter() but it failed in 
PyThreadState_Swap() with this error : "PyFatalError("Invalid thread state 
for this thread");".
So I use 2 dictionaries for each script, but is it sufficient?
What about the call stack ? Where/how is it saved ?

//-
class cPython
{
public:
virtual ~cPython();
cPython();
public:
int Run( const char* iArgs );

void Module( const char* iModuleName, PyMethodDef* iModuleMethod );
void Dictionary( const char* iModuleName );

private:
PyObject*  mMainModule;
PyObject*  mGlobalDictionary;
PyObject*  mLocalDictionary;
};
void
cPython::Module( const char* iModuleName, PyMethodDef* iModuleMethod )
{
mMainModule = Py_InitModule( iModuleName, iModuleMethod );
PyDict_Merge( PyModule_GetDict( mMainModule ), PyModule_GetDict( 
PyImport_AddModule( "__main__" ) ), true );
}
void
cPython::Dictionary( const char* iModuleName )
{
mGlobalDictionary = PyDict_Copy( PyModule_GetDict( mMainModule ) );
PyDict_SetItemString( mGlobalDictionary, iModuleName, mMainModule );

mLocalDictionary = PyDict_Copy( PyModule_GetDict( mMainModule ) );
}
int
cPython::Run( const char* iArgs )
{
PyObject* run_string = PyRun_String( iArgs, Py_file_input, 
mGlobalDictionary, mLocalDictionary );
Py_XDECREF( run_string );
return 0;
}


cPython pyt;
pyt.Module( L"MyModule", sgMethods ); //create the module "MyModule"
InitPythonProject( pyt.Module() );  //add the "class" project in the 
module "MyModule"
InitPythonLayer( pyt.Module() );  //add the "class" layer in the module 
"MyModule"
InitPythonWindow( pyt.Module() );  //add the "class" window in the 
module "MyModule"
pyt.Dictionary( L"MyModule );   //create the 2 dictionary

pyt.Run( L"MyPath/MyFile.py" );
//-

If I create more python objects, the dictionaries are different but not the 
module( there is no copy of the module for the next python object ), right?
And can this make problems for globals variables or callstack for each 
suspended script ?

Here, that's all  :)

So, if you have any suggestions ( or even solutions ).

Thanks for reading

Regards


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


Re: Making immutable instances

2005-11-23 Thread Mike

"Ben Finney" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Howdy all,
>
> How can a (user-defined) class ensure that its instances are
> immutable, like an int or a tuple, without inheriting from those
> types?
>
> What caveats should be observed in making immutable instances?

IMHO, this is usually (but not always) a mistake. (If you're programming a 
missle guidance system, or it makes your program go faster it's not a 
mistake :))
So are PRIVATE, CONST (all types), SEALED, FINAL, etc -- even the best 
programmer doesn't foresee what a user will want to do to make best use of 
his components, and many a time I've been annoyed (in Java and MS 
frameworks) by not being able to access/modify/subclass a member/class that 
I know is there because it has to be there (or because I can see it in the 
debugger), but it's not accessable because the programmer was overly clever 
and had been to OOP school.  A fine-grained capability architecture married 
to the language and runtime where I can declare my own level cleverness to 
override the programmer's would be nice, but I think Python's voluntary 
DoThis, _DoThisIfYouReallyHaveTo, and __You'dBetterKnowWhatYou'reDoing__ 
approach is a better way to go than the undefeatable keyword approach.

m

>
> -- 
> \ "Love is the triumph of imagination over intelligence."  -- |
>  `\  Henry L. Mencken |
> _o__)  |
> Ben Finney 


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


Re: Making immutable instances

2005-11-24 Thread Mike

"Giovanni Bajo" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Mike wrote:
>
>>> How can a (user-defined) class ensure that its instances are
>>> immutable, like an int or a tuple, without inheriting from those
>>> types?
>>>
>>> What caveats should be observed in making immutable instances?
>>
>> IMHO, this is usually (but not always) a mistake. (If you're
>> programming a missle guidance system, or it makes your program go
>> faster it's not a mistake :))
>> So are PRIVATE, CONST (all types), SEALED, FINAL, etc -- even the best
>> programmer doesn't foresee what a user will want to do to make best
>> use of his components, and many a time I've been annoyed (in Java and
>> MS frameworks) by not being able to access/modify/subclass a
>> member/class that I know is there because it has to be there (or
>> because I can see it in the debugger), but it's not accessable
>> because the programmer was overly clever and had been to OOP school.

> There's a big difference. An immutable object has a totally different 
> semantic,
> compared to a mutable object. If you document it to be immutable, and 
> maybe
> even provide __eq__ /__hash__, adding attributes from it is surely an user 
> bug.
> And surely a bug for which I'd expect an exception to be raised.

Why is it "surely" a bug?  It is arguable whether adding new attributes (vs. 
changing those that are already there) is, in fact, mutation.
How will adding user attibutes that your code knows nothing about break the 
contracts you have specified?
If __hash__/__eq__ does not look at the new attributes, all the better - as 
these attributes are just "along for the ride". (But if the hash reflected 
into all attrs, things would indeed break.)
Personally, adding attributes to existing objects would not be my preferred 
programming style, epsecailly in a langauge like Python with rich and 
easy-to-use associative data structures, but sometimes it's the quickest or 
only way to get something done -- if you are unwilling (or more likely, 
unable) to modify all the levels of method signatures required to pass new 
information about an object/state along.
I can see how a compile-time *warning* would be of value to show it is not 
the *desired* usage pattern in the eyes of the component programmer, but 
beyond that, why get in the way? Python is not Java or any other language --  
sometimes I don't like the total dynamicity either (I'd like optional types 
and/or type-inference), but it is what it is.

> Sometimes, I play with some of my objects and I have to go back and check
> documentation whether they are immutable or not, to make sure I use the 
> correct
> usage pattern. That's fine, this is what docs are for, but couldn't Python 
> give
> me some way to enforce this so that, if I or some other dev do the 
> mistake, it
> doesn't go unnoticed?

It sounds like what you may want are opaque objects where you can control 
access better -- if that's so, keep them all hidden, and just pass back a 
handle or proxy - you could always implement restrictred/readonly or 
copy-on-write semantics. (If there isn't one already, auto-proxy generation 
for this sort of thing sounds like a fun python cookbook recipe...)

> -- 
> Giovanni Bajo




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


Re: Making immutable instances

2005-11-24 Thread Mike

"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Op 2005-11-24, Mike schreef <[EMAIL PROTECTED]>:

[...snip...]

>> ...but I think Python's voluntary
>> DoThis, _DoThisIfYouReallyHaveTo, and __You'dBetterKnowWhatYou'reDoing__
>> approach is a better way to go than the undefeatable keyword approach.
>
> I disagree.
>
> Suppose I have the following code.
>
> from module import __take_care__
>
> __private_detail__ = ...
>
> I now have two variable that are flaged the same way, but they are not.
>
> __take_care__ is a private variable from an other module which I should
> use with extreme care not to break the other package.
>
> __private_detail__ on the other hand is just keeping private data for
> my own module, which I should care about as just any other variable
> in my module. It are other modules that should take special care
> if they should choose to import this variable.

If you just import the module and use __private_detail__ vs. 
module.__take_care__ -- that solves that problem :)

>
> That is why I don't think the underscore prefixes are very usefull.
> They constantly flag to take care with a specific variable, while
> that variable is nothing special within the module itself.

I didn't say that the methods used were perfect or fully expressive, but 
just in the right direction.
Maybe there should be a few more variations, and they should be documented 
and blessed, and *tools* can honor them as they see fit. (Different syntax 
hilighting, lint checking, etc.)

m

>
> -- 
> Antoon Pardon 


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


Re: Making immutable instances

2005-11-24 Thread Mike

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Mike Meyer wrote:
>> "Giovanni Bajo" <[EMAIL PROTECTED]> writes:
>> > Mike Meyer wrote:
>> >> Note that this property of __slots__ is an implementation detail. You
>> >> can't rely on it working in the future.
>> > I don't "rely" on it. I just want to catch bugs in my code.
>>
>> I certainly hope you're not relying on it to catch bugs. You should do
>> proper testing instead. Not only will that catch pretty much all the
>> bugs you mention later - thus resolving you of the need to handcuff
>> clients of your class - it will catch lots of other bugs as well.
>>
> That is an ideal case and we all know the real world is not ideal or
> every program would be bug free. And I don't think anyone would solely
> relies on the language feature for spotting bugs. Whether this kind of
> guard is useful is another story.

This is a case where the *language* should be expressive as possible, and 
the *tools* surrounding it should be of more help.
Have I ever mistyped a python variable and introduced a bug? -- many times, 
and it's really annoying. It's a fault that there's no tool that realizes 
that "positon" looks a hell of a lot like "position", more than it's the 
compiler's fault to make such an assumption, because the compiler can't 
"close the loop" with the user, but the tool can. (Or my fault for not using 
such a tool - I know there's pylint, etc.) 


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


Re: Software keyboard

2005-11-24 Thread Mike

You need to call keybd_event which is (or was in win3.x - win95 at least) in 
USER32.DLL.

Simulate return keypress:
keybd_event(VK_RETURN,0,0,0);
keybd_event(VK_RETURN,0,KEYEVENTF_KEYUP,0);

Google turned this up: 
http://www.howtodothings.com/viewarticle.aspx?article=395
Note: This is old stuff -- you'll need to handle different versions of 
windows where that DLL and API are rennamed -- I beleive it is now 
SendInput.

SendMessage and Windows hooks can also work, but not as well in all 
circumstances.

If you feel nervous about programming this, you can probably find/buy a COM 
component that will do this and call it from Python that way.

But, this would seem to fit the bill out-of-the-box: 
http://rutherfurd.net/python/sendkeys/index.html

m


"maxxx_77" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello. I'm a newbye of Python.
> I'm looking for a way of coding a virtual keyboard similar to the one
> that comes with Windows (Accessories -> Accessibility -> On Screen
> Keyboard).
> What I would like to do is make one which is a lot larger and add
> transparency to it.
> I've a first version in which I used TKinter and Pythonwin.
> Can anyone provide me with a snipet of code which would explain how to
> send characters to other applications?
> The first difficulty that I have is to find which application is active
> and has the focus. I think that my keyboard application must be
> modeless and cannot receive the focus. But how?
> Please help me.
> Bye.
> 


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


This Program Realy Works

2005-01-06 Thread MIke
MAKE LOTS OF MONEY QUICKLY, GUARANTEED 100%, NO SCAM! 

Turn 6.00 into 42,000! This is true!! Read this carefully to find out 
how!! 

READING THIS WILL CHANGE YOUR LIFE! 
I found this on a bulletin board and decided to try it. A little while back, I 
was browsing through newsgroups, and came across an article similar to this 
that said you could make thousands of cash within weeks with only an initial 
investment of .00! So I thought, "Yeah right, this must be a scam", but like 
most of us, I was curious, so I kept reading. 

Before you get skeptical, just take a few minutes to finish reading. 

HERE'S HOW IT WORKS 
WITH THIS PLAN, YOU REALLY CAN MAKE TONS OF TOTALLY LEGAL, FAST AND EASY CASH 
MONEY!! IT WORKS!!! BUT YOU HAVE TO FOLLOW IT CAREFULLY FOR IT TO WORK 
CORRECTLY AND IN YOUR FAVOR WITH ALL THE MONEY YOU ARE GONNA MAKE, YOU WILL 
SOON GET EVERYTHING YOU'VE ALWAYS DREAMED OF 

ALL YOU DO IS...
All you do is send $1.00 to each of the 6 names and address stated in the 
article. You then place your own name and address in the bottom of the list at 
#6, and post the article in at least 200 newsgroups. (There are thousands.) No 
catch, that was it . So after thinking it over, and talking to a few people 
first, I thought about trying it. I figured, what have I got to lose except 6 
stamps and 6.00, right? Like most of us I was a little skeptical and a little 
worried about the legal aspects of it all. So I checked it out with the U.S. 
Post Office (1-800-725-2161) and they confirmed that it is indeed legal! 

AND THEN GUESS WHAT...
Then I invested the measly 6.00. Well, GUESS WHAT!!... Within 7 days, I started 
getting money just kept coming in. In my first week, I made about 25. By the 
end of the second week I had made a total of over 1,000! In the third week I 
had over 10,000 and it's still growing. This is now my fourth week and I have 
made a total of just over 42000, and it's still coming in rapidly. It's 
certainly worth 6. and 6 stamps. By the way, I have spent more than that on the 
lottery in the last month!! Let me tell you how this works and most 
importantly, why it works also, make sure you print a copy of this article 
NOW, So you can get the information off of it, as you need it. 

SO LET'S GET STARTED AND SEE WHAT HAPPENS

STEP 1: 
Get 6 separate pieces of paper and write the following on eash piece of paper, 
"PLEASE PUT MY NAME ON YOUR MAILING LIST." Also, be sure to include your name 
and address. Now, get 6 U.S. $1.00 bills and place ONE inside EACH of the 6 
pieces of paper so the bill will not be seen through the envelope, to prevent 
thievery. Next, place one paper in each of the 6 envelopes and seal them. You 
should now have 6 sealed envelopes, each with a piece of paper stating the 
above phrase, your name and address email , and a $1.00 bill. What you are 
doing is creating a service by this. THIS IS ABSOLUTELY LEGAL! 

STEP 2 :

Mail the 6 envelopes to the following addresses: 

#1 John Christensen 5446 Santa Barbara Sparks, NV 89436
#2 Randall Hines 22 Stature Dr. Newark DE 19713
#3 Mike Sharrer 921 West State St. Coopersburg PA 18036
#4 Travis Montgomery 2211 Elmers Lane Norfolk NE 68701
#5 James Adair the third 22 Over Rd. Feasterville PA 19053
#6 Michael Lescault 123 Rhode Island Ave. Pawtucket, RI. 02860

STEP 3:
Now take the #1 name off the list that you see above, move the other names up 
(6 becomes 5, 5 becomes 4, etc.) and add YOUR Name as number 6 on the list. 

STEP 4: 
Change anything you need to, but try to keep this article as close to original 
as possible. If you do not live in the U.S. or there is a foreign address, you 
must put an international stamp on your envelopes. Now, post your amended 
article to at least 200 newsgroups. ( I think there are close to 24,000 groups 
in all.) All you need is 200, but remember, the more you post, the more money 
you make!! 


DIRECTIONS FOR POSTING TO NEWSGROUP BULLETINS
STEP 1: You do not need to re-type this entire letter to do your own posting. 
Simply put you cursor at the beginning of this letter and drag your cursor to 
the bottom of this letter. Then select 'copy' from the edit menu. 
This will copy the entire letter into the computer's temporary memory. 

STEP 2: Open a blank 'notepad' or word processor file and place your cursor at 
the top of the blank page. From the 'edit' menu select 'paste'. This will paste 
a copy of the letter into notepad so that you can add your name to the list. 

STEP 3: Save your new notepad file as a *.txt file. If you want to do your 
postings in different sittings, you'll always have this file to fo back to. 

STEP 4: Use your Internet provider and search engines to find various 
newsgroups (on-line forums, message boards, chat sites, discussions). 

STEP 5: Visit these message boards and post this article as a new message by 
higlighting the text of this l

is extending an object considered acceptable usage?

2005-01-24 Thread mike
i have an Item which belongs to a Category, so Item has:
- item.categoryId, the database primary key of its Category
- item.category, a reference to its Category.  this null unless i need a 
reference from item to its Category object, in which case i call 
setCategory(category)

sometimes i want a list of categories, and from each i want to be able 
to access a list of its items.  in this case is it considered acceptable 
to just create a list of those items and assign it as a property of 
their category?  eg:

  category.items = listOfItems
this packages everything up into a hierarchy and is more convenient to 
use, especially in Cheetah templates, but requries modifying the 
structure of the object, which bothers me (probably for some 
subconscious java-related reason).

the alternative might be to create a dictionary that keys the lists of 
items on their category:

  items = {}
  items[category.id] = listOfItems
this feels less "controversial" to me, but requires extra objects and 
house-keeping.

thanks - just curious if there were arguments one way or the other.
--
http://mail.python.org/mailman/listinfo/python-list


py.dll for version 2.2.1 (Windows)

2005-01-28 Thread mike
Just recently, my virus checker detected what it called a Trojan Horse
in the py.dll file in the python22 folder.  Installation is version
2.2.1 and I think that it came installed when I bought the PC in
October 2002.

Does anyone know where I can get a copy of the py.dll file from version
2.2.1 for Windows (XP) ?

I looked at www.python.org and do not see a py.dll file in the
self-installation or .tgz versions of 2.2.1 that are posted.
Thanks !

  Mike

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


Microsoft Visual C++ and pyton

2005-01-30 Thread mike
Hi,
I am new with python.  Is it possible to have an MFC application and
develop some module using python? what are the steps in doing this? can
anybody give me a url or some documentation for this.. thanks..

mike

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


Re: Microsoft Visual C++ and pyton

2005-01-31 Thread mike
Thanks Chris..
I was also advised to build the python core (pythoncore.vcproj) with my
C++ program. By that way I would not have to load the python core
anymore during runtime. Is this a good approach?
I am currently using VC++ 7 and python 2.4.
- mike

Christopher De Vries wrote:
> On Sun, Jan 30, 2005 at 03:12:06PM -0800, mike wrote:
> > I am new with python.  Is it possible to have an MFC application
and
> > develop some module using python? what are the steps in doing this?
can
> > anybody give me a url or some documentation for this.. thanks..
>
> It is possible to embed python in a C or C++ application, enabling
you to call
> python functions from C. I would recommend reading "Extending and
Embedding the
> Python Interpreter" at http://docs.python.org/ext/ext.html for more
> information. If you are currently using Visual C++ 6.0, either stick
with
> Python 2.3 or read this:
http://www.vrplumber.com/programming/mstoolkit/ to
> learn how to build extensions for python 2.4 with the free VC++
toolkit
> compiler. If you are already using version 7 of the Microsoft C++
compiler then
> you should have no problems with Python 2.4.
>
> I usually do not embed the interpreter, but I have written some
extension
> modules... well, I should say I have used SWIG (http://www.swig.org/)
to create
> wrappers around some C libraries. For information (read: rants) on
extending
> versus embedding see
http://twistedmatrix.com/users/glyph/rant/extendit.html
> and http://c2.com/cgi/wiki?EmbedVsExtend .
>
> You can also use win32 python extensions to make your module
available through
> COM, but I don't know anything about that.
> 
> Chris

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


Re: python object model diagram

2005-09-09 Thread Mike

I think he's looking for diagrams of the batteries-included modules and 
classes.
My guess is that he thinks there's a set of "framework" classes that is a 
lot deeper and class-ier than it is, similar to what you'd find in C++, C#, 
Java, etc.

So, OP - who won the guessing game :)

m

"gene tani" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I think he's looking for tidy pictures of how metaclasses and
> descriptors interact with your classes and instances at compile- &
> runtime, something like that (which I haven't seen)
>
> There's pictures of the class hierarchy for C and j-python:
>
> http://www.brpreiss.com/books/opus7/html/page114.html
> http://www.jython.org/docs/javadoc/overview-tree.html
>
> , there's pictures of method resolution order in Python Nutshell, (but
> I don't think that's what he's looking for.)
>
> Ara.T.Howard wrote:
>> anyone out there know where i might find a python object model diagram?
>>
> 


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


Re: Perl's documentation come of age

2005-09-22 Thread Mike

"Steve Holden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Jim Hugunin's keynote speech at this year's PyCon was accompanied by a 
> projection if his interactive interpreter session, and I know I wasn't 
> alone in finding this a convincing example of Microsoft's (well, Jim's, 
> really) full integration of Python into the .net framework.
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.pycon.org

Which .Net integreation technology are you speaking of?
BTW, PyCon.org seems to be down (at least not reachable from here at the 
moment.)

thanks


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


NEED MONEY FOR FAMILY MATTERS

2005-02-28 Thread mike
HI
I WAS A MARINE MECHANIC working boat engines for 20 years and now I have
started making money for the rest of my life after i got into my own business
but I wish I had started many years ago, check it out for yourself
you'll be HAPPY you did. This site changed my life and my families
and it will change yours.

COPY AND PAST THIS SITE
http://www.mach90.com/pre.asp?username=mad4701
-- 
http://mail.python.org/mailman/listinfo/python-list


help running python in a limited interpreted environment

2004-12-02 Thread Mike
We have a large c++ program that runs under Windows NT Embedded to
control an instrument.  That program has been written to run external
python scripts.  The computer where this code runs does not and cannot
have a full python installation.  It ONLY has the pythonNN.dll file
that comes with a full python installation.

For simple scripts that do not import external modules, this works just
fine.

For more complex scripts that require imported external modules, the
called modules (.py) have been placed on the computer in the same
folder as the calling script.  However, when the calling scripts run,
we get the error message:

AttributeError: 'module' object has no attribute 'xxx'

We know the calling script finds the necessary modules, and the
attribute clearly appears in the module's .py file.

Can anyone tell me what the problem is or if what we're trying to do is
not possible?  Is there something in addition to the .dll that needs to
be present?

Thanks.

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


Re: Python installation breaks Outlook Express

2004-12-06 Thread Mike
I have the same problem.  It isn't a problem with Outlook.  It is with
Python.  I loose my wired AND wireless connections.  Removing Python
bringst them back to operational.
Mike

M. Laymon wrote:
> I just installed Python 2.3.3 under Windows XP professional.   After
I
> did, my wife tried to access her email using Outlook Express and got
> the error messages:
>
> Your server has unexpectedly terminated the connection. Possible
> causes for
> this include server problems, network problems, or a long period of
> inactivity.
> Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net',
> Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F
>
> Your server has unexpectedly terminated the connection. Possible
> causes for this
> include server problems, network problems, or a long period of
> inactivity.
> Account: 'incoming.verizon.net', Server: 'incoming.verizon.net',
> Protocol: POP3,
> Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F
>
>  (No comments about Outlook, please.I have tried to get her to use a
> different email program, but she likes Outlook.)   I checked the
> settings, then recreated her account in Outlook, but nothing worked.
> My Mozilla Thunderbird email client worked fine.
>
> Since the only thing I had done recently was to install Python.  I
> used system restore to go back to the point before installing Python.
> After I did, Outlook started working again.  Has anyone else seen
this
> behavior ?
> 
> Thanks.
> 
> M. Laymon

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


Re: Writing to stdout and a log file

2005-04-19 Thread Mike
Thanks.

I should've mentioned I want StdoutLog to subclass the 'file' type
because I need all the file attributes available.

I could add all the standard file methods and attributes to StdoutLog
without subclassing  'file' but I'd rather avoid this if I can.

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


Writing to stdout and a log file

2005-04-19 Thread Mike
I would like my 'print' statements to send its output to the user's
screen and a log file.

This is my initial attempt:

class StdoutLog(file):
def __init__(self, stdout, name='/tmp/stdout.log',
mode='w',bufsize=-1):
super(StdoutLog, self).__init__(name,mode,bufsize)
self.stdout = stdout
def write(self, data):
self.stdout.write(data)
self.write(data)

import sys
sys.stdout = StdoutLog(sys.stdout)
print 'STDOUT', sys.stdout

When the program is run the string is written to the log file but
nothing appears on my screen. Where's the screen output?

It looks like the superclass's write() method is getting called instead
of the StdoutLog instance's write() method.

The python documentation says 'print' should write to
sys.stdout.write() but that doesn't seem to be happening.

Any idea what's going one? 
Or ideas on how to debug this?

Thanks, Mike

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


Re: Writing to stdout and a log file

2005-04-20 Thread Mike
flushing stdout has no effect.

I've got an implementation that does not subclass file. It's not as
nice but it works.

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


Re: Writing to stdout and a log file

2005-04-20 Thread Mike
Perfect. This is what I"ll use. Thanks! Mike

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


Printer list value problem

2014-01-14 Thread Mike
Hello,
I confudsed,need printer the value of list (this is reaer from csv) . The 
reader is ok, but my problem is in the print moment because printer only the 
last value. For example my csv is:

[]
us...@example.com;user1;lastName;Name
us...@example.com;user2;lastName;Name
[]

But when execute the script I view the print is only the last user

[]
ca us...@example.com displayName 'user2' sn 'lastName' cn 'Name'
[]

And I need the next printer

[]
ca us...@example.com displayName 'User1' sn ''lastName" cn 'Name'
ca us...@example.com displayName 'User2' sn ''lastName" cn 'Name'
[]

My script is 

[]
#!/usr/bin/python
import csv
with open ('users.csv', 'rb') as f:

reader = csv.reader (f, delimiter=';' ) #delimiter tabulador
for row in reader:

mail = row [0]
name = row [3]
lastname = row [2]

print "ma {} displayName '{}' sn '{}'".format(mail,name,lastname)

f.close()
[]


Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Printer list value problem

2014-01-14 Thread Mike
El martes, 14 de enero de 2014 16:32:49 UTC-3, MRAB  escribió:
> On 2014-01-14 19:24, Mike wrote:
> 
> > Hello,
> 
> > I confudsed,need printer the value of list (this is reaer from csv) . The 
> > reader is ok, but my problem is in the print moment because printer only 
> > the last value. For example my csv is:
> 
> >
> 
> > []
> 
> > us...@example.com;user1;lastName;Name
> 
> > us...@example.com;user2;lastName;Name
> 
> > []
> 
> >
> 
> > But when execute the script I view the print is only the last user
> 
> >
> 
> > []
> 
> > ca us...@example.com displayName 'user2' sn 'lastName' cn 'Name'
> 
> > []
> 
> >
> 
> > And I need the next printer
> 
> >
> 
> > []
> 
> > ca us...@example.com displayName 'User1' sn ''lastName" cn 'Name'
> 
> > ca us...@example.com displayName 'User2' sn ''lastName" cn 'Name'
> 
> > []
> 
> >
> 
> > My script is
> 
> >
> 
> > []
> 
> > #!/usr/bin/python
> 
> > import csv
> 
> > with open ('users.csv', 'rb') as f:
> 
> >
> 
> >  reader = csv.reader (f, delimiter=';' ) #delimiter tabulador
> 
> >  for row in reader:
> 
> >
> 
> >  mail = row [0]
> 
> >  name = row [3]
> 
> >  lastname = row [2]
> 
> >
> 
> 
> 
> This line is indented the same amount as the 'for' loop, which means
> 
> that it will be executed after the loop has finished.
> 
> 
> 
> >  print "ma {} displayName '{}' sn '{}'".format(mail,name,lastname)
> 
> >
> 
> You don't need to close the file here because the 'with' statement will
> 
> do that for you.
> 
> 
> 
> > f.close()
> 
> > []
> 
> >
> 
> >
> 
> > Thanks.
> 
> >

Hello MRAB,
I remove the "f.close" and after execute the script but still i have the same 
result (print the last row)

Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything good about Python except GUI IDE?

2016-03-01 Thread Mike
On Saturday, February 27, 2016 at 6:19:21 AM UTC-5, wrong.a...@gmail.com wrote:
> I have some VB forms with more than a hundred objects. If I cannot drag and 
> drop text boxes, list boxes, labels, etc., it will be too much work to create 
> that with several lines of code for each object. 
> 
> Isn't there any good GUI IDE like Visual Basic? I hope there are some less 
> well known GUI IDEs which I did not come across. Thanks.

I'd recommend PyQt/PySide and Eric as an IDE:

http://eric-ide.python-projects.org/index.html 

Eric has good integration with QtDesigner - you can create forms in designer
like in VB and it will automatically generate python code for it or you
can load *.ui files dynamically. The project management and VCS integration
is also very convenient.

Regards,
Mikhail
-- 
https://mail.python.org/mailman/listinfo/python-list


Error compressing tar file

2014-03-02 Thread Mike
Hello,
I have the script that make a backup file (this process is ok), but now i wish 
compress the file on tar file format. But i have problem syntax in the line of 
the tar function. 

The error is 

[root@master ~]# python bkp_db.py 
  File "bkp_db.py", line 19
tar = tarfile.open(dumpfile)+'.tar.gz','w:gz')
 ^

Note: The 'dumpfile' is the variable for my dump generate with format 
db_02-27-14

..
tar = tarfile.open(dumpfile)+'.tar.gz','w:gz')
tar.add(os.path.join(dumpfile), arcname=dumpfile)
tar.close()


Wath is the correct sintax?


Thanks.



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


Re: Error compressing tar file

2014-03-02 Thread Mike
El domingo, 2 de marzo de 2014 21:38:49 UTC-3, Mike  escribió:
> Hello,
> 
> I have the script that make a backup file (this process is ok), but now i 
> wish compress the file on tar file format. But i have problem syntax in the 
> line of the tar function. 
> 
> 
> 
> The error is 
> 
> 
> 
> [root@master ~]# python bkp_db.py 
> 
>   File "bkp_db.py", line 19
> 
> tar = tarfile.open(dumpfile)+'.tar.gz','w:gz')
> 
>  ^
> 
> 
> 
> Note: The 'dumpfile' is the variable for my dump generate with format 
> db_02-27-14
> 
> 
> 
> ..
> 
> tar = tarfile.open(dumpfile)+'.tar.gz','w:gz')
> 
> tar.add(os.path.join(dumpfile), arcname=dumpfile)
> 
> tar.close()
> 
> 
> 
> 
> 
> Wath is the correct sintax?
> 
> 
> 
> 
> 
> Thanks.

Hello,
without ")" i have the same sintax error: 

[root@master ~]# python bkp_db.py 
Traceback (most recent call last):
  File "bkp_db.py", line 19, in 
tar = tarfile.open(dumpfile + '.tar.gz','w:gz')
TypeError: unsupported operand type(s) for +: 'file' and 'str' 

Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


ERROR:root:code for hash md5 was not found

2012-01-11 Thread mike
Hi,

We are running are running Python program on Redhat 5.5.

When executing our program we get the following error ( see below).

Any ideas what this is due to?

br,

//mike

/pysibelius/lib/common/
DataTypes.py
Overwriten ...
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
  File "/python/lib/python2.7/hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/python/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ERROR:root:code for hash md5 was not found

2012-01-11 Thread mike
On Jan 12, 12:28 am, Steven D'Aprano  wrote:
> On Wed, 11 Jan 2012 05:54:29 -0800, mike wrote:
> > I did some more digging and found that our class imports a "yacc.py"
> > that uses
>
> > import re, types, sys, cStringIO, hashlib, os.path
>
> > so it has hashlib.
>
> > yacc.py seems to be an old version 1.3 ( I found 2.3 -->).
>
> > Reading about hashlib it seems to be dependent on os installation of
> > OpenSSL but I cannot find out how.
>
> It shouldn't be. It will use OpenSSL if available, otherwise it will fall
> back on its own code.
>
> > br,
>
> > //mike
>
> > yacc.py
> > ===
>
> #->
>  # ply: yacc.py
>
> [snip over TWO THOUSAND lines of code]
>
> Mike, what lead you to believe that an error in hashlib could be solved
> by posting the ENTIRE two thousand lines of yacc.py? Please do not post
> such huge chunks of code unless asked. It is unnecessary and annoying.
>
> Try this. Open a terminal window and enter "python" at the prompt to
> start a clean interactive session. Then enter the following commands:
>
> import sys
> print(sys.version)
> import hashlib
> print(hashlib.__file__)
> print(hashlib.md5)
> import _md5
> print(_md5.__file__)
>
> and copy and paste (do not retype) the full output of these commands.
>
> Thank you.
>
> --
> Steven

Hi,

Sorry for posting huge file. I added your copy-paste snippet.

esekilx5030 [7:09am] [roamFroBl/pysibelius/bin] -> python
Python 2.7.2 (default, Jun 16 2011, 15:05:49)
[GCC 4.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
print(sys.version)
import hashlib
print(hashlib.__file__)
print(hashlib.md5)
import _md5
print(_md5.__file__) >>> 2.7.2 (default, Jun 16 2011, 15:05:49)
[GCC 4.5.0]
>>> ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha512
>>> /vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/hashlib.pyc
>>> Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'md5'
>>> Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named _md5

Thanks for support!

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


Re: ERROR:root:code for hash md5 was not found

2012-01-11 Thread mike
On Jan 12, 7:13 am, mike  wrote:
> On Jan 12, 12:28 am, Steven D'Aprano 
>
>
>
>
>
>
>
>
> +comp.lang.pyt...@pearwood.info> wrote:
> > On Wed, 11 Jan 2012 05:54:29 -0800, mike wrote:
> > > I did some more digging and found that our class imports a "yacc.py"
> > > that uses
>
> > > import re, types, sys, cStringIO, hashlib, os.path
>
> > > so it has hashlib.
>
> > > yacc.py seems to be an old version 1.3 ( I found 2.3 -->).
>
> > > Reading about hashlib it seems to be dependent on os installation of
> > > OpenSSL but I cannot find out how.
>
> > It shouldn't be. It will use OpenSSL if available, otherwise it will fall
> > back on its own code.
>
> > > br,
>
> > > //mike
>
> > > yacc.py
> > > ===
>
> > #->
> >  # ply: yacc.py
>
> > [snip over TWO THOUSAND lines of code]
>
> > Mike, what lead you to believe that an error in hashlib could be solved
> > by posting the ENTIRE two thousand lines of yacc.py? Please do not post
> > such huge chunks of code unless asked. It is unnecessary and annoying.
>
> > Try this. Open a terminal window and enter "python" at the prompt to
> > start a clean interactive session. Then enter the following commands:
>
> > import sys
> > print(sys.version)
> > import hashlib
> > print(hashlib.__file__)
> > print(hashlib.md5)
> > import _md5
> > print(_md5.__file__)
>
> > and copy and paste (do not retype) the full output of these commands.
>
> > Thank you.
>
> > --
> > Steven
>
> Hi,
>
> Sorry for posting huge file. I added your copy-paste snippet.
>
> esekilx5030 [7:09am] [roamFroBl/pysibelius/bin] -> python
> Python 2.7.2 (default, Jun 16 2011, 15:05:49)
> [GCC 4.5.0] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import sys
>
> print(sys.version)
> import hashlib
> print(hashlib.__file__)
> print(hashlib.md5)
> import _md5
> print(_md5.__file__) >>> 2.7.2 (default, Jun 16 2011, 15:05:49)
> [GCC 4.5.0]>>> ERROR:root:code for hash md5 was not found.
>
> Traceback (most recent call last):
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 139, in 
>     globals()[__func_name] = __get_hash(__func_name)
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 91, in __get_builtin_constructor
>     raise ValueError('unsupported hash type %s' % name)
> ValueError: unsupported hash type md5
> ERROR:root:code for hash sha1 was not found.
> Traceback (most recent call last):
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 139, in 
>     globals()[__func_name] = __get_hash(__func_name)
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 91, in __get_builtin_constructor
>     raise ValueError('unsupported hash type %s' % name)
> ValueError: unsupported hash type sha1
> ERROR:root:code for hash sha224 was not found.
> Traceback (most recent call last):
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 139, in 
>     globals()[__func_name] = __get_hash(__func_name)
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 91, in __get_builtin_constructor
>     raise ValueError('unsupported hash type %s' % name)
> ValueError: unsupported hash type sha224
> ERROR:root:code for hash sha256 was not found.
> Traceback (most recent call last):
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 139, in 
>     globals()[__func_name] = __get_hash(__func_name)
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 91, in __get_builtin_constructor
>     raise ValueError('unsupported hash type %s' % name)
> ValueError: unsupported hash type sha256
> ERROR:root:code for hash sha384 was not found.
> Traceback (most recent call last):
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 139, in 
>     globals()[__func_name] = __get_hash(__func_name)
>   File "/vobs/rnc/rrt/roam1/roamSs/roamFroBl/python/lib/python2.7/
> hashlib.py", line 91, in __get_builtin_constructor
>     raise ValueError('unsupported hash type %s'

Re: ERROR:root:code for hash md5 was not found

2012-01-13 Thread mike
On Jan 13, 5:41 am, alex23  wrote:
> On Jan 13, 1:34 pm, Steven D'Aprano 
> +comp.lang.pyt...@pearwood.info> wrote:
> > What is pysibelius? I can't find it on the web. Does it have anything to
> > do with Sibelius the music composition software?
>
> Yes, please provide more information about the pysibelius package,
> especially if this is the case.
>
> The few tenuous Python/Sibelius links I found didn't have anything on
> pysibelius, unfortunately.

Hi,

pysibelius is a lib that we use.

I am not sure that is the problem since the python program works on
SuSE but not on RH server. And AFAIK
the only difference ( well that I can see) is the OpenSSL version.

According to code it uses openssl:



So I need to find a way to convince the linux sys admin to install
same version of openssl on both servers.

Thanks a lot for your valuable time.

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


Re: Remote Function Call

2006-01-12 Thread Mike
Sounds like what I need. Thanks Irmen. I heard google uses python with
multiple machines... how do they do it?

Mike

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


Remote Function Call

2006-01-13 Thread Mike
Hi,

I have two machines. A python program on machine 1 needs to make a
python call to a method in machine 2. What is the most efficient / fast
/ programmer friendly way to do it?

- XML-RPC?
- Http Call?

Thanks,
Mike

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


Re: Remote Function Call

2006-01-13 Thread Mike
Thanks Everyone for your input.

Mike

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


XML vs. cPickle

2006-01-13 Thread Mike
I know XML is more (processor) costly than cPickle, but how bad is it?
The idea is I want to store data that can be described as XML into my
database as cPickle objects. Except my web framework has no support for
BLOB datatype yet, and I might have to go with XML.

Ideas are appreciated,

Thanks,
Mike

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


Marshal Obj is String or Binary?

2006-01-13 Thread Mike
Hi,

The example below shows that result of a marshaled data structure is
nothing but a string

>>> data = {2:'two', 3:'three'}
>>> import marshal
>>> bytes = marshal.dumps(data)
>>> type(bytes)

>>> bytes
'{i\x02\x00\x00\x00t\x03\x00\x00\x00twoi\x03\x00\x00\x00t\x05\x00\x00\x00three0'

Now, I need to store this data safely in my database as CLEAR TEXT, not
BLOB. It seems to me that it should work just fine since it is string
anyways. So, why does O'reilly's Python Cookbook is insisting in saving
it as a binary file and BLOB type?

Am I missing out something?

Thanks,
Mike

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


Re: XML vs. cPickle

2006-01-13 Thread Mike
> I'd guess that XML serialisation with cElementTree is both cpu and
> memory competitive with cpickle, if not superior. Although I'm too lazy
> to fire up the timeit module right now :-)

That maybe true, but I bet Marshal is the fastest. ...right?

> Also, how quickly the relevant parsers work depends on the input, i.e.
> your data structures. Only you can take measurements with your data
> structures 

True.

> > The idea is I want to store data that can be described as XML
> can != should

I certainly 'can', I don't think I should.

> > into my
> > database as cPickle objects. Except my web framework has no support for
> > BLOB datatype yet, and I might have to go with XML.

> Or you could encode the binary pickle in a text-safe encoding such as
> base64, and store the result in a text column. Although that will
> obviously increase your processing time, both going in and out of the
> database.

base64... (used to convert arbitrary binary data to plain text), sounds
fantastic. Except, I don't think I need it when marshaling anymore
since marshaling gives you clear text anyways. (right?)

> > Ideas are appreciated,

> I'd write a few simple prototypes and take some empirical measurements.

I am doing it now. Thanks,

Mike

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


Re: Marshal Obj is String or Binary?

2006-01-13 Thread Mike
Wait a sec. \x00 may represent a byte when unmarshaled, but as long as
marshal likes it as \x00, I think my db is capable of storing \ x 0 0
characters. What is the problem? Is it that \? I could escape that...
actually I think my django framework already does that for me.

Thanks,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-13 Thread Mike
Wait a sec. \x00 may represent a byte when unmarshaled, but as long as
marshal likes it as \x00, I think my db is capable of storing \ x 0 0
characters. What is the problem? Is it that \? I could escape that...
actually I think my django framework already does that for me.

Thanks,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-13 Thread Mike
Thanks everyone. It seems broken storing complex structures as escaped
strings, but I think I'll take my changes. 

Thanks,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-14 Thread Mike
Thanks everyone.

Why Marshal & not Pickle: Well, Marshal is supposed to be faster. But
then, if I wanted to do the whole repr()-eval() hack, I am already
defeating the purpose by refusing to save bytes as bytes in terms of
both size and speed.

At this point, I am considering one of the following:
- Save my structure as binary data, and reference the file from my db
- Find a clean method of saving bytes into my db

Thanks again,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-15 Thread Mike
> Even faster would be to write your code in assembly, and dump that
> ridiculously bloated database and just write everything to raw bytes on
> an unformatted disk. Of course, it might take the programmer a thousand
> times longer to actually write the program, and there will probably be
> hundreds of bugs in it, but the important thing is that you'll save three
> or four milliseconds at runtime.

> Right?

Correct. I didn't quite see the issue as assembly vs. python, having
direct translation to programming hours. The structure in mind is meant
to act as a dictionary to extend my db with a few table fields that
could vary from one record to another and won't be queried for.
Considering everytime my record is loaded, it pickle or marshal data
has to be decoded, I figured the faster alternative should be better.
With the incompatibility issue, I figured the day I upgrade my python,
I would write a python script to upgrade the data. I take my word back.

> Your database either can handle binary data, or it can't.

It can. It's my web framework that doesn't.

> If it can, then just use pickle with a binary protocol and be done with it.

That I will do.

> Either way, you have to find a way to translate your Python data
> structures into something that you can feed to the database. Your database
> can't automatically suck data structures out of Python's working memory!
> So why re-invent the wheel? marshal is not recommended, but if you can
> live with the limitations of marshal then it might do the job. But trying
> to optimise code that hasn't even been written yet is a sure way to
> trouble. 

Thanks. Will do.

Regards,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-15 Thread Mike
> Even faster would be to write your code in assembly, and dump that
> ridiculously bloated database and just write everything to raw bytes on
> an unformatted disk. Of course, it might take the programmer a thousand
> times longer to actually write the program, and there will probably be
> hundreds of bugs in it, but the important thing is that you'll save three
> or four milliseconds at runtime.

> Right?

Correct. I didn't quite see the issue as assembly vs. python, having
direct translation to programming hours. The structure in mind is meant
to act as a dictionary to extend my db with a few table fields that
could vary from one record to another and won't be queried for.
Considering everytime my record is loaded, it pickle or marshal data
has to be decoded, I figured the faster alternative should be better.
With the incompatibility issue, I figured the day I upgrade my python,
I would write a python script to upgrade the data. I take my word back.

> Your database either can handle binary data, or it can't.

It can. It's my web framework that doesn't.

> If it can, then just use pickle with a binary protocol and be done with it.

That I will do.

> Either way, you have to find a way to translate your Python data
> structures into something that you can feed to the database. Your database
> can't automatically suck data structures out of Python's working memory!
> So why re-invent the wheel? marshal is not recommended, but if you can
> live with the limitations of marshal then it might do the job. But trying
> to optimise code that hasn't even been written yet is a sure way to
> trouble. 

Thanks. Will do.

Regards,
Mike

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


Re: Marshal Obj is String or Binary?

2006-01-15 Thread Mike
> Well, the Cookbook isn't an exhaustive list of everything you can do
> with Python, it's just a record of some of the things people *have* done.

Considering I am a newbie, it's a good start for me...

> I presume your database has no datatype that will store binary data of
> indeterminate length? Clearly that would be the most satisfactory solution.

PostgreSQL. I think the only two thing it doesn't do is wash my car and
code my software. Well, that's up until you use it in conjunction with
Django, then the only work left is to wash my car, which I can't care
less either. We'll wait for some rain :)

Mike

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


Re: Marshal Obj is String or Binary?

2006-01-15 Thread Mike
> So this question was primarily theoretical, right?

Theoretical? not really Steve. I wanted to use django's wonderful db
framework to save a structure into my postgresql. Except there is no
direct BLOB support for it yet. There, I was trying to explore my
options with saving this structure in clear text.

Thanks,
Mike

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


Re: self question

2006-07-26 Thread Mike

Schüle Daniel wrote:
> Hi all,
>
> given python description below
>
> import random
>
> class Node:
>  def __init__(self):
>  self.nachbarn = []
>
> class Graph(object):
>   # more code here
>  def randomizeEdges(self, low=1, high=self.n):
>  pass
>
>
> graph = Graph(20)
> graph.randomizeEdges(2,5)
>
> I am burned by high=self.n
> quick test with
>
> cnt = 1
> def foo():
>   global cnt
>   cnt += 1
>   return cnt
>
> def bar(x=foo()):
>   print x
>
> bar() # 2
> bar() # 2
> bar() # 2
>
> this is not behaviour C++ programmer would expect
> does someone know why this kind of behaviour is/was choosen?
>
> Regards, Daniel

I think the answer is that 'def' is an executable statement in python
rather than a definition that the compiler interprets at compile time.

As a result the compiler can evaluate 'foo()' when it defines 'bar', so
it does.

The following works as expected:
def bar():
  print foo()

Hopefully somebody more knowledgable will also respond

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


"no module named win32api" using PyWin32-208

2006-06-27 Thread Mike
Hi.

I have Python 2.4 installed on my local machine in c:\Python24. I have
also downloaded the python for windows extensions installer
pywin32-208.win32-py2.4.exe and installed this to
C:\Python24\Lib\site-packages

Trying to run a python script through a C# console app is causing me
problems: the last line of code in the following block results in a no
module named win32ap error. I'm not sure if this is because there is no
win32api.py in the win32 fikder off site-packages, just a win32api.pyc
file.

m_engine = new PythonEngine();

m_engine.AddToPath("C:\\Python24\\DLLs");
m_engine.AddToPath("C:\\Python24\\lib");
m_engine.AddToPath("C:\\Python24\\lib\\plat-win");
m_engine.AddToPath("C:\\Python24\\lib\\lib-tk");

m_engine.AddToPath("C:\\Python24\\Lib\\site-packages\\pythonwin");
m_engine.AddToPath("C:\\Python24");
m_engine.AddToPath("C:\\Python24\\lib\\site-packages");

m_engine.AddToPath("C:\\Python24\\lib\\site-packages\\win32");

m_engine.AddToPath("C:\\Python24\\lib\\site-packages\\win32\\lib");

m_engine.Execute("from win32api import win32api");

I have added all the addtopaths to get the path to match the sys.path I
see in a normal python console which can successfully import the
module.

Incidentally, I have tried making the last line
 m_engine.Execute("import win32api");
with no luck.

Can the win32 extensions handle compiled python modules? If not how can
I get it to work?

Thanks,
Mike

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


raw strings in regexps

2006-12-07 Thread Mike
I've been having trouble with a regular expression, and I finally simplified 
things down to the point that (a) my example is very simple, and (b) I'm 
totally confused. There are those who would say (b) is normal, but that's 
another thread.

I finally simplified my problem down to this simple case:

   re.match(r'\\this', r'\\this')

Both the pattern and the string to match are identical raw strings, yet they 
don't match. What does match is this:

   re.match(r'this', r'\\this')

Below are outputs from two versions of Python on two different machines, 
with identical outputs, so it's probably not a compiler problem or a version 
bug.

What's going on here? Am I missing something obvious?

linux25> python
Python 2.2.3 (#1, Feb  2 2005, 12:22:48)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> print re.match(r'\\this', r'\\this')
None
>>> print re.match(r'this', r'\\this')
<_sre.SRE_Match object at 0x6bf0e0>
>>>

C:\Dev\python>python
ActivePython 2.4.2 Build 10 (ActiveState Corp.) based on
Python 2.4.2 (#67, Jan 17 2006, 15:36:03) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> print re.match(r'\\this', r'\\this')
None
>>> print re.match(r'this', r'\\this')
<_sre.SRE_Match object at 0x009DA058>
>>>

-- Mike --


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


Re: raw strings in regexps

2006-12-08 Thread Mike
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

...

> You have to quote metacharacters if you want to match them. The escape 
> method is useful for this:
>
> >>> re.escape('(a)')
> '\\(a\\)'

Doh! Of course! Thanks everyone.

-- Mike --


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


Re: What is different with Python ?

2005-06-13 Thread Mike

>there should be no room for "magic" in a computer
>for a professional programmer.
>
well put. sounds like the makings of a good signature...


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


how to print out each single char from a string in HEX format?

2007-06-04 Thread mike
guys,

I've researched python pretty much but still have no idea how to print
out each single character from a string in HEX format? Hope someone
can give me some hints. Thanks a lot.

e.g.###here is a string

  a='01234'

  ###how to print out it out in this way

  0x31 0x31 0x32 0x33 0x34

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


Re: how to print out each single char from a string in HEX format?

2007-06-04 Thread mike
Great! It works.

Thanks a lot.

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


Could someone show me a sample how to flush the socket sending buffer? Thanks a lot.

2007-06-08 Thread mike
I have called the setsockopt() to set no delay after connecting like
this way:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.10.1', 21980))
s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 0)
s.send("[EMAIL PROTECTED]")
s.send("[EMAIL PROTECTED]")
..

but still, the server can only receive the first line, and keep
waiting for the second line. So, in my mind the second line is still
in the sending buffer, and not reach the server side.

Any hints would be appreciated.

Mike

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


Re: MI5 Persecution: Goldfish and Piranha 29/9/95 (5104)

2007-06-09 Thread Mike
And this is here because ???


<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I just thought I'd let you know what I've been reading into 
the
| "Crusader" spam. I don't want to post this to usenet 
because somebody
| might try to tie that in to my posts in some way (someone 
already has, in
| uk.misc).
|
| First of all, I'd like to ask you to believe that my phone 
line in my
| apartment is bugged, and has been for many months. I have 
moved a couple
| of times this year, but "they" have faithfully been on my 
trail.
|
| Anyway, let's suppose my phone line is bugged. Now, when I 
talk to my
| internet service provider, it's over a SLIP (now PPP) 
connection. So if
| you wanted to bug what was said, either you'd listen in 
over the line and
| have to decode the transmission, or you could go to the 
service provider
| (more difficult) and ask them to decode a particular 
user's connection.
|
| OK, so now they're listening to everything I do over my 
SLIP/PPP
| connection. A couple of months ago I was messing around 
with faking
| articles through nntp servers and through anonymous 
remailers. I chose a
| nice inconspicuous newsgroup for my little tests, 
something no-one would
| ever notice. Guess which newsgroup I chose??? Yes, 
_FISH_!!! or
| rec.aquaria to be precise
|
| And guess what articles I tried to post? Goldfish, Koi 
carp and, you'll
| never guess... PIRANHA!!! The goldfish article and the Koi 
went through,
| but the piranha didn';t appear.
|
| by now you probably think this is too silly for words. But 
if you look in
| the papers a few eeks ago you will find John Major, Tonny 
Blair and Paddy
| Ashdown sharing a "private joke" about Major's sunburnt 
goldfish. We
| haven't had anything about Koi yet (they must be too 
dull ). Now, sent by
| someone who clearly knew what they were doing (they chose 
an Italian
| backbone site for their launch point) we have many 
thousands of messages
| to people all over the globe. All about piranha, and with 
the punchline
| "that gives you something to think about, doesn't it?"
|
| The way it works is that they're trying to kill two birds 
with one stone
| again. I don't knoiw why they should be against these 
national alliance
| people, but my interpretation is that they simultaneously 
try to
| discredit them, and stem the flow of Corley articles.
|
| 
=
|
| In article <[EMAIL PROTECTED]>,
| Mike Corley <[EMAIL PROTECTED]> wrote:
| >
| >John J Smith ([EMAIL PROTECTED]) wrote:
| >
| >: b) we do know who you are. Or are you someone else we 
don't know about?
| >: You are currently known as "That bloody persistant net 
nutter, who's
| >: expanding from uk.misc to the rest of the world".
| >
| >I think the point I was trying to make is that I could 
tell you things
| >from my personal life, at home and at work, which would 
add credibility
| >to my story. But if I named people, then (a) they would 
object violently
| >to being included in this shenanigans, and (b) I would be 
revealing my
| >identity which would be bad for my personal life and my 
work life. Of
| >course some people in my personal life, and at work, do 
know who "mike
| >corley" is. But at least we're observing a studied 
silence for now.
|
| :People can always be called "MR X", to save them being 
named.
| :
| :I'm completely perplexed as to what you mean by b). 
Revealing identity?
| :To who? And why would this be bad for any part of your 
life when you
| :already have a less than respectful reputation here?
|
| I'll just enumerate one or two things that I can still 
remember. Sometime
| around August/Sept 1992 I was living in a house in Oxford, 
and coming out
| of the house was physically attacked by someone - not 
punched, just grabbed
| by the coat, with some verbals thrown in for good measure. 
That was something
| the people at work shouldn't have known about... but soon 
after a couple of
| people were talking right in front of me about, "yeah, I 
heard he was
| attacked".
|
| Again, one I went for a walk in some woods outside Oxford. 
The next day,
| at work, someone said "you know he went to the forest 
yesterday".
|
| I don't want to put details on usenet of what happened 
because to do so
| would be to risk it happening again. If you put ideas in 
peoples' heads
| then you can find them reflecting back at you, and I don't 
want that.
| Also I can't remember that much from three years ago. From 
november 1992
| I started taking "major tranquilizers" and just blotted 
the whole thing
| from my mind.
|
| >This is a feature time and time again, that the security 
services
| >(presumed) get at you by manipulat

How can I capture all exceptions especially when os.system() fail? Thanks

2007-06-13 Thread mike
Hi Guys,

Following piece of code can capture IOError when the file doesn't
exist, also, other unknown exceptions can be captured when I press
Ctrl-C while the program is sleeping(time.sleep). Now the question is:
when I run the non-exist command, the exception cannot be captured.

Here is the code:
===
#!/usr/bin/python
import os
import sys
import time

try:
fh = open("tt.py")
time.sleep(10)
#os.system("wrong_command_test")
except IOError:
print 'failed to open.'
sys.exit(0)
except:
print 'Some exceptions occurred.'
else:
print 'well',

print 'Done'

===
when the tt.py doesn't exist, the script printed:
failed to open.
when the tt.py exists, the script printed:
well done
when I press Ctrl-C while the program is sleeping, the script printed:
Some exceptions occurred.
Done

So far so good, then I changed the code to run a non-exist command
"wrong_command_test"(commented the open and sleep lines), then the
script printed:
sh: wrong_command_test: command not found
well Done


Any opinions would be appreciated.

Mike

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


Re: How can I capture all exceptions especially when os.system() fail? Thanks

2007-06-14 Thread mike
On Jun 14, 2:55 am, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> Gabriel Genellina wrote:
> > En Wed, 13 Jun 2007 21:47:16 -0300, mike <[EMAIL PROTECTED]> escribió:
>
> >> Following piece of code can capture IOError when the file doesn't
> >> exist, also, other unknown exceptions can be captured when I press
> >> Ctrl-C while the program is sleeping(time.sleep). Now the question is:
> >> when I run the non-exist command, the exception cannot be captured.
>
> >> So far so good, then I changed the code to run a non-exist command
> >> "wrong_command_test"(commented the open and sleep lines), then the
> >> script printed:
> >> sh: wrong_command_test: command not found
> >> well Done
>
> > That's because it is not an exception, it is an error message coming
> > from your shell, not from Python.
>
> Of course if you use subprocess.check_call() instead of os.system(), it
> will become an exception (CalledProcessError).
> --
> Michael Hoffman

Really helps. Thanks Michael

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

adding methods at runtime and lambda

2007-05-03 Thread Mike
I was messing around with adding methods to a class instance at
runtime and saw the usual code one finds online for this. All the
examples I saw say, of course, to make sure that for your method that
you have 'self' as the first parameter. I got to thinking and thought
"I have a lot of arbitrary methods in several utility files that I
might like to add to things. How would I do that?" And this is what I
came up with:


def AddMethod(currObject, method, name = None):
if name is None: name = method.func_name
class newclass(currObject.__class__):pass
setattr(newclass, name, method)
return newclass()

And lets say I have a utility function that can check if a drive
exists on my windows box called HasDrive. I can add that like this:

superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d),
"hasdrive")

and then I can call

superdict.HasDrive('c')

lambda makes it possible to add any random function because you can
use it to set self as the first parameter. I've found several real
uses for this already. My big question is, will something like this be
possible in python 3000 if lambda really does go away? I've not heard
much about lambda, reduce, etc. lately but I know Guido wanted them
out of the language.

Is there a better way to do this today than to use lambda? It seemed
the simplest way to do this that I could find.

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


Re: adding methods at runtime and lambda

2007-05-03 Thread Mike
In the above example 'addm' should be 'AddMethod'

superdict = AddMethod(dict(), lambda self, d:
myUtils.HasDrive(d),"hasdrive")

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


Re: adding methods at runtime and lambda

2007-05-04 Thread Mike
On May 3, 11:25 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 03 May 2007 16:52:55 -0300, Mike <[EMAIL PROTECTED]> escribió:
>
> > I was messing around with adding methods to a class instance at
> > runtime and saw the usual code one finds online for this. All the
> > examples I saw say, of course, to make sure that for your method that
> > you have 'self' as the first parameter. I got to thinking and thought
> > "I have a lot of arbitrary methods in several utility files that I
> > might like to add to things. How would I do that?" And this is what I
> > came up with:
>
> I don't see the reason to do that. If you have a function that does not
> use its "self" argument, what do you get from making it an instance method?
> If -for whatever strange reason- you want it to actually be a method, use
> a static method:
>
> py> def foo(x):
> ...   print "I like %r" % x
> ...
> py> class A(object): pass
> ...
> py> a = A()
> py> A.foo = staticmethod(foo)
> py> a.foo()
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: foo() takes exactly 1 argument (0 given)
> py> a.foo("coffee")
> I like 'coffee'
> py> A.foo("tea")
> I like 'tea'
>
> --
> Gabriel Genellina

staticmethod makes the function available to the whole class according
to the docs. What if I only want it to be available on a particular
instance? Say I'm adding abilities to a character in a game and I want
to give a particular character the ability to 'NukeEverybody'. I don't
want all characters of that type to be able to wipe out the entire
planet, just the particular character that got the powerup.

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


Re: adding methods at runtime and lambda

2007-05-04 Thread Mike
On May 4, 2:05 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> Mike wrote:
> > staticmethod makes the function available to the whole class according
> > to the docs. What if I only want it to be available on a particular
> > instance? Say I'm adding abilities to a character in a game and I want
> > to give a particular character the ability to 'NukeEverybody'. I don't
> > want all characters of that type to be able to wipe out the entire
> > planet, just the particular character that got the powerup.
>
> Static methods are for specialists, you don't need them. But then, your
> initial post looked like you were just exploring the possibilities...

Yeah, I'm just poking around.

>
> You can
>
> - have the Character.nuke_everybody() method check a self._can_nuke_eb flag

I don't like this one because it would require me to know every
ability everybody might ever have up front.

> - subclass the Character class with a NukingChar subclass and make only one
>   instance of that class

A possibility, I guess, but does this then mean I would need a new
class for every type of character? Probably not, but you would at
least need types grouped by general class, kind of like D&D characters
(Fighter, Magic User, etc.). It makes it harder for anybody to learn
anything they want.

> - add an instancemethod to one Character instance
>
> The simpler the approach you take the smarter you are ;)
>
> Peter

I just realized in working with this more that the issues I was having
with instancemethod and other things seems to be tied solely to
builtins like dict or object. I remember at some point just doing
something like:

x.fn = myfnFunction

and having it just work. If I do that with an instance of generic
object however, I get an AttributeError. So:

x = object()
x.fn = myFn

blows up. However, if I do

class nc(object):pass
x = nc()
x.fn = myFn

Then all is well.

checking for an ability on somebody is as simple as

'fn' in dir(x)

or

hasattr(x, 'fn')


I had thought this was a lot easier than I was making it out to be.
What I don't know is why using an object derived from object allows
you to dynamically add methods like this but the base object does not.
At this point it is more of a curiosity than anything, but if somebody
knows the answer off the top of their head, that would be great.

Thanks.

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


Re: adding methods at runtime and lambda

2007-05-07 Thread Mike
On May 4, 5:46 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> Mike wrote:
> > I just realized in working with this more that the issues I was having
> > with instancemethod and other things seems to be tied solely to
>
> What you describe below is a function that happens to be an attribute of an
> instance. There are also "real" instance methods that know about "their"
> instance:
>
> >>> import new
> >>> class A(object):
>
> ... def __init__(self, name):
> ... self.name = name
> ...>>> def method(self): # a function...
>
> ... print self.name
> ...>>> a = A("alpha")
> >>> b = A("beta")
> >>> a.method = new.instancemethod(method, a) # ...turned into a method...
> >>> a.method()
> alpha
> >>> b.method() # ... but only known to a specific instance of A
>
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'A' object has no attribute 'method'
>
> > builtins like dict or object. I remember at some point just doing
> > something like:
>
> > x.fn = myfnFunction
>
> > and having it just work.
>
> With the caveat that x.fn is now an alias for myfnFunction, but doesn't get
> x passed as its first argument (conventionally named 'self') and therefore
> has no knowledge of the instance x.
>
>
>
> > If I do that with an instance of generic
> > object however, I get an AttributeError. So:
>
> > x = object()
> > x.fn = myFn
>
> > blows up. However, if I do
>
> > class nc(object):pass
> > x = nc()
> > x.fn = myFn
>
> > Then all is well.
>
> > checking for an ability on somebody is as simple as
>
> > 'fn' in dir(x)
>
> > or
>
> > hasattr(x, 'fn')
>
> > I had thought this was a lot easier than I was making it out to be.
> > What I don't know is why using an object derived from object allows
> > you to dynamically add methods like this but the base object does not.
> > At this point it is more of a curiosity than anything, but if somebody
> > knows the answer off the top of their head, that would be great.
>
> Arbitrary instance attributes are implemented via a dictionary (called
> __dict__), and that incurs a certain overhead which is sometimes better to
> avoid (think gazillion instances of some tiny class). For example, tuples
> are derived from object but don't have a __dict__.
> As a special case, what would happen if dict were to allow attributes? It
> would need a __dict__ which would have a __dict__ which would have...
> As a consequence object could no longer be the base class of all (newstyle)
> classes.
>
> Peter

Thanks.

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


Re: Basic Class/Instance Question

2007-05-23 Thread Mike
Thanks Alan,

I am still perplexed why the default value of this object is shared.
hemm...d

Back to programming, :)
Sia


On May 23, 7:19 am, Alan Franzoni
<[EMAIL PROTECTED]> wrote:
> Il 23 May 2007 04:07:19 -0700, Siah ha scritto:
>
> > Ready to go insane here. Class A, taking on a default value for a
>
> __init__ is a function, taking a default value of [], which is a list,
> which is a mutable object. That said, you should remember that this means
> that such default value is 'shared' between all instances. If you don't
> want that, do something like:
>
> def __init__(self, defaultvalue=None):
> if defaultvalue is None:
> defaultvalue=[]
>
> http://docs.python.org/tut/node6.html#SECTION00671
>
> --
> Alan Franzoni <[EMAIL PROTECTED]>
> -
> Togli .xyz dalla mia email per contattarmi.
> Remove .xyz from my address in order to contact me.
> -
> GPG Key Fingerprint (Key ID = FE068F3E):
> 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E


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


Key Listeners

2007-05-29 Thread Mike
Are there key listeners for Python? Either built in or third party?

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


Re: first, second, etc line of text file

2007-07-26 Thread Mike
On Jul 26, 8:46 am, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote:
> > > A very simple question: I currently use a cumbersome-looking way of
> > > getting the first, second, etc. line of a text file:
>
> > > for i, line in enumerate( open( textfile ) ):
> > > if i == 0:
> > > print 'First line is: ' + line
> > > elif i == 1:
> > > print 'Second line is: ' + line
> > > ...
> > > ...
>
> > > I thought about f = open( textfile ) and then f[0], f[1], etc but that
> > > throws a TypeError: 'file' object is unsubscriptable.
>
> > > Is there a simpler way?
>
> > If all you need is sequential access, you can use the next() method of
> > the file object:
>
> > nextline = open(textfile).next
> > print 'First line is: %r' % nextline()
> > print 'Second line is: %r' % nextline()
> > ...
>
> > For random access, the easiest way is to slurp all the file in a list
> > using file.readlines().
>
> Thanks! This looks the best, I only need the first couple of lines
> sequentially so don't need to read in the whole file ever.

if you only ever need the first few lines of a file, why not keep it
simple and do something like this?

mylines = open("c:\\myfile.txt","r").readlines()[:5]

that will give you the first five lines of the file. Replace 5 with
whatever number you need. next will work, too, obviously, but won't
that use of next hold the file open until you are done with it? Or,
more specifically, since you do not have a file object at all, won't
you have to wait until the function goes out of scope to release the
file? Would that be a problem? Or am I just being paranoid?

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


Re: help on object programing

2007-08-17 Thread mike
On Aug 17, 11:07 am, yadin <[EMAIL PROTECTED]> wrote:
> class big(self):
>
> x = 32
> list = []
> def inside (self):
>
> class small(self): # a new class defined inside the first
>
> y = 348
> list.append(y) # send the value to first list
> list.append(x)
>
> print list
>
> how can i define my variables so that there are valid outside the
> class???


Well, first you have to create an instance of the class big:
  bigInstance = big();

then to get to bigInstance's list you do bigInstance.list and you can
get to the list:
  print bigInstance.list;

but the list will be empty.

check out the dive into python book to understand it object oriented
programming a little more.
http://www.diveintopython.org/


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


  1   2   3   4   5   6   7   8   9   10   >