Re: is there a way to access postgresql in python3.0rc1

2008-10-29 Thread davy zhang
thanks, I'll wait a month and see, in the mean time I can use 2.x for
my prototyping, hope python3.0 final can drop a nuke on the ground :D

On Thu, Oct 30, 2008 at 12:31 PM, Steve Holden <[EMAIL PROTECTED]> wrote:
> Terry Reedy wrote:
>> davy zhang wrote:
>>> I'm currently on a  project, it could last for at least 1 or 2 years.
>>> so I choose python3 as server side programing language.
>>> All I found on are python2.x ready libraries, Is there any library is
>>> python3.0 ready? or just under alpha ,beta or something, I don't much
>>> features, just basic functions are OK
>>
>> Python3.0 final should be released in about a month.  Extension
>> libraries will start appearing after that.  You will have to ask the
>> maintainers of a particular library what their plans are for Python 3.
>> Some will port very easily and could be available soon.  Others will
>> take more work and may not appear so soon.
>>
> Please note, however, that Python 3.x is not likely to be as
> well-supported by extension modules as Python 2.x for some considerable
> time. The OP may therefore wish to reconsider his choice of Python 3.0.
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: beutifulsoup

2008-10-29 Thread Kay Schluehr
On 29 Okt., 17:45, luca72 <[EMAIL PROTECTED]> wrote:
> Hello
> I try to use beautifulsoup
> i have this:
> sito = urllib.urlopen('http://www.prova.com/')
> esamino = BeautifulSoup(sito)
> luca = esamino.findAll('tr', align='center')
>
> print luca[0]
>
> >> >>href="#">#144.4MB >>align="left"> Pc-prova.rar 
>
> I need to get the following information:
> 1)Only|G|BoT|05
> 2)#1
> 3)44.4MB
> 4)Pc-prova.rar
> with: print luca[0].a.stringi get #1
> with print luca[0].td.stringi get 44.4MB
> can you explain me how to get the others two value
> Thanks
> Luca

The same way you got `luca`

1,2) luca.find("a")["onclick"].split("'") and search through the
result list
3)   luca.find("td").string
4)   luca.find("font").string


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


Re: beutifulsoup

2008-10-29 Thread Stefan Behnel
Peter Pearson wrote:
> Like you, I struggle with BeautifulSoup

Well, there's always lxml.html if you need it.

http://codespeak.net/lxml/

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


How to open a shell prompt from an existing shell prompt

2008-10-29 Thread gaurav kashyap
Dear all.
On windows platform python 2.4,i can use os.startfile("filename") to
execute a file on a new command prompt

but on unix platform and python 2.3 what is the alternate for
executing a file like above in a new shell prompt
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Terry Reedy

Mensanator wrote:

On Oct 29, 4:17�pm, [EMAIL PROTECTED] (Cameron Laird) wrote:


I contest that; my observation is that it's entirely an artifact
of legacy software,


Really? Don't they still use octal for this stuff?

$ ls -l
total 1717
-r-xr-x---+  1 mensanator Users 57 Mar 29  2008 Cygwin.bat
-r-xr-x---+  1 mensanator Users   7022 Mar 29  2008 Cygwin.ico
d-+  5 mensanator None   0 Apr 21  2008 Seed7
-rwxr-xr-x   1 mensanator None   15870 Apr 11  2008 a.exe
|
This would be 0755, wouldn't it? You certainly wouldn't want
to try to figure out the decimal equivalent.


There was a suggestion to dump octal literals.  The above is why they 
were not.


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


Re: Fastest way to convert sql result into a dict or list ?

2008-10-29 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I'm trying to find the fastest way to convert an sql result into a
> dict or list.
> What i mean, for example:
> my sql result:
> contact_id, field_id, field_name, value
> sql_result=[[1, 1, 'address', 'something street'],
>  [1, 2, 'telnumber', '11'],
>  [1, 3, 'email', '[EMAIL PROTECTED]'],
>  [2, 1, 'address','something stree'],
>  [2, 3, 'email','[EMAIL PROTECTED]']]
> the dict can be:
> dict={1:['something street', '11' ,
> '[EMAIL PROTECTED]'],
> 2:['something street', '', '[EMAIL PROTECTED]' ]}
> or a list can be:
> list=[[1,'something street', '11' ,
> '[EMAIL PROTECTED]'],
>[2,'something street', '', '[EMAIL PROTECTED]' ]]
> 
> I tried to make a dict, but i think it is slower then make a list, and
> i tried the "one lined for" to make a list, it's look like little bit
> faster than make a dict.
> 
> def empty_list_make(sql_result):
> return [ [line[0],"", "", ""]   for line in sql_result]
> 
> than fill in the list with another for loop.
> I hope there is an easyest way to do something like this ??
> any idea ?

Why not go for full attribute access? The following code is untested,
yada yada yada.

class recstruct:
   def __init__(self, names, data):
  self.__dict__.update(dict(zip(names, data))

FIELDS = "A B C D".split()
sql = "SELECT %s FROM table" % ", ",join(FIELDS)
curs.execute(sql)
for data in curs.fetchall():
row = recstruct(FIELDS, data)
print row.A, row.B ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Finding the instance reference of an object

2008-10-29 Thread Steve Holden
Joe Strout wrote:
> On Oct 29, 2008, at 4:52 PM, Fuzzyman wrote:
> 
>> You're pretty straightforwardly wrong. In Python the 'value' of a
>> variable is not the reference itself.
> 
> That's the misconception that is leading some folks around here into
> tangled nots of twisty mislogic, ultimately causing them to make up new
> terms for what every other modern language is perfectly happy calling
> Call-By-Value.
> 
I tried hard to make myself believe that the above was a clever pun and
knot [sic] a typo. Sadly I failed.

> I've thought a lot about why this misconception is so widespread here,
> and I think it must be one of the following:
> 
> 1. There was one community leader with this idea, who has been
> successful at promoting it widely, much to the detriment of all; or,
> 
> 2. Because everything in Python is an object, you're not forced to think
> clearly (and more generally) about references as values as you are in
> languages (such as Java, VB.NET, etc.) which have both simple types and
> object types.
> 
How about

3. You just hate being wrong.

> Either way, it's wrong (or at least, a needlessly complicated way of
> looking at things).
> 
One that has apparently served for almost twenty years now.

>> .NET does draw a distinction between 'value types' and reference types
>> - where using reference types are called by reference (the reference
>> is passed) and value types are called by value (the value itself is
>> copied).
> 
> Quite right.  Now, note that "ByRef" and "ByVal" apply to both. 
> Generalize to Python.  There you go.
> 
> Best,
> - Joe
> 
> P.S. I really am trying to quit responding to this thread.  Sometimes
> the urge is too strong.  But I'll keep trying!
> 
We must tax your patience dreadfully. I have suffered from the same
myself, but I fear we are doomed to pursue each other until Godwin's law
releases us.

Which reminds me, had you thought about submitting a paper along these
lines to PyCon? If we meet at PyCon at least let me buy you a pint to
show there are no hard feelings.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: how to use logging module to log an object like print()

2008-10-29 Thread Steve Holden
Diez B. Roggisch wrote:
> Steve Holden schrieb:
>> Diez B. Roggisch wrote:
>>> davy zhang schrieb:
 mport logging
 import pickle


 # create logger
 logger = logging.getLogger("simple_example")
 logger.setLevel(logging.DEBUG)
 # create console handler and set level to debug
 ch = logging.StreamHandler()
 ch.setLevel(logging.DEBUG)
 # create formatter
 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
 - %(message)s ")
 # add formatter to ch
 ch.setFormatter(formatter)
 # add ch to logger
 logger.addHandler(ch)

 d = {'key':'msg','key2':'msg2'}

 # "application" code
 logger.debug("debug message",d)#can not do this
>>> logger.debug("yes you can: %r", d)
>>>
>> One deficiency of this approach, however, is that the string formatting
>> is performed even when no logging is required, thereby wasting a certain
>> amount of effort on unnecessary formatting.
> 
> Nope, it's not. It only happens when the message is really logged.
> 
Vinay, please tell me whether I was right or wrong ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Steve Holden
Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Mensanator  <[EMAIL PROTECTED]> wrote:
>> On Oct 29, 2:44 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
>>> Guilherme Polo wrote:
 On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>  Why gives "k = 09"  a syntax error ?
 09 is not a valid octal number. Instead use 011.
 Ok, I guess you were not aware that prefixing a number with a '0'
 would cause python to parse it as an octal and now you know.
>>> thanks guys,
>>> I didn't realize there were still people using octal notation ;-)
>> Windows users don't have much need for it, but it's still
>> popular with the 'Nix crowd.
>   .
>   .
>   .
> I contest that; my observation is that it's entirely an artifact
> of legacy software, and regarded as no better than a distraction
> by even the most narrow human 'Nixers, or the hardware types who
> might at one time have found octal natural.  My own origins were
> in hardware, Unix, and other DEC OSs, so I consider myself as
> likely as anyone to think in octal--and I rarely do.
> 
> While I can't accept the "popular" part, I agree with you that
> Unix people are at least more likely to recognize the 0-prefix.
> 
They are also more likely to write

  chmod 330 file

than

  chmod ug=rw file

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Mensanator
On Oct 29, 4:17�pm, [EMAIL PROTECTED] (Cameron Laird) wrote:
> In article <[EMAIL PROTECTED]>,
>
>
>
> Mensanator �<[EMAIL PROTECTED]> wrote:
> >On Oct 29, 2:44�pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> >> Guilherme Polo wrote:
> >> > On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
>
> >> >> hello,
>
> >> >> �Why gives "k = 09" �a syntax error ?
>
> >> > 09 is not a valid octal number. Instead use 011.
>
> >> > Ok, I guess you were not aware that prefixing a number with a '0'
> >> > would cause python to parse it as an octal and now you know.
>
> >> thanks guys,
> >> I didn't realize there were still people using octal notation ;-)
>
> >Windows users don't have much need for it, but it's still
> >popular with the 'Nix crowd.
>
> � � � � � � � � � � � � .
> � � � � � � � � � � � � .
> � � � � � � � � � � � � .
> I contest that; my observation is that it's entirely an artifact
> of legacy software,

Really? Don't they still use octal for this stuff?

$ ls -l
total 1717
-r-xr-x---+  1 mensanator Users 57 Mar 29  2008 Cygwin.bat
-r-xr-x---+  1 mensanator Users   7022 Mar 29  2008 Cygwin.ico
d-+  5 mensanator None   0 Apr 21  2008 Seed7
-rwxr-xr-x   1 mensanator None   15870 Apr 11  2008 a.exe
|
This would be 0755, wouldn't it? You certainly wouldn't want
to try to figure out the decimal equivalent.

? and regarded as no better than a distraction
> by even the most narrow human 'Nixers,

Appears necessary to me.

> or the hardware types who
> might at one time have found octal natural. �My own origins were
> in hardware, Unix, and other DEC OSs, so I consider myself as
> likely as anyone to think in octal--and I rarely do.
>
> While I can't accept the "popular" part,

I meant popular as in ubiquitous, not that I imagined there was
anybody who liked to use it.

> I agree with you that
> Unix people are at least more likely to recognize the 0-prefix.

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


Re: is there a way to access postgresql in python3.0rc1

2008-10-29 Thread Steve Holden
Terry Reedy wrote:
> davy zhang wrote:
>> I'm currently on a  project, it could last for at least 1 or 2 years.
>> so I choose python3 as server side programing language.
>> All I found on are python2.x ready libraries, Is there any library is
>> python3.0 ready? or just under alpha ,beta or something, I don't much
>> features, just basic functions are OK
> 
> Python3.0 final should be released in about a month.  Extension
> libraries will start appearing after that.  You will have to ask the
> maintainers of a particular library what their plans are for Python 3.
> Some will port very easily and could be available soon.  Others will
> take more work and may not appear so soon.
> 
Please note, however, that Python 3.x is not likely to be as
well-supported by extension modules as Python 2.x for some considerable
time. The OP may therefore wish to reconsider his choice of Python 3.0.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: how to use logging module to log an object like print()

2008-10-29 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On 29 Ott, 12:24, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Diez B. Roggisch wrote:
>>> davy zhang schrieb:
 mport logging
 import pickle
 # create logger
 logger = logging.getLogger("simple_example")
 logger.setLevel(logging.DEBUG)
 # create console handler and set level to debug
 ch = logging.StreamHandler()
 ch.setLevel(logging.DEBUG)
 # create formatter
 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
 - %(message)s ")
 # add formatter to ch
 ch.setFormatter(formatter)
 # add ch to logger
 logger.addHandler(ch)
 d = {'key':'msg','key2':'msg2'}
 # "application" code
 logger.debug("debug message",d)#can not do this
>>> logger.debug("yes you can: %r", d)
>> One deficiency of this approach, however, is that the string formatting
>> is performed even when no logging is required, thereby wasting a certain
>> amount of effort on unnecessary formatting.
>>
>> regards
>>  Steve
>> --
>> Steve Holden+1 571 484 6266   +1 800 494 3119
>> Holden Web LLC  http://www.holdenweb.com/- Nascondi testo citato
>>
> 
> Sure about that?
> 
> This is the implementation of Logger.debug in
> the file : ..Python25\lib\logging\__init__.py
> 
>def debug(self, msg, *args, **kwargs):
> """
> Log 'msg % args' with severity 'DEBUG'.
> 
> To pass exception information, use the keyword argument
> exc_info with
> a true value, e.g.
> 
> logger.debug("Houston, we have a %s", "thorny problem",
> exc_info=1)
> """
> if self.manager.disable >= DEBUG:
> return
> if DEBUG >= self.getEffectiveLevel():
> apply(self._log, (DEBUG, msg, args), kwargs)
> 
> 
> The other methods (info, warning, ...) are similar. It looks like
> the formatting is only done if actually used.
> 
Pretty sure, and Vinay's reply convinced me I was correct. He should
know, after all ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: [Novice]Installing eric4 with python 2.6

2008-10-29 Thread Steve Holden
Saurabh Agrawal wrote:
> 
> PyQt supported Python 2.6 on the day it was released.
> 
> A snapshot of the PyQt Windows installer for Python 2.6 can be
> downloaded
> from the same page as you downloaded the installer for Python 2.5.
> 
> Phil
> --
> 
> 
> 
> 
> Thanks Phil, it worked. My bad, sorry.
> 
... and thanks for offering such great support to 2.6, Phil. PyQt is one
of those package that just goes on Just Working (tm).

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Improving interpreter startup speed

2008-10-29 Thread Steve Holden
BJörn Lindqvist wrote:
> 2008/10/27 James Mills <[EMAIL PROTECTED]>:
>> On Mon, Oct 27, 2008 at 5:40 PM, David Cournapeau <[EMAIL PROTECTED]> wrote:
>>> Depends on the tool: build tool and source control tools are example
>>> it matters (specially when you start interfaciing them with IDE or
>>> editors). Having fast command line tools is an important feature of
>>> UNIX, and if you want to insert a python-based tool in a given
>>> pipeline, it can hurt it the pipeline is regularly updated.
>> Fair enough. But still:
>> 0.5s old startup is fast enough
>> 0.08s warm startup is fast enough.
>>
>> Often "fast enough" is "fast enough"
> 
> Nope, when it comes to start up speed the only thing that is fast
> enough is "instantly." :) For example, if I write a GUI text editor in
> Python, the total cold start up time might be 1500 ms on a cold
> system. 750 ms for the interpreter and 750 ms for the app itself.
> However, if I also have other processes competing for IO, torrent
> downloads or compilations for example, the start up time grows
> proportional to the disk load. For example, if there is 50% constant
> disk load, my app will start in 1.5 / (1 - 0.5) = 3 seconds (in the
> best case, assuming IO access is allocated as efficiently as possible
> when the number of processes grows, which it isn't). If the load is
> 75%, the start time becomes 1.5 / (1 - 0.75) = 6 seconds.
> 
> Now if the Python interpreters start up time was 200 ms, by apps start
> up time with 75% disk load becomes (0.2 + 0.75) / (1 - 0.75) = 3.8
> seconds which is significantly better.
> 
> 
But still not fast enough to be regarded as even close to "instant", so
you appear to be fiddling while Rome burns ...

reqards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Regarding shared memory

2008-10-29 Thread gaurav kashyap
Dear all,

I have a server program that listens to a particular port and a number
of client programs that connect to the server.

Now i want to put some data in form of python list in main memory on
server.Hence whenver a client program is run it connects to the server
and access the data in main memory.Here the server calls a module that
processes the data as per the client request and the returns some
information to the client.

I can create client and server programs using socket programming,but i
am not able to put the data in shared memory and then access it.

NOTE:I want to put the data in main memory only once(on the server
using server program) i.e. whenever client connects to the server it
should only access the data and not create a replica of data already
loaded in memory.How can this be achieved

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


download image from flickr.com

2008-10-29 Thread He Jibo
Dear Pythoners,

Could you please help me look at a code, which is to download image
from flickr.com? I wish to download images from flickr.com
automatically. You can get the code at
http://cid-bbc15003189d7799.skydrive.live.com/self.aspx/Public/FImageCrawl.py.
There is still some problem with the code. I do not know much about
regular expression. There seems to be something wrong with the line of
"compile_obj = re.compile(r'dyn.Img\(".*?",".*?",".*?","(.*?)"')".
Could you please help me debug it? And I aslo hope to download the
first 10 pages of the images, how can I do this?

Thank you so much ! Good night!

He Jibo
[EMAIL PROTECTED]
[EMAIL PROTECTED]


---
He Jibo
Department of Psychology,
Beckman Institute for Advanced Science and Technology
University of Illinois, Urbana Champaign,
603 East Daniel St.,
Champaign, IL 61820
Tel: 217-244-4461(office)
217-244-6763(lab)
Email: [EMAIL PROTECTED]
Yogi Berra  - "Half the lies they tell about me aren't true."
--
http://mail.python.org/mailman/listinfo/python-list


Re: set/dict comp in Py2.6

2008-10-29 Thread Benjamin
On Oct 27, 3:38 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Sat, 25 Oct 2008 23:44:46 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> >> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> >> dicts of Python 3.0, like:
>
> > Because nobody bothered to backport them.
>
> En Sat, 25 Oct 2008 23:47:32 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > Because nobody bothered to backport them.
>
> En Mon, 27 Oct 2008 00:17:20 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > Because nobody bothered to backport it.
> > En Mon, 27 Oct 2008 00:19:29 -0200, Benjamin  
> > <[EMAIL PROTECTED]> escribió:
> > Because nobody bothered to backport it.
>
> Yeah, we already know... :)

Sorry about that.
>
> --
> Gabriel Genellina

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


Need some help speeding up this loop

2008-10-29 Thread erikcw
Hi all,

I'm trying to write a loop that will build a list of "template
strings".

My current implementation is *really slow*.  It took 15 minutes to
finish. (final len(list) was about 16k entries.)

#combinations = 12 small template strings ie "{{ city }},
{{ state }}..."
#states = either a django model or a list of 50 states
#cities = either a django model of 400 cities or a smaller list of
cities.

templates = []
for c in combinations:
if len(states):
for state in states:
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
city = city.city
templates.append(c.template.replace('{{ city }}',
city))
templates.append(c.template) #just in case there are no
cities
templates = [k.replace('{{ state }}',
state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
templates]
elif len(geo):
for city in geo:
templates.append(c.template.replace('{{ city }}', city))
else:
#no cities or states so add roots
templates.append(c.template)

The final output needs to be a list of the templates combined with all
the states and cities (some templates will only have the city, some
only the state).

Any ideas how I can optimize this?

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


Earn 5000$ To 10000$ In every Month.

2008-10-29 Thread chinu
hai,
i am srinu from india. i am sending a blog url for yours use.


Right side Of The Blog Awsurvey Banner will appear.

click on the banner and get a free signup with 6$ bonus and you will
get more surveys.
once you have completed one survey you will get minimem 4$ and more

left side of the blog home based jobs will appear
click on the ads you will get more details about to choose your job.

you willnot satisfy to choose your job
you will type jobs or sports or jewelery etc on
search box field .and click on search.
then you will find what resuilts are you want.




click on the blog and get more information to choose yours job.

the blog url is:


   http://wealthinonline.blogspot.com/



 goodluck

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


Re: math equation, svg and matplotlib

2008-10-29 Thread André
On Oct 29, 6:34 pm, kib2 <[EMAIL PROTECTED]> wrote:
> André a écrit :
>
> > Would anyone have a "quick and dirty" code sample to create an svg
> > output of a sample math equation using matplotlib?
>
> > André
>
> Hi André,
>
> maybe that's not what you want be there's something like this here (a
> converter from DVI to SVG in pure Python), look at the samples at the bottom
> of the page:
>
> http://www.wmula.republika.pl/proj/pydvi2svg/index.html#samples

Your project looks very interesting; however, I figured out a way to
do it.  It required doing a bit of playing around with one
comprehensive examples on the matplotlib gallery.

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


Re: guenstige kredite

2008-10-29 Thread [EMAIL PROTECTED]
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
http://www.officeformac.com/ProductForums/WindowsMediaPlayerMac/275 -
kredit ohne schufa ohne kredit ohne schufa ohne vorkosten
--
http://mail.python.org/mailman/listinfo/python-list


Re: Graphical object browser

2008-10-29 Thread Jason
Hooray! I discovered PyCrust. I made this script (for Linux - under
Win, you could just have all but the first line as a python file and
run it directly):

#!/usr/bin/python
import wx
import wx.py.PyCrust

if __name__ == '__main__' :
app = wx.App()
pc = wx.py.PyCrust.App(app)
pc.MainLoop()

Run it from the working dir and tinker from there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-29 Thread Joe Strout

On Oct 29, 2008, at 4:52 PM, Fuzzyman wrote:


You're pretty straightforwardly wrong. In Python the 'value' of a
variable is not the reference itself.


That's the misconception that is leading some folks around here into  
tangled nots of twisty mislogic, ultimately causing them to make up  
new terms for what every other modern language is perfectly happy  
calling Call-By-Value.


I've thought a lot about why this misconception is so widespread here,  
and I think it must be one of the following:


1. There was one community leader with this idea, who has been  
successful at promoting it widely, much to the detriment of all; or,


2. Because everything in Python is an object, you're not forced to  
think clearly (and more generally) about references as values as you  
are in languages (such as Java, VB.NET, etc.) which have both simple  
types and object types.


Either way, it's wrong (or at least, a needlessly complicated way of  
looking at things).



.NET does draw a distinction between 'value types' and reference types
- where using reference types are called by reference (the reference
is passed) and value types are called by value (the value itself is
copied).


Quite right.  Now, note that "ByRef" and "ByVal" apply to both.   
Generalize to Python.  There you go.


Best,
- Joe

P.S. I really am trying to quit responding to this thread.  Sometimes  
the urge is too strong.  But I'll keep trying!


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


Re: Filter function and lists

2008-10-29 Thread Mensanator
On Oct 29, 4:28 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> John Townsend wrote:
> > I’m trying to figure out how to use filter to walk through a list.
>
> > If I try a simple scripts like this:
>
> > def greaterthanten (number):
> >                 #pdb.set_trace()
> >                 if (number > 10):
> >                                 ret_val = 1
>
> >                 else:
> >                                 ret_val = 0
>
> >                 return ret_val
>
> > old_list = [1,2,20,30,5]
>
> > new_list = filter(greaterthanten, old_list)
>
> > #new_list becomes [20, 30]
>
> > The script works as I would expect. However, what if I need to pass more
> > than one argument to the function? Can I do that with filter? Or does
> > filter work only with function that take only a single arg?

That single argument could be a list.

>>> old_list = [1,2,20,30,5]

>>> def power_of_10(a):
if a[0]%10==0 and a[0]>> new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in 
>>> old_list])]
>>> new_list

[20, 30]

>>> the_limit = 25
>>> new_list = [i[0] for i in filter(power_of_10,[[i,the_limit] for i in 
>>> old_list])]
>>> new_list

[20]



>
> The latter.  Other functions could be wrapped to bind all parameters
> except the list element.  Or write an explicit loop.- Hide quoted text -
>
> - Show quoted text -

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Terry Reedy

Mensanator wrote:

On Oct 29, 4:25 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

Stef Mientki wrote:

hello,
Why gives "k = 09"  a syntax error ?

You have gotten the 2.x answer.  In 3.0, 0b,0o,0x prefixes are valid and
required for binary, octal, and hexadecimal literals.  0digits is invalid.


except 00, 000, etc.



Is it documented? :-)


Very clearly.

Integer literals
Integer literals are described by the following lexical definitions:

integer::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"+
nonzerodigit   ::=  "1"..."9"
digit  ::=  "0"..."9"
octinteger ::=  "0" ("o" | "O") octdigit+
hexinteger ::=  "0" ("x" | "X") hexdigit+
bininteger ::=  "0" ("b" | "B") bindigit+
octdigit   ::=  "0"..."7"
hexdigit   ::=  digit | "a"..."f" | "A"..."F"
bindigit   ::=  "0" | "1"

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


Re: Finding the instance reference of an object

2008-10-29 Thread Steven D'Aprano
On Wed, 29 Oct 2008 08:27:07 -0700, Dale Roberts wrote:

> On Oct 28, 11:59 am, Joe Strout <[EMAIL PROTECTED]> wrote:
>> ...
>>
>> There are only the two cases, which Greg quite succinctly and
>> accurately described above.  One is by value, the other is by
>> reference.  Python quite clearly uses by value.  Parameters are
>> expressions that are evaluated, and the resulting value copied into the
>> formal parameter, pure and simple.  The continued attempts to obfuscate
>> this is pointless and wrong.
>>
>> Best,
>> - Joe
> 
> Joe, you are being too generous and expansive here.
> 
> [Play along with me for a minute here...]
> 
> Don't you know? There is really only *ONE* case, and, you are right, it
> is Pass By Value. There is no such thing as Pass By Reference at the
> physical CPU level at all, right? If there is, show it to me. Pass By
> Reference is just a silly idiom developed by high-minded CS academics to
> confuse the rest of us. It has no practical use and should not be given
> its own name, when we already have a good an proper name for it.
[snip]

But Dale, you're wrong. At the physical CPU level, there's no copying of 
bits at all. If we could copy bits, then we could start with 512MB of RAM 
and say "copy all the bits" and end up with 1GB of RAM. So-called copying 
is actually just bit-flipping.

So anyone who talks about copying parameters is talking nonsense. There 
is no "pass by value". It's all pass by bit-flipping.



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


Re: how to get the thighest bit position in big integers?

2008-10-29 Thread Terry Reedy

Mensanator wrote:


You would think when you add a new function, you would
also add it's documentation, but maybe that was an
oversight. I don't have 3.0, but maybe it can be found
in that set of docs.

3.0c1
>>> help(bin)
Help on built-in function bin in module builtins:

bin(...)
bin(number) -> string

Return the binary representation of an integer or long integer.

Manual
bin(x)
Convert an integer number to a binary string. The result is a valid 
Python expression. If x is not a Python int object, it has to define an 
__index__() method that returns an integer.


You can file a doc bug for whatever is missing in 2.6.  You might check 
other 3.0 builtins that were backported.


tjr

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


Re: Finding the instance reference of an object

2008-10-29 Thread Fuzzyman
On Oct 28, 3:59 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Oct 27, 2008, at 11:28 PM, Gabriel Genellina wrote:
>
>
>
> > En Tue, 28 Oct 2008 00:58:10 -0200, greg  
> > <[EMAIL PROTECTED]> escribió:
>
> >> Let's look at the definitions of the terms:
>
> >> (1) Call by value: The actual parameter is an expression. It is
> >>    evaluated and the result is assigned to the formal parameter.
> >>    Subsequent assignments to the formal parameter do not affect
> >>    the actual parameter.
>
> >> (2) Call by reference: The actual parameter is an lvalue. The
> >>    formal parameter becomes an alias for the actual parameter,
> >>    so that assigning to the formal parameter has the same
> >>    effect as assigning to the actual parameter.
>
> >> Seems to me that (1) describes exactly how parameter passing
> >> works in Python. So why insist that it's *not* call by value?
>
> Greg is right on the money here.  It really is as simple as that.
>
> > Those definitions are only applicable to unstructured, primitive  
> > types, where the only relevant operations are "get value" and  
> > "assign value".
>
> Nonsense.  They apply to any type.  See here for an introduction to  
> the topic in VB.NET:
>
>    http://www.homeandlearn.co.uk/net/nets9p4.html
>
> The example shown uses an Integer, but guess what -- you can pass ANY  
> type either ByRef or ByVal, including object references (which are, of  
> course, quite common in VB.NET).  The default is ByVal, which means  
> that (as in Python) the actual parameter is an expression, and no  
> assignments to it can affect the actual parameter.  It DOES NOT MATTER  
> that both the formal parameter and the actual parameter may refer to  
> the same object, and if that object is mutable, you can mutate that  
> object.
>

You're pretty straightforwardly wrong. In Python the 'value' of a
variable is not the reference itself. If that sentence has any meaning
for Python then the value is the object itself.

.NET does draw a distinction between 'value types' and reference types
- where using reference types are called by reference (the reference
is passed) and value types are called by value (the value itself is
copied).

Value types (all numeric types, structs, enumerations etc) actually
live on the stack, whereas reference types (strings, classes etc) live
in the heap and have a
pointer on the stack.

It is complicated by the fact that .NET perpetuates the myth that the
primitives (the value types) inherit from System.Object (a reference
type). The runtime does auto-boxing for you where this matters.

This means that when you pass a value type into a method the value
*is* copied. Structs can be arbitrarily big, so this can be a
performance problem. It is often a performance win for working with
the numeric types as you remove a level of indirection.

It isn't without problems though - and some of these can be seen in
IronPython.

System.Drawing.Point is a struct, but it is effectively a mutable
value type. However, when you access it you are often accessing a copy
- and if you attempt to mutate it then your changes will be lost.

The following code illustrates the problem:

>>> r = Rectangle(0, 1002 20, 40)
>>> r.Location.X
0
>>> r.Location.X = 20
>>> r.Location.X

0

Because r.Location returns a value type (a Point), the update to it is
'lost'.

By this definition Python objects (all of them) are clearly reference
ypes and not value types.

In .NET you can specify that a parameter to a method takes a reference
('out' in C# or ByRef in VB.NET). If you pass in a value type as a
reference parameter then the .NET runtime will do boxing / unboxing
for you.

This means that we can write code like the following C#:

int x = 3;
SomeMethod(out x);

The value of x can be changed by 'SomeMethod' and can have a different
value - something that can't happen in Python.

In a 'way' immutable Python types behave a bit like .NET value types,
and mutable types like reference types. As you can see, this analogy
breaks down.

Michael Foord
--
http://www.ironpythoninaction.com/



> But ByRef is another option, and if you pass an object reference  
> ByRef, then the formal parameter is an alias for the actual parameter,  
> and assignments to it change the actual parameter.  Python doesn't  
> have this feature (nor much need for it, given its other features,  
> like tuple packing/unpacking).  So, parameter passing in ByRef is  
> clearly exactly the same as the default "ByVal" parameter passing in  
> VB.NET... as well as Java, RB, C++ (when you remember that an object  
> reference in modern languages is like a pointer in C++), and every  
> other OOP language I've looked into.
>
> Some of those languages, like Python, don't have different modes, and  
> so the language designers had no call to give their one mode a name.  
> So let's look at those that did have such a need, like VB.NET and  
> REALbasic.  What's the default mode called?  Why, it's "ByVal".  Even  
> when that value is an

Re: 2.6, 3.0, and truly independent intepreters

2008-10-29 Thread Patrick Stinson
If you are dealing with "lots" of data like in video or sound editing,
you would just keep the data in shared memory and send the reference
over IPC to the worker process. Otherwise, if you marshal and send you
are looking at a temporary doubling of the memory footprint of your
app because the data will be copied, and marshaling overhead.

On Fri, Oct 24, 2008 at 3:50 PM, Andy O'Meara <[EMAIL PROTECTED]> wrote:
>
>
>> Are you familiar with the API at all? Multiprocessing was designed to
>> mimic threading in about every way possible, the only restriction on
>> shared data is that it must be serializable, but event then you can
>> override or customize the behavior.
>>
>> Also, inter process communication is done via pipes. It can also be
>> done with messages if you want to tweak the manager(s).
>>
>
> I apologize in advance if I don't understand something correctly, but
> as I understand them, everything has to be serialized in order to go
> through IPC.  So when you're talking about thousands of objects,
> buffers, and/or large OS opaque objects (e.g. memory-resident video
> and images), that seems like a pretty rough hit of run-time resources.
>
> Please don't misunderstand my comments to suggest that multiprocessing
> isn't great stuff.  On the contrary, it's very impressive and it
> singlehandedly catapults python *way* closer to efficient CPU bound
> processing than it ever was before.  All I mean to say is that in the
> case where using a shared address space with a worker pthread per
> spare core to do CPU bound work, it's a really big win not to have to
> serialize stuff.  And in the case of hundreds of megs of data and/or
> thousands of data structure instances, it's a deal breaker to
> serialize and unserialize everything just so that it can be sent
> though IPC.  It's a deal breaker for most performance-centric apps
> because of the unnecessary runtime resource hit and because now all
> those data structures being passed around have to have accompanying
> serialization code written (and maintained) for them.   That's
> actually what I meant when I made the comment that a high level sync
> object in a shared address space is "better" then sending it all
> through IPC (when the data sets are wild and crazy).  From a C/C++
> point of view, I would venture to say that it's always a huge win to
> just stick those "embarrassingly easy" parallelization cases into the
> thread with a sync object than forking and using IPC and having to
> write all the serialization code. And in the case of huge data types--
> such as video or image rendering--it makes me nervous to think of
> serializing it all just so it can go through IPC when it could just be
> passed using a pointer change and a single sync object.
>
> So, if I'm missing something and there's a way so pass data structures
> without serialization, then I'd definitely like to learn more (sorry
> in advance if I missed something there).  When I took a look at
> multiprocessing my concerns where:
>   - serialization (discussed above)
>   - maturity (are we ready to bet the farm that mp is going to work
> properly on the platforms we need it to?)
>
> Again, I'm psyched that multiprocessing appeared in 2.6 and it's a
> huge huge step in getting everyone to unlock the power of python!
> But, then some of the tidbits described above are additional data
> points for you and others to chew on.  I can tell you they're pretty
> important points for any performance-centric software provider (us,
> game developers--from EA to Ambrosia, and A/V production app
> developers like Patrick).
>
> Andy
>
>
>
>
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: beutifulsoup

2008-10-29 Thread Peter Pearson
On Wed, 29 Oct 2008 09:45:31 -0700 (PDT), luca72 <[EMAIL PROTECTED]> wrote:
> Hello
> I try to use beautifulsoup
> i have this:
> sito = urllib.urlopen('http://www.prova.com/')
> esamino = BeautifulSoup(sito)
> luca = esamino.findAll('tr', align='center')
>
> print luca[0]
>
[The following long string has been wrapped.]
>>>#144.4MB
   
Pc-prova.rar 
>
> I need to get the following information:
> 1)Only|G|BoT|05
> 2)#1
> 3)44.4MB
> 4)Pc-prova.rar
> with: print luca[0].a.stringi get #1
> with print luca[0].td.stringi get 44.4MB
> can you explain me how to get the others two value

Like you, I struggle with BeautifulSoup; but perhaps this will help
while waiting for somebody smarter to join the thread:

>>> soup = BeautifulSoup.BeautifulSoup(
... ""
... """#1"""
... """44.4MB"""
... """ Pc-prova.rar """ )
>>> tr = soup.findAll( 'tr' )
>>> tr[0].findAll( text = True )
[u'#1', u'44.4MB', u' Pc-prova.rar ']
>>> c = tr[0].findChild( attrs={"onclick": True} )
>>> print c[ "onclick" ]
t('Only|G|BoT|05','#1');


-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: free IDE with removing import and refactoring

2008-10-29 Thread Fabio Zadrozny
> I am looking for a python IDE which can remove my unused imports, and
> can do basic refactoring under windows.

If you have Pydev Extensions, it analyzes your source for undefined
tokens and is able to make the imports for you (but it doesn't remove
the unused imports... especially because this can be very tricky in
Python, where tokens can be imported from one module to another --
different from java, where the only thing you import are actually the
classes, so, in practice, the effectiveness in Python for that feature
is not the same as in Java, still, being able to write the imports for
you is really useful:
http://fabioz.com/pydev/manual_adv_complnoctx.html and ctrl+shift+O
for it to write the imports for the undefined tokens)

Also, basic refactoring is available.

> Besides, an installation howto would be useful for me.

Start here: http://fabioz.com/pydev/manual_101_root.html

Cheers,

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Mensanator  <[EMAIL PROTECTED]> wrote:
>On Oct 29, 2:44 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
>> Guilherme Polo wrote:
>> > On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
>>
>> >> hello,
>>
>> >>  Why gives "k = 09"  a syntax error ?
>>
>> > 09 is not a valid octal number. Instead use 011.
>>
>> > Ok, I guess you were not aware that prefixing a number with a '0'
>> > would cause python to parse it as an octal and now you know.
>>
>> thanks guys,
>> I didn't realize there were still people using octal notation ;-)
>
>Windows users don't have much need for it, but it's still
>popular with the 'Nix crowd.
.
.
.
I contest that; my observation is that it's entirely an artifact
of legacy software, and regarded as no better than a distraction
by even the most narrow human 'Nixers, or the hardware types who
might at one time have found octal natural.  My own origins were
in hardware, Unix, and other DEC OSs, so I consider myself as
likely as anyone to think in octal--and I rarely do.

While I can't accept the "popular" part, I agree with you that
Unix people are at least more likely to recognize the 0-prefix.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to Implement an XMLRPC Server in Python?

2008-10-29 Thread Zix
On Oct 29, 11:26 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> These pages might be useful, they include example code:

Thanks Daniel, they do help.

On Oct 29, 11:42 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> Why did you decide to "expose" a web service through xmlrpc instead of
> actually exposing it by using a restful web service ?
> ...
> I'm still surprised on this decision specially because you said you
> read a lot about this topic.

The basic idea behind this app is for me to get comfortable in
building web applications with Python. The REST architechture, while
sounding simple seemed a bit too much work to implement. I am
comfortable with xmlrpc since I've built xmlrpc clients using Perl. So
in summary, no REST because I felt lazy. :)

(I do like how Google has implemented REST with their GData API -
http://code.google.com/apis/gdata/overview.html - they also offer
GData python client library. A GData "server" in Python would be cool!)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-29 Thread Chuckk Hubbard
On Wed, Oct 29, 2008 at 5:27 PM, Dale Roberts <[EMAIL PROTECTED]> wrote:
> Don't you know? There is really only *ONE* case, and, you are right,
> it is Pass By Value. There is no such thing as Pass By Reference at
> the physical CPU level at all, right? If there is, show it to me. Pass
> By Reference is just a silly idiom developed by high-minded CS
> academics to confuse the rest of us. It has no practical use and
> should not be given its own name, when we already have a good an
> proper name for it.
>
> Let me demonstrate with 3 examples of a function definition, and the
> appropriate calling syntax for that function in C++, all sharing the
> common "int i" global variable:
>
> int i = 5;
>
> myfunc(int &val){}   /*CALL:*/ myfunc(i);// "ByRef" (ya, right!)
> myfunc(int val){}/*CALL:*/ myfunc(i);// ByVal
> myfunc(int *val){}   /*CALL:*/ myfunc(&i);   // Joe's ByVal
>
> The first is what all the fakers call "Pass By Reference" - sheesh,
> how naive. We all know that what *really* happens internally is that
> the *address* of val (A VALUE itself, or course) is copied and passed
> on the stack, right? There couldn't be a more straightforward example
> of Pass By Value (unless it's an inline function, or optimized away,
> or possibly when implemented in a VM, or...). It passes the *address*
> of i by value, then we can access the *value* of i too via
> indirection. Hmm, did we need to have two definitions of VALUE there?
> Well, never mind, no one will notice...
>
> The next is obviously pass by value. It's right out there. The value
> of i (which is what we are talking about, right?) is copied out, and
> passed right on the stack in plain daylight where we can all see it.
>
> How about the third? Pass By Value, obviously, of course. This is the
> version you are defending, right? The parameter's value, &i, is
> evaluated and copied right onto the stack, just like in the first
> example. In fact, if you compare the assembler output of the first and
> third examples, you may not even see a difference. Never mind the
> actual contents of that pesky "i" variable that most people are
> referring to when they use the term "value". We don't need to dress up
> example 3 and call it an "idiom" where we are really passing a so-
> called "reference" of the variable "i". Indeed! Don't insult our
> intelligence. We can all see that it's an address passed by value,
> plain and simple.
>
>
> Pass By Reference? So "postmodern". Who needs it. Show me a so-called
> "reference". I've looked at the assembler output and have never seen
> one. There is no such thing.

You are so right!  We also don't need "object-oriented programming".
I looked at the motherboard and I don't see any objects moving around!
 I don't see any values being passed, either.
When I turn on the TV and see Chuck Norris, though, I know it's only a
reference to Chuck Norris, or I would be blinded.  The only case he
needs is "Pass By Roundhouse Kick".

-Chuckk


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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Robert Kern

Mensanator wrote:

On Oct 29, 4:25 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

Stef Mientki wrote:

hello,
Why gives "k = 09"  a syntax error ?

You have gotten the 2.x answer.  In 3.0, 0b,0o,0x prefixes are valid and
required for binary, octal, and hexadecimal literals.  0digits is invalid.

tjr


Is it documented? :-)


Yes.

http://www.python.org/dev/peps/pep-3127/

--
Robert Kern

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

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Mensanator
On Oct 29, 4:25 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Stef Mientki wrote:
> > hello,
>
> > Why gives "k = 09"  a syntax error ?
>
> You have gotten the 2.x answer.  In 3.0, 0b,0o,0x prefixes are valid and
> required for binary, octal, and hexadecimal literals.  0digits is invalid.
>
> tjr

Is it documented? :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-29 Thread Mensanator
On Oct 29, 4:16 pm, Glenn Linderman <[EMAIL PROTECTED]> wrote:
> On approximately 10/29/2008 11:51 AM, came the following characters from
> the keyboard of Mensanator:
>
> > or in 2.6
>
> > print 'highest bit position: %d' % (len(bin(3328)[2:])-1)
>
> > highest bit position: 11
>
> This works, but where is it documented?  

Good question. Now that I think about it, I believe I learned of
it here, never saw it in the docs.

> Searching the Python 2.6 docs
> for bin found lots of things that start with bin, but none of them were
> bin.  Searching the builtins page manual didn't find it.  Is this a bug
> in the documentation?

Well ,it's mentioned in "What's new in Python 2.6":

Python 3.0 adds several new built-in functions
and change the semantics of some existing built-ins.
Entirely new functions such as bin() have simply
been added to Python 2.6, but existing built-ins
haven’t been changed;


You would think when you add a new function, you would
also add it's documentation, but maybe that was an
oversight. I don't have 3.0, but maybe it can be found
in that set of docs.

>
> --
> Glenn --http://nevcal.com/
> ===
> A protocol is complete when there is nothing left to remove.
> -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking

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


Re: math equation, svg and matplotlib

2008-10-29 Thread kib2

André a écrit :

Would anyone have a "quick and dirty" code sample to create an svg
output of a sample math equation using matplotlib?

André


Hi André,

maybe that's not what you want be there's something like this here (a 
converter from DVI to SVG in pure Python), look at the samples at the bottom 
of the page:


http://www.wmula.republika.pl/proj/pydvi2svg/index.html#samples
--
http://mail.python.org/mailman/listinfo/python-list


Re: project in python

2008-10-29 Thread Terry Reedy

asit wrote:

On Oct 28, 10:02 am, alex23 <[EMAIL PROTECTED]> wrote:

On Oct 26, 2:51 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:


The more you spam people with your repetitive postings, the less likely it
becomes that they are willing to answer you.

In asit's defence, the Google Groups interface has been woefully
broken for the past 3-4 days. If e had posted via it, messages
wouldn't have been visible to em until today at the earliest.


gmane.comp.python.general at the free and open (no login) news.gmane.org 
works much better than gg.




After all these search and queries, I have decided to make smething
about Google API.

Is there an API available for google group ???
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: Filter function and lists

2008-10-29 Thread Terry Reedy

John Townsend wrote:

I’m trying to figure out how to use filter to walk through a list.
 
If I try a simple scripts like this:
 
def greaterthanten (number):

#pdb.set_trace()
if (number > 10):
ret_val = 1
   
else:

ret_val = 0
   
return ret_val
 
old_list = [1,2,20,30,5]
 
new_list = filter(greaterthanten, old_list)
 
#new_list becomes [20, 30]
 
The script works as I would expect. However, what if I need to pass more 
than one argument to the function? Can I do that with filter? Or does 
filter work only with function that take only a single arg?


The latter.  Other functions could be wrapped to bind all parameters 
except the list element.  Or write an explicit loop.


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


win32pipe.popen4 howto example

2008-10-29 Thread yaipa

trying to remind myself that running a subprocess under Win32 isn't a
pain in the ass... ];^)

###
#!/usr/bin/env python

'''
original author
credits: chris levis

original sources found:
http://mail.python.org/pipermail/python-list/2005-August/336390.html

from python docs,
17.4 popen2 -- Subprocesses with accessible I/O streams

popen4(cmd [, bufsize[, mode]])
Executes cmd as a sub-process.
Returns the file objects (child_stdout_and_stderr,
child_stdin).
  -- New in version 2.0.

If,
o   bufsize,  is provided,   it specifies the buffer size for
the I/O pipes.
o   mode,is provided,   the string 'b' or 't';
-  'b'  required on Windows for binary read access
-  't'  (text mode) is default
'''

'''
External test file.

test_exit_code.py

 start snippet  -

import sys

print "hello, world"
sys.exit(-1)

 end snippet  ---

'''

import win32pipe;

cmd = 'test_exit_code.py'

  # open stdout pseudo file in textmode 't'
(stdin,stdout) = win32pipe.popen4( cmd, 't' );

stdin.close();
output = stdout.read();
try:
exitcode = stdout.close() or 0;
except IOError:
exitcode = ( -1 );

print output ## prints 'hello world'
print exitcode   ## print '-1'

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Terry Reedy

Stef Mientki wrote:

hello,

Why gives "k = 09"  a syntax error ?


You have gotten the 2.x answer.  In 3.0, 0b,0o,0x prefixes are valid and 
required for binary, octal, and hexadecimal literals.  0digits is invalid.


tjr

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


Re: Python Regex Question

2008-10-29 Thread Terry Reedy

MalteseUnderdog wrote:

Hi there I just started python (but this question isn't that trivial
since I couldn't find it in google :) )

I have the following text file entries (simplified)

start  #frag 1 start
x=Dog # frag 1 end
stop
start# frag 2 start
x=Cat # frag 2 end
stop
start #frag 3 start
x=Dog #frag 3 end
stop


I need a regex expression which returns the start to the x=ANIMAL for
only the x=Dog fragments so all my entries should be start ...
(something here) ... x=Dog .  So I am really interested in fragments 1
and 3 only.


As I understand the above
I would first write a generator that separates the file into fragments 
and yields them one at a time.  Perhaps something like


def fragments(ifile):
  frag = []
  for line in ifile:
frag += line
if :
  yield frag
  frag = []

Then I would iterate through fragments, testing for the ones I want:

for frag in fragments(somefile):
  if 'x=Dog' in frag:


Terry Jan Reedy

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


Re: project in python

2008-10-29 Thread asit
On Oct 28, 10:02 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Oct 26, 2:51 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
>
> > The more you spam people with your repetitive postings, the less likely it
> > becomes that they are willing to answer you.
>
> In asit's defence, the Google Groups interface has been woefully
> broken for the past 3-4 days. If e had posted via it, messages
> wouldn't have been visible to em until today at the earliest.

After all these search and queries, I have decided to make smething
about Google API.

Is there an API available for google group ???
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Numeric users be aware!

2008-10-29 Thread Robert Kern

Benyang Tang wrote:

I also found that the a[5:] problem is Python version dependent.

On a 64-bit linux, of the following combinations I have tried, only
the first one has the problem. The other two are ok.
* Python 2.5.1 and Numeric 24.2
* Python 2.4.5 and Numeric 24.2
* Python 2.3.7 and Numeric 24.2


Python 2.5.1 introduced the use of Py_ssize_t for indices. Previously, those 
functions took C ints. Numeric 24.2 predates Python 2.5 substantially.


--
Robert Kern

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

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


Re: Python suitable for Midi ?

2008-10-29 Thread J Kenneth King
Derek Martin <[EMAIL PROTECTED]> writes:

> On Tue, Oct 28, 2008 at 06:54:57PM +0200, Chuckk Hubbard wrote:
>> The problem I've run into is that I can't set the audio to a higher
>> priority than the GUI (Tkinter).  If I move the mouse over the app, no
>> matter what, I get audio dropouts.  AFAICT this is the same for all
>> Python, regardless of what modules one uses: you can't assign system
>> priorities to different threads.  If you're planning to pipe MIDI to
>> another app for playback, maybe it won't be an issue for you.
>
> FWIW...  You could take your own advice, and devide your application
> in two: one process manages the GUI, and the second is a back-end
> process that plays the MIDI.  Your GUI can even launch the back end,
> which will inherit the priority of the GUI, after which the GUI can
> reduce its own priority (the priority of the back end will not be
> affected by the change)...
>
>
> -- 
> Derek D. Martin
> http://www.pizzashack.org/
> GPG Key ID: 0x81CFE75D

One also has access to nice-levels on unix systems.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Andrii V. Mishkovskyi
2008/10/29 Stef Mientki <[EMAIL PROTECTED]>:
> hello,
>
> Why gives "k = 09"  a syntax error ?

Because leading zero means that the number is octal, and there is no 9
among octal digits. :)

>
> thanks,
> Stef Mientki
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dot operator magic has me stymied...

2008-10-29 Thread Arnaud Delobelle
On Oct 29, 7:46 pm, "Casey Rodarmor" <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I'm trying to use a class as a decorator for another class method, but
> it's giving me a lot of grief. Basically, my problem is with the
> example below:
>
> >>> class decorator:
>
> ...     def __init__(self, function):
> ...         self.function = function
> ...
> ...     def __call__(self, *args, **kwargs):
> ...         self.function(*args, **kwargs)
> ...>>> class Foo:
>
> ...     def __init__(self):
> ...         self.msg = "Hello,"
> ...
> ...     @decorator
> ...     def greet(self, name):
> ...         print self.msg, name
> ...>>> foo = Foo()
> >>> foo.greet("Bob")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "decorate.py", line 6, in __call__
>     self.function(*args, **kwargs)
> TypeError: greet() takes exactly 2 arguments (1 given)
>
> I'm guessing that using a decorator that returns a class instance
> instead of a function instance has messed up the magic of the dot
> operator, causing it not to bind the foo instance to the self
> argument.
>
> Can anybody shed some light on what's happening here?

When

@decorator
def greet(self, name):
print self.msg, name

is executed, a new decorator object is created whose function
attribute is the function 'greet' above (with two arguments) and the
result is given the name 'greet'.

Later, when

>>> foo = Foo()
>>> foo.greet("Bob")

is executed,

foo.greet is a decorator object whose attribute 'function' is the
plain function 'greet'. So it expects two arguments and you only
provide one.

To fix this you could use the Descriptor protocol.  If you don't know
what it is, I suggest you read this:

http://users.rcn.com/python/download/Descriptor.htm

It should give you what you need to get it right.

HTH

--
Arnaud


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


Re: How to Implement an XMLRPC Server in Python?

2008-10-29 Thread Diez B. Roggisch

Guilherme Polo schrieb:

On 10/29/08, Zix <[EMAIL PROTECTED]> wrote:

Hello,
 I am a newbie to python and trying to get a hang of some of its
 advanced features through an application I am building. Basically, I'd
 like to build a weather forecasting web service. The clients should be
 able to query the service with a location and date and get back the
 weather forecast.

 After reading a lot on the topic I've settled on the following:
 * not using any python frameworks (Django, pylons etc)
 * exposing the service through an XMLRPC API using Python 2.4.3
 (that's the python version on CentOS 5.2)


Why did you decide to "expose" a web service through xmlrpc instead of
actually exposing it by using a restful web service ?

The links pointed by the previous email should help you, but well, I'm
still surprised on this decision specially because you said you read a
lot about this topic.


What is wrong with XMLRPC? I've implemented both kind of systems, and 
while REST has it's strengths in a HTML-centric environment, a real RCP 
mechanism with built-in type marshalling known to both sides of the 
communication is for pure interoperability better.


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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Diez B. Roggisch

Stef Mientki schrieb:

hello,

Why gives "k = 09"  a syntax error ?


because numbers starting with 0 are an octal value, allowing only the 
literals 0-7.


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


Re: 2.6, 3.0, and truly independent intepreters

2008-10-29 Thread Rhamphoryncus
On Oct 29, 7:20 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 28 Okt, 21:03, Rhamphoryncus <[EMAIL PROTECTED]> wrote:
>
> > * get a short-term bodge that works, like hacking the 3rd party
> > library to use your shared-memory allocator.  Should be far less work
> > than hacking all of CPython.
>
> Did anyone come up with a reason why shared memory couldn't be used
> for the purpose described by the inquirer? With the disadvantages of
> serialisation circumvented, that would leave issues of contention, and
> on such matters I have to say that I'm skeptical about solutions which
> try and make concurrent access to CPython objects totally transparent,
> mostly because it appears to be quite a lot of work to get right (as
> POSH illustrates, and as your own safethread work shows), and also
> because systems where contention is spread over a large "surface" (any
> object can potentially be accessed by any process at any time) are
> likely to incur a lot of trouble for the dubious benefit of being
> vague about which objects are actually being shared.

I believe large existing libraries were the reason.  Thus my
suggestion of the evil fork+mmap abuse.
--
http://mail.python.org/mailman/listinfo/python-list


Dot operator magic has me stymied...

2008-10-29 Thread Casey Rodarmor
Hi All,

I'm trying to use a class as a decorator for another class method, but
it's giving me a lot of grief. Basically, my problem is with the
example below:

>>> class decorator:
... def __init__(self, function):
... self.function = function
...
... def __call__(self, *args, **kwargs):
... self.function(*args, **kwargs)
...
>>> class Foo:
... def __init__(self):
... self.msg = "Hello,"
...
... @decorator
... def greet(self, name):
... print self.msg, name
...
>>> foo = Foo()
>>> foo.greet("Bob")
Traceback (most recent call last):
  File "", line 1, in 
  File "decorate.py", line 6, in __call__
self.function(*args, **kwargs)
TypeError: greet() takes exactly 2 arguments (1 given)


I'm guessing that using a decorator that returns a class instance
instead of a function instance has messed up the magic of the dot
operator, causing it not to bind the foo instance to the self
argument.

Can anybody shed some light on what's happening here?

Also, I really do like using classes as decorators. Are there any
workarounds to get it to work with methods?

Thanks a bunch!

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Mensanator
On Oct 29, 2:44 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> Guilherme Polo wrote:
> > On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
>
> >> hello,
>
> >>  Why gives "k = 09"  a syntax error ?
>
> > 09 is not a valid octal number. Instead use 011.
>
> > Ok, I guess you were not aware that prefixing a number with a '0'
> > would cause python to parse it as an octal and now you know.
>
> thanks guys,
> I didn't realize there were still people using octal notation ;-)

Windows users don't have much need for it, but it's still
popular with the 'Nix crowd.

>
> cheers,
> Stef

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


Re: Python/Numeric users be aware!

2008-10-29 Thread Benyang Tang
I also found that the a[5:] problem is Python version dependent.

On a 64-bit linux, of the following combinations I have tried, only
the first one has the problem. The other two are ok.
* Python 2.5.1 and Numeric 24.2
* Python 2.4.5 and Numeric 24.2
* Python 2.3.7 and Numeric 24.2

On Oct 29, 10:53 am, Benyang <[EMAIL PROTECTED]> wrote:
> Maybe it has been reported somewhere, but it is a big surprise to me.
>
> # Try the following:
> import Numeric
> a = Numeric.ones(10)
> a[5:] = -1
> print a
>
> It works correctly on 32-bit linux machines and on 32-bit Windows XP:
> [ 1  1  1  1  1 -1 -1 -1 -1 -1]
>
> It is totally screwed up on 64-bit linux machines:
> [1 1 1 1 1 1 1 1 1 1]
>
> # The following works correctly on both 32-bit and 64-bit machines
> (notice the comma):
> a[5:,] *= -1
>
> The Python version is 2.5.1, and Numeric is the latest version 24.2.

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


Filter function and lists

2008-10-29 Thread John Townsend
I'm trying to figure out how to use filter to walk through a list.

If I try a simple scripts like this:

def greaterthanten (number):
#pdb.set_trace()
if (number > 10):
ret_val = 1

else:
ret_val = 0

return ret_val

old_list = [1,2,20,30,5]

new_list = filter(greaterthanten, old_list)

#new_list becomes [20, 30]

The script works as I would expect. However, what if I need to pass more than 
one argument to the function? Can I do that with filter? Or does filter work 
only with function that take only a single arg?

Thanks


John Townsend (5-7204),
AGM-FL and PSL QE Lead



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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Stef Mientki

Guilherme Polo wrote:

On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
  

hello,

 Why gives "k = 09"  a syntax error ?




09 is not a valid octal number. Instead use 011.

Ok, I guess you were not aware that prefixing a number with a '0'
would cause python to parse it as an octal and now you know.
  

thanks guys,
I didn't realize there were still people using octal notation ;-)

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Regex Question

2008-10-29 Thread Arnaud Delobelle
On Oct 29, 7:01 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I need a regex expression which returns the start to the x=ANIMAL for
> > only the x=Dog fragments so all my entries should be start ...
> > (something here) ... x=Dog .  So I am really interested in fragments 1
> > and 3 only.
>
> > My idea (primitive) ^start.*?x=Dog doesn't work because clearly it
> > would return results
>
> > start
> > x=Dog  # (good)
>
> > and
>
> > start
> > x=Cat
> > stop
> > start
> > x=Dog # bad since I only want start ... x=Dog portion
>
> Looks like the following does the trick:
>
>  >>> s = """start      #frag 1 start
> ... x=Dog # frag 1 end
> ... stop
> ... start    # frag 2 start
> ... x=Cat # frag 2 end
> ... stop
> ... start     #frag 3 start
> ... x=Dog #frag 3 end
> ... stop"""
>  >>> import re
>  >>> r = re.compile(r'^start.*\nx=Dog.*\nstop.*', re.MULTILINE)
>  >>> for i, result in enumerate(r.findall(s)):
> ...     print i, repr(result)
> ...
> 0 'start      #frag 1 start\nx=Dog # frag 1 end\nstop'
> 1 'start     #frag 3 start\nx=Dog #frag 3 end\nstop'
>
> -tkc

This will only work if 'x=Dog' directly follows 'start' (which happens
in the given example).  If that's not necessarily the case, I would do
it in two steps (in fact I wouldn't use regexps probably but...):

>>> for chunk in re.split(r'\nstop', data):
... m = re.search('^start.*^x=Dog', chunk, re.DOTALL |
re.MULTILINE)
... if m: print repr(m.group())
...
'start  #frag 1 start \nx=Dog'
'start #frag 3 start \nx=Dog'

--
Arnaud

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


Re: Why gives "k = 09" a syntax error ?

2008-10-29 Thread Guilherme Polo
On 10/29/08, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
>  Why gives "k = 09"  a syntax error ?
>

09 is not a valid octal number. Instead use 011.

Ok, I guess you were not aware that prefixing a number with a '0'
would cause python to parse it as an octal and now you know.

>  thanks,
>  Stef Mientki
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>


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


Why gives "k = 09" a syntax error ?

2008-10-29 Thread Stef Mientki

hello,

Why gives "k = 09"  a syntax error ?

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use logging module to log an object like print()

2008-10-29 Thread Diez B. Roggisch

Steve Holden schrieb:

Diez B. Roggisch wrote:

davy zhang schrieb:

mport logging
import pickle


# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this

logger.debug("yes you can: %r", d)


One deficiency of this approach, however, is that the string formatting
is performed even when no logging is required, thereby wasting a certain
amount of effort on unnecessary formatting.


Nope, it's not. It only happens when the message is really logged.

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


Re: parsing MS word docs -- tutorial request

2008-10-29 Thread bp . tralfamadore

Thanks everyone -- very helpful!
I really appreciate your help -- that is what makes the world a
wonderful place.

peace.

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


Re: Default Argument Question

2008-10-29 Thread Benjamin Kaplan
On Wed, Oct 29, 2008 at 12:44 PM, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

> Chris Rebert a écrit :
> (snip)
>
>> Note that the "accumulation" behavior of lists is considered an
>> aberration
>>
>
> By who ?
>

All the python newbies who don't read the tutorial and get tripped up by
this.


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


Re: parsing MS word docs -- tutorial request

2008-10-29 Thread Terry Reedy

Kay Schluehr wrote:

On 28 Okt., 15:25, [EMAIL PROTECTED] wrote:

All,

I am trying to write a script that will parse and extract data from a
MS Word document.  Can / would anyone refer me to a tutorial on how to
do that?  (perhaps from tables).  I am aware of, and have downloaded
the pywin32 extensions, but am unsure of how to proceed -- I'm not
familiar with the COM API for word, so help for that would also be
welcome.

Any help would be appreciated.  Thanks for your attention and
patience.

::bp::


One can convert MS-Word documents into some class of XML documents
called MHTML. If I remember correctly those documents had an .mht
extension. The result is a huge amount of ( nevertheless structured )
markup gibberish together with text. If one spends time and attention
one can find pattern in the markup ( we have XML and it's human
readable ).


A related solution is to use OpenOffice to convert to 
OpenDocumentFormat, a zipped multiple XML format, and then use ODFPY to 
parse the XML and access the contents as linked objects.

http://opendocumentfellowship.com/development/projects/odfpy

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


math equation, svg and matplotlib

2008-10-29 Thread André
Would anyone have a "quick and dirty" code sample to create an svg
output of a sample math equation using matplotlib?

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


Re: Python Regex Question

2008-10-29 Thread Tim Chase

I need a regex expression which returns the start to the x=ANIMAL for
only the x=Dog fragments so all my entries should be start ...
(something here) ... x=Dog .  So I am really interested in fragments 1
and 3 only.

My idea (primitive) ^start.*?x=Dog doesn't work because clearly it
would return results

start
x=Dog  # (good)

and

start
x=Cat
stop
start
x=Dog # bad since I only want start ... x=Dog portion


Looks like the following does the trick:

>>> s = """start  #frag 1 start
... x=Dog # frag 1 end
... stop
... start# frag 2 start
... x=Cat # frag 2 end
... stop
... start #frag 3 start
... x=Dog #frag 3 end
... stop"""
>>> import re
>>> r = re.compile(r'^start.*\nx=Dog.*\nstop.*', re.MULTILINE)
>>> for i, result in enumerate(r.findall(s)):
... print i, repr(result)
...
0 'start  #frag 1 start\nx=Dog # frag 1 end\nstop'
1 'start #frag 3 start\nx=Dog #frag 3 end\nstop'

-tkc







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


Re: is there a way to access postgresql in python3.0rc1

2008-10-29 Thread Terry Reedy

davy zhang wrote:

I'm currently on a  project, it could last for at least 1 or 2 years.
so I choose python3 as server side programing language.
All I found on are python2.x ready libraries, Is there any library is
python3.0 ready? or just under alpha ,beta or something, I don't much
features, just basic functions are OK


Python3.0 final should be released in about a month.  Extension 
libraries will start appearing after that.  You will have to ask the 
maintainers of a particular library what their plans are for Python 3. 
Some will port very easily and could be available soon.  Others will 
take more work and may not appear so soon.


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


Re: how to get the thighest bit position in big integers?

2008-10-29 Thread Mensanator
On Oct 29, 1:26 am, Nick Mellor <[EMAIL PROTECTED]>
wrote:
> On Oct 6, 3:40 am, Gary Herron <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > Hi,
>
> > > I'm using python to develop some proof-of-concept code for a
> > > cryptographic application. My code makes extended use of python's
> > > native bignum capabilities.
>
> > > In many cryptographic applications there is the need for a function
> > > 'get_highest_bit_num' that returns the position number of the highest
> > > set bit of a given integer. For example:
>
> > >    get_highest_bit_num( (1 << 159))     == 159
> > >    get_highest_bit_num( (1 << 160) - 1) == 159
> > >    get_highest_bit_num( (1 << 160))     == 160
>
> > How about a binary search?
>
> > >>> from bisect import bisect
> > >>> BITS = [1< > >>> bisect(BITS, 1<<159)
> > 159
> > >>> bisect(BITS, 1<<160-1)
> > 159
> > >>> bisect(BITS, 1<<160)
> > 160
>
> > I have no clue if this is faster or not.  The comparison function used
> > in the search is (potentially) slow, but the search is O(log n) on the
> > number of bits rather than O(n), so its worth a test.
>
> > If you run timing test, let us know the results.
>
> > Gary Herron
>
> > > I implemented this the following way:
>
> > > def get_highest_bit_num(r):
> > >     i = -1
> > >     while r > 0:
> > >         r >>= 1
> > >         i = i + 1
> > >     return i
>
> > > This works, but it is a very unsatisfying solution, because it is so
> > > slow.
>
> > > My second try was using the math.log function:
>
> > > import math
> > > r = (1 << 160) - 1
> > > print highest_bit_num(r)              # prints out 159
> > > print math.floor(math.log(r, 2))      # prints out 160.0
>
> > > We see that math.log can only serve as a heuristic for the highest bit
> > > position. For small r, for example r = (1 << 16) - 1, the result from
> > > math.log(, 2) is correct, for big r it isn't any more.
>
> > > My question to the group: Does anyone know of a non-hackish way to
> > > determine the required bit position in python? I know that my two
> > > ideas
> > > can be combined to get something working. But is there a *better* way,
> > > that isn't that hackish?
>
> > > cheers,
> > > mmg
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> The following might be worth a try. It's faster the fewer set bits
> there are in the original number, and lightning fast if there are only
> one or two:
>
> def get_highest_bit_num(i):
>     while i>0: highestbit, i = i, i & (i-1)
>     return highestbit
>
> >>> highestbit(1<<31)
> 2147483648L
> >>> highestbit(1<<4)
> 16
> >>> highestbit(3<<4)
>
> 32
>
> Note that it returns the value of the highest bit, not its position.
>
> All it's doing is successively ANDing i with (i-1) until i is zero,
> then returning the previous value of i.
>
> It works because i & (i-1) has a useful property: it returns i less
> its least significant set bit:
>
> i=6 (binary 110) => i & (i-1)==4 (binary 100)
> i=3328 => (binary 1101__) then i & (i-1)==3072 (binary
> 1100__)
>
> (underscores for readability)
>
> As far as I know there isn't another piece of logic that helps you
> extract the most significant bit as simply :-)

import gmpy
print 'highest bit position: %d' % (len(gmpy.digits(3328,2))-1)

highest bit position: 11


or in 2.6

print 'highest bit position: %d' % (len(bin(3328)[2:])-1)

highest bit position: 11


>
> Best wishes,
>
> Nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is ctypes appropriate in my case?

2008-10-29 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

Hi,

I've a dll and its header file that controls an hardware. I want to 
write a wrapper for this dll in Python.

What is the best way that I can write a wrapper?


What do you want to do with the wrapper?

I know ctypes modules and have used it before. As far as I know ctypes 
is only used to call the dll functions in a python module.


I am not sure what you mean here.  Python code can directly import and 
call functions in dlls that represent Python extension modules and that 
are placed in the Pythonxx/dlls directory in your Windows Python 
installation.  Ctypes is mostly used to call functions in a dll that is 
*not* a python extension module, that was not written for Python.


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


Re: How to get an object's name as a string?

2008-10-29 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

>> That explanation makes no sense. Given the assignment:
>> 
>> x = 57
>> 
>> if the name of x isn't 'x', then what on earth can it possibly mean to 
>> ask for the name of a variable?
>> 
> He didn't ask for the name of a variable, he asked for the name of an
> object. You may choose to equate them, but they aren't the same thing.

When I do that assignment there seem to be 5 references to that object, two 
of them are dictionary keys (what's the name of a dictionary key?), and two
are dictionary values. the last one is of course x. Any of these seem a 
reasonable answer to the question, but how the code is supposed to tell
which name is the one the user wanted is another matter.

>>> import varname
>>> x = 57
>>> for s in varname.object_info(x):
... print s
...
opcode.opmap['INPLACE_MULTIPLY']
encodings.cp850.encoding_map[57]
encodings.cp850.decoding_map[57]
dis.opmap['INPLACE_MULTIPLY']
__main__.x
>>>

When I repeat the experiment in Idle the cp850 encoding entries disappear so 
I only get a choice of 3 'names'.

> l = []
> l.append(l)
> del l
> 
> What's the name of the list formerly known as "l"?

My code thinks its name is <...>, but then that's just my code:

>>> l = []
>>> l.append(l)
>>> for s in varname.object_info(l):
print s


__main__.l
<...>
>>> 

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


Re: Python/Numeric users be aware!

2008-10-29 Thread Kirk Strauser
At 2008-10-29T17:53:43Z, Benyang <[EMAIL PROTECTED]> writes:

> It is totally screwed up on 64-bit linux machines:
> [1 1 1 1 1 1 1 1 1 1]

And on 64-bit FreeBSD machines.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to Implement an XMLRPC Server in Python?

2008-10-29 Thread Guilherme Polo
On 10/29/08, Zix <[EMAIL PROTECTED]> wrote:
> Hello,
>  I am a newbie to python and trying to get a hang of some of its
>  advanced features through an application I am building. Basically, I'd
>  like to build a weather forecasting web service. The clients should be
>  able to query the service with a location and date and get back the
>  weather forecast.
>
>  After reading a lot on the topic I've settled on the following:
>  * not using any python frameworks (Django, pylons etc)
>  * exposing the service through an XMLRPC API using Python 2.4.3
>  (that's the python version on CentOS 5.2)

Why did you decide to "expose" a web service through xmlrpc instead of
actually exposing it by using a restful web service ?

The links pointed by the previous email should help you, but well, I'm
still surprised on this decision specially because you said you read a
lot about this topic.

>  * using mod_wsgi ( http://code.google.com/p/modwsgi/ ) instead of
>  mod_python
>
>  So far, I've just created the database design and been focusing on
>  that. But now I realize I've been procrastinating because I am not
>  sure how to really go about implementing this (the docs on xml rpc
>  python module are especially sparse). Please advice.
>
>


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


Re: free IDE with removing import and refactoring

2008-10-29 Thread Stef Mientki

pihentagy wrote:

Hi!

I am looking for a python IDE which can remove my unused imports,

is that possible in a language like Python ?
I can imagine the opposite, importing those things that are necessary.

 and
can do basic refactoring under windows.
  

What kind of refactoring do you think of ?

cheers,
Stef

Can somebody advice me such an IDE?

I have played with eclipse and netbeans, but I cannot find such a
functionality (but maybe I looked it over).

Besides, an installation howto would be useful for me.

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


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


Python Regex Question

2008-10-29 Thread MalteseUnderdog

Hi there I just started python (but this question isn't that trivial
since I couldn't find it in google :) )

I have the following text file entries (simplified)

start  #frag 1 start
x=Dog # frag 1 end
stop
start# frag 2 start
x=Cat # frag 2 end
stop
start #frag 3 start
x=Dog #frag 3 end
stop


I need a regex expression which returns the start to the x=ANIMAL for
only the x=Dog fragments so all my entries should be start ...
(something here) ... x=Dog .  So I am really interested in fragments 1
and 3 only.

My idea (primitive) ^start.*?x=Dog doesn't work because clearly it
would return results

start
x=Dog  # (good)

and

start
x=Cat
stop
start
x=Dog # bad since I only want start ... x=Dog portion

Can you help me ?

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


Re: How to Implement an XMLRPC Server in Python?

2008-10-29 Thread Daniel Fetchinson
On 10/29/08, Zix <[EMAIL PROTECTED]> wrote:
> Hello,
> I am a newbie to python and trying to get a hang of some of its
> advanced features through an application I am building. Basically, I'd
> like to build a weather forecasting web service. The clients should be
> able to query the service with a location and date and get back the
> weather forecast.
>
> After reading a lot on the topic I've settled on the following:
> * not using any python frameworks (Django, pylons etc)
> * exposing the service through an XMLRPC API using Python 2.4.3
> (that's the python version on CentOS 5.2)
> * using mod_wsgi ( http://code.google.com/p/modwsgi/ ) instead of
> mod_python
>
> So far, I've just created the database design and been focusing on
> that. But now I realize I've been procrastinating because I am not
> sure how to really go about implementing this (the docs on xml rpc
> python module are especially sparse). Please advice.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

These pages might be useful, they include example code:

http://docs.python.org/library/simplexmlrpcserver.html
http://code.activestate.com/recipes/81549/
http://code.activestate.com/recipes/496786/
http://www.google.com/search?q=python+xmlrpc+server+example

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Numeric users be aware!

2008-10-29 Thread Jerry Hill
On Wed, Oct 29, 2008 at 1:53 PM, Benyang <[EMAIL PROTECTED]> wrote:
> The Python version is 2.5.1, and Numeric is the latest version 24.2.

While 24.2 is the latest version of Numeric, it's also three years old
and no longer supported.  From http://numpy.scipy.org/ - "Numeric was
the first arrayobject built for Python.  It has been quite successful
and is used in a wide variety of settings and applications.
Maintenance has ceased for Numeric, and users should transisition to
NumPy as quickly as possible."

So, you are unlikely to find anyone to do bug fixes on Numeric.

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


Re: Python/Numeric users be aware!

2008-10-29 Thread Carl

Confirmed

Benyang wrote:

Maybe it has been reported somewhere, but it is a big surprise to me.

# Try the following:
import Numeric
a = Numeric.ones(10)
a[5:] = -1
print a

It works correctly on 32-bit linux machines and on 32-bit Windows XP:
[ 1  1  1  1  1 -1 -1 -1 -1 -1]

It is totally screwed up on 64-bit linux machines:
[1 1 1 1 1 1 1 1 1 1]

# The following works correctly on both 32-bit and 64-bit machines
(notice the comma):
a[5:,] *= -1

The Python version is 2.5.1, and Numeric is the latest version 24.2.

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


Re: Amharic Question Answering

2008-10-29 Thread Terry Reedy

seid muhie wrote:



Dear All
I am new to Python. Am new to NLP(NAtural LAnguage Processing) too.
But take the initiation to develop Autamatic Amharic Question Answering 
as part of my MSc. degree partial fuflfilment thesis work.


Please excuse my ignorance, but is an Amharic QA system different from 
an English QA system, other that the characters and language?



Now I need,
1. If python could help me in doing the QA system
2. if any QA system been developed in Python.
am going through the NLTK book with its nice examples. That is why I 
seemed to prefer python as a development tool for my QA.


The only part I can answer is that Python2 supports Unicode, which I 
believe contains Amharic characters, which the upcoming Python3 uses 
Unicode as the text class.


tjr

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


Python/Numeric users be aware!

2008-10-29 Thread Benyang
Maybe it has been reported somewhere, but it is a big surprise to me.

# Try the following:
import Numeric
a = Numeric.ones(10)
a[5:] = -1
print a

It works correctly on 32-bit linux machines and on 32-bit Windows XP:
[ 1  1  1  1  1 -1 -1 -1 -1 -1]

It is totally screwed up on 64-bit linux machines:
[1 1 1 1 1 1 1 1 1 1]

# The following works correctly on both 32-bit and 64-bit machines
(notice the comma):
a[5:,] *= -1

The Python version is 2.5.1, and Numeric is the latest version 24.2.
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing MS word docs -- tutorial request

2008-10-29 Thread Kay Schluehr
On 28 Okt., 15:25, [EMAIL PROTECTED] wrote:
> All,
>
> I am trying to write a script that will parse and extract data from a
> MS Word document.  Can / would anyone refer me to a tutorial on how to
> do that?  (perhaps from tables).  I am aware of, and have downloaded
> the pywin32 extensions, but am unsure of how to proceed -- I'm not
> familiar with the COM API for word, so help for that would also be
> welcome.
>
> Any help would be appreciated.  Thanks for your attention and
> patience.
>
> ::bp::

One can convert MS-Word documents into some class of XML documents
called MHTML. If I remember correctly those documents had an .mht
extension. The result is a huge amount of ( nevertheless structured )
markup gibberish together with text. If one spends time and attention
one can find pattern in the markup ( we have XML and it's human
readable ).

A few years ago I used this conversion to implement roughly following
thing algorithm:

1. I manually highlighted one or more sections in a Word doc using a
background colour marker.
2. I searched for the colour marked section and determined the
structure. The structure information was fed into a state machine.
3. With this state machine I searched for all sections that were
equally structured.
4. I applied a href link to the text that was surrounded by the
structure and removed the colour marker.
5. In another document I searched for the same text and set an anchor.

This way I could link two documents ( those were public specifications
being originally disconnected ).

Kay

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


Re: error estimation in a non-linear least squares fitting

2008-10-29 Thread Evelien
Ok, then I have to look into scipy.odr to see how it can help me move
forward. Thanks Robert!
Evelien
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Novice]Installing eric4 with python 2.6

2008-10-29 Thread Saurabh Agrawal
>
>
> PyQt supported Python 2.6 on the day it was released.
>
> A snapshot of the PyQt Windows installer for Python 2.6 can be downloaded
> from the same page as you downloaded the installer for Python 2.5.
>
> Phil
> --
>  
>


Thanks Phil, it worked. My bad, sorry.
--
http://mail.python.org/mailman/listinfo/python-list


How to Implement an XMLRPC Server in Python?

2008-10-29 Thread Zix
Hello,
I am a newbie to python and trying to get a hang of some of its
advanced features through an application I am building. Basically, I'd
like to build a weather forecasting web service. The clients should be
able to query the service with a location and date and get back the
weather forecast.

After reading a lot on the topic I've settled on the following:
* not using any python frameworks (Django, pylons etc)
* exposing the service through an XMLRPC API using Python 2.4.3
(that's the python version on CentOS 5.2)
* using mod_wsgi ( http://code.google.com/p/modwsgi/ ) instead of
mod_python

So far, I've just created the database design and been focusing on
that. But now I realize I've been procrastinating because I am not
sure how to really go about implementing this (the docs on xml rpc
python module are especially sparse). Please advice.


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


RE: parsing MS word docs -- tutorial request

2008-10-29 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Tuesday, October 28, 2008 10:26 AM
> To: python-list@python.org
> Subject: parsing MS word docs -- tutorial request
> 
> All,
> 
> I am trying to write a script that will parse and extract data from a
> MS Word document.  Can / would anyone refer me to a tutorial on how to
> do that?  (perhaps from tables).  I am aware of, and have downloaded
> the pywin32 extensions, but am unsure of how to proceed -- I'm not
> familiar with the COM API for word, so help for that would also be
> welcome.
> 
> Any help would be appreciated.  Thanks for your attention and
> patience.
> 
> ::bp::
> --
> http://mail.python.org/mailman/listinfo/python-list


Word Object Model:
http://msdn.microsoft.com/en-us/library/bb244515.aspx

Google for sample code to get you started.


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


beutifulsoup

2008-10-29 Thread luca72
Hello
I try to use beautifulsoup
i have this:
sito = urllib.urlopen('http://www.prova.com/')
esamino = BeautifulSoup(sito)
luca = esamino.findAll('tr', align='center')

print luca[0]

>>>href="#">#144.4MB>align="left"> Pc-prova.rar 

I need to get the following information:
1)Only|G|BoT|05
2)#1
3)44.4MB
4)Pc-prova.rar
with: print luca[0].a.stringi get #1
with print luca[0].td.stringi get 44.4MB
can you explain me how to get the others two value
Thanks
Luca
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default Argument Question

2008-10-29 Thread Bruno Desthuilliers

Chris Rebert a écrit :
(snip)

Note that the "accumulation" behavior of lists is considered an
aberration 


By who ?

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


Re: Default Argument Question

2008-10-29 Thread Bruno Desthuilliers

Paulo J. Matos a écrit :

Hi all,

Going through the tutorial brought up a question. Consider the functions:

def f(a, L=[]):
L.append(a)
return L

print f(3)
print f(9)
print f(7)

def f1(i = 0):
i = i + 1
print i

f1()
f1()
f1()
f1()

Since the f accumulates the values in L, I was expecting to see i
printing 1,2,3,4 but this doesn't happen.
Can someone please explain why and what is going on beneath the veil?


In the first case, you are mutating L. In the second, you are rebinding 
the local name i. IOW, you are comparing oranges and apples. The 
corresponding code using a list would be:


>>> def f2(arg, alist=[]):
... alist = alist + [arg]
... print alist
...

And it behaves just like your f1 function:

>>> f2(1)
[1]
>>> f2(1)
[1]
>>> f2(1)
[1]
>>> f2(1)
[1]
>>>


But anyway: you just couldn't mutate i in f1, since integers are 
immutables...


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


Re: Default Argument Question

2008-10-29 Thread Chris Rebert
On Wed, Oct 29, 2008 at 9:14 AM, Paulo J. Matos <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> Going through the tutorial brought up a question. Consider the functions:
>
> def f(a, L=[]):
>L.append(a)
>return L
>
> print f(3)
> print f(9)
> print f(7)
>
> def f1(i = 0):
>i = i + 1
>print i
>
> f1()
> f1()
> f1()
> f1()
>
> Since the f accumulates the values in L, I was expecting to see i
> printing 1,2,3,4 but this doesn't happen.
> Can someone please explain why and what is going on beneath the veil?

http://effbot.org/zone/default-values.htm explains this FAQ quite
well. Note that the "accumulation" behavior of lists is considered an
aberration and is usually not desired.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Cheers,
>
> --
> Paulo Jorge Matos - pocmatos @ gmail.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Default Argument Question

2008-10-29 Thread Paulo J. Matos
Hi all,

Going through the tutorial brought up a question. Consider the functions:

def f(a, L=[]):
L.append(a)
return L

print f(3)
print f(9)
print f(7)

def f1(i = 0):
i = i + 1
print i

f1()
f1()
f1()
f1()

Since the f accumulates the values in L, I was expecting to see i
printing 1,2,3,4 but this doesn't happen.
Can someone please explain why and what is going on beneath the veil?

Cheers,

-- 
Paulo Jorge Matos - pocmatos @ gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use logging module to log an object like print()

2008-10-29 Thread bieffe62
On 29 Ott, 12:24, Steve Holden <[EMAIL PROTECTED]> wrote:
> Diez B. Roggisch wrote:
> > davy zhang schrieb:
> >> mport logging
> >> import pickle
>
> >> # create logger
> >> logger = logging.getLogger("simple_example")
> >> logger.setLevel(logging.DEBUG)
> >> # create console handler and set level to debug
> >> ch = logging.StreamHandler()
> >> ch.setLevel(logging.DEBUG)
> >> # create formatter
> >> formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
> >> - %(message)s ")
> >> # add formatter to ch
> >> ch.setFormatter(formatter)
> >> # add ch to logger
> >> logger.addHandler(ch)
>
> >> d = {'key':'msg','key2':'msg2'}
>
> >> # "application" code
> >> logger.debug("debug message",d)#can not do this
>
> > logger.debug("yes you can: %r", d)
>
> One deficiency of this approach, however, is that the string formatting
> is performed even when no logging is required, thereby wasting a certain
> amount of effort on unnecessary formatting.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/- Nascondi testo citato
>

Sure about that?

This is the implementation of Logger.debug in
the file : ..Python25\lib\logging\__init__.py

   def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.

To pass exception information, use the keyword argument
exc_info with
a true value, e.g.

logger.debug("Houston, we have a %s", "thorny problem",
exc_info=1)
"""
if self.manager.disable >= DEBUG:
return
if DEBUG >= self.getEffectiveLevel():
apply(self._log, (DEBUG, msg, args), kwargs)


The other methods (info, warning, ...) are similar. It looks like
the formatting is only done if actually used.

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


Re: Improving interpreter startup speed

2008-10-29 Thread Michael
Tried using the precache daemon to see if it gives any boost?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-29 Thread Dale Roberts
On Oct 28, 11:59 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> ...
>
> There are only the two cases, which Greg quite succinctly and  
> accurately described above.  One is by value, the other is by  
> reference.  Python quite clearly uses by value.  Parameters are  
> expressions that are evaluated, and the resulting value copied into  
> the formal parameter, pure and simple.  The continued attempts to  
> obfuscate this is pointless and wrong.
>
> Best,
> - Joe

Joe, you are being too generous and expansive here.

[Play along with me for a minute here...]

Don't you know? There is really only *ONE* case, and, you are right,
it is Pass By Value. There is no such thing as Pass By Reference at
the physical CPU level at all, right? If there is, show it to me. Pass
By Reference is just a silly idiom developed by high-minded CS
academics to confuse the rest of us. It has no practical use and
should not be given its own name, when we already have a good an
proper name for it.

Let me demonstrate with 3 examples of a function definition, and the
appropriate calling syntax for that function in C++, all sharing the
common "int i" global variable:

int i = 5;

myfunc(int &val){}   /*CALL:*/ myfunc(i);// "ByRef" (ya, right!)
myfunc(int val){}/*CALL:*/ myfunc(i);// ByVal
myfunc(int *val){}   /*CALL:*/ myfunc(&i);   // Joe's ByVal

The first is what all the fakers call "Pass By Reference" - sheesh,
how naive. We all know that what *really* happens internally is that
the *address* of val (A VALUE itself, or course) is copied and passed
on the stack, right? There couldn't be a more straightforward example
of Pass By Value (unless it's an inline function, or optimized away,
or possibly when implemented in a VM, or...). It passes the *address*
of i by value, then we can access the *value* of i too via
indirection. Hmm, did we need to have two definitions of VALUE there?
Well, never mind, no one will notice...

The next is obviously pass by value. It's right out there. The value
of i (which is what we are talking about, right?) is copied out, and
passed right on the stack in plain daylight where we can all see it.

How about the third? Pass By Value, obviously, of course. This is the
version you are defending, right? The parameter's value, &i, is
evaluated and copied right onto the stack, just like in the first
example. In fact, if you compare the assembler output of the first and
third examples, you may not even see a difference. Never mind the
actual contents of that pesky "i" variable that most people are
referring to when they use the term "value". We don't need to dress up
example 3 and call it an "idiom" where we are really passing a so-
called "reference" of the variable "i". Indeed! Don't insult our
intelligence. We can all see that it's an address passed by value,
plain and simple.


Pass By Reference? So "postmodern". Who needs it. Show me a so-called
"reference". I've looked at the assembler output and have never seen
one. There is no such thing.

"The continued attempts to obfuscate this is pointless and wrong."


---
I hate to have to add this, but for those not paying close attention:

  ;-)

dale

(tongue back out of cheek now)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory usage

2008-10-29 Thread bieffe62
On 21 Ott, 17:19, Rolf Wester <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have the problem that with long running Python scripts (many loops)
> memory consumption increases until the script crashes. I used the
> following small script to understand what might happen:
>
> import gc
>
> print len(gc.get_objects())
>
> a = []
> for i in range( 400 ):
>     a.append( None )
> for i in range( 400 ):
>     a[i] = {}
>
> print len(gc.get_objects())
>
> ret = raw_input("Return:")
>
> del a
> gc.collect()
>
> print len(gc.get_objects())
>
> ret = raw_input("Return:")
>
> The output is:
> 4002706
> Return:
> 2705
> Return:
>
> When I do ps aux | grep python before the first "Return" I get:
> wester    5255 51.2 16.3 1306696 1286828 pts/4 S+   17:59   0:30 python
> memory_prob2.py
>
> and before the second one:
> wester    5255 34.6 15.9 1271784 1255580 pts/4 S+   17:59   0:31 python
> memory_prob2.py
>
> This indicates that although the garbage collector freed 401 objects
> memory consumption does not change accordingly.
>
> I tried the C++ code:
>
> #include 
> using namespace std;
>
> int main()
> {
>         int i;
>         cout << ":";
> //ps 1
>         cin >> i;
>
>         double * v = new double[4000];
>         cout << ":";
> //ps 2
>         cin >> i;
>
>         for(int i=0; i < 4000; i++)
>                 v[i] = i;
>
>         cout << v[4000-1] << ":";
> //ps 3
>         cin >> i;
>
>         delete [] v;
>
>         cout << ":";
> //ps 4
>         cin >> i;
>
> }
>
> and got from ps:
>
> ps 1: 11184
> ps 1: 323688
> ps 1: 323688
> ps 1: 11184
>
> which means that the memery which is deallocated is no longer used by
> the C++ program.
>
> Do I miss something or is this a problem with Python? Is there any means
> to force Python to release the memory that is not used any more?
>
> I would be very appreciative for any help.
>
> With kind regards
>
> Rolf



To be sure that the deallocated memory is not cached at some level to
be reused, you could try
someting like this:

while 1:
l = [dict() for i in range(400)]
l = None # no need of gc and del

For what is worth, on my PC ( Windows XP and Python 2.5.2) the memory
usage of the process
monitored with the Task manager grows up to 600 MB before the memory
is actually released.

Note that in your example, as in mine, you do not need to call
gc.collect(), because
the huge list object is already deleted when you do "del a" ( or in my
case when I reassign "l" and the
huge list drops to 0 reference counts ). The basic memory garbage
collector in CPython
is based on reference counts; gc is only used to find and break
circular reference chains,
which your example do not create. As a proof of that, if ypu print the
retuirn value of
gc.collect (whic is the number of collected objects) you should get 0.

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


Re: Fastest way to convert sql result into a dict or list ?

2008-10-29 Thread alex23
On Oct 29, 9:35 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I'm trying to find the fastest way to convert an sql result into a
> dict or list.

>>> from collections import defaultdict
>>> results = defaultdict(defaultdict)
>>> for contact_id, field_id, field_name, value in sql_result:
... results[contact_id][field_id] = value
... results[contact_id][field_name] = value
...

This lets you reference things in a straightforward way:

>>> results[1]['email']
'[EMAIL PROTECTED]'

If you'd prefer to use only the ids for reference:

>>> results = defaultdict(defaultdict)
>>> for contact_id, field_id, field_name, value in sql_result:
... results[contact_id][field_id] = (field_name, value)
...
>>> results[1][1]
('address', 'something street')

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


Re: Python memory usage

2008-10-29 Thread David Cournapeau
On Wed, Oct 29, 2008 at 6:56 PM, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> On Oct 21, 5:19 pm, Rolf Wester <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I have the problem that with long running Python scripts (many loops)
>> memory consumption increases until the script crashes. I used the
>> following small script to understand what might happen:
>>
> 
>
> AFAIK, python uses malloc behind the scenes to allocate memory. From
> the malloc man page...
>
> "The  malloc() and free() functions provide a simple, general-purpose
> memory allocation package. The malloc() function returns a pointer to
> a block of at least size bytes suitably aligned for any use. If the
> space assigned by malloc() is overrun, the results are undefined.
>
> The argument to free() is a pointer to a block previously allocated by
> malloc(), calloc(), or realloc(). After free() is executed, this space
> is made available for further  allocation by the application, though
> not returned to the system. Memory is returned to the system only
> upon  termination of  the  application.  If ptr is a null pointer, no
> action occurs. If a random number is passed to free(), the results are
> undefined."

Depending on your malloc implementation, that may not be true. IN
particular, with glibc, bit allocations are done with mmap, and those
areas are unmaped when free is called; any such area is immediatly
returned to the system

http://www.gnu.org/software/libtool/manual/libc/Malloc-Tunable-Parameters.html#Malloc-Tunable-Parameters

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


Re: Fastest way to convert sql result into a dict or list ?

2008-10-29 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I'm trying to find the fastest way to convert an sql result into a
> dict or list.
> What i mean, for example:
> my sql result:
> contact_id, field_id, field_name, value
> sql_result=[[1, 1, 'address', 'something street'],
>  [1, 2, 'telnumber', '11'],
>  [1, 3, 'email', '[EMAIL PROTECTED]'],
>  [2, 1, 'address','something stree'],
>  [2, 3, 'email','[EMAIL PROTECTED]']]
> the dict can be:
> dict={1:['something street', '11' ,
> '[EMAIL PROTECTED]'],
> 2:['something street', '', '[EMAIL PROTECTED]' ]}
> or a list can be:
> list=[[1,'something street', '11' ,
> '[EMAIL PROTECTED]'],
>[2,'something street', '', '[EMAIL PROTECTED]' ]]
> 
> I tried to make a dict, but i think it is slower then make a list, and
> i tried the "one lined for" to make a list, it's look like little bit
> faster than make a dict.
> 
> def empty_list_make(sql_result):
> return [ [line[0],"", "", ""]   for line in sql_result]
> 
> than fill in the list with another for loop.
> I hope there is an easyest way to do something like this ??
> any idea ?

I think it won't get much easier than this:

dod = {}
to_index = [None] + range(3)
for contact_id, field_id, field_name, value in data:
if contact_id not in dod:
dod[contact_id] = [""]*len(to_index)
dod[contact_id][to_index[field_id]] = value

A database expert might do it in SQL, but my try got a bit messy:

import sqlite3 as sqlite

conn = sqlite.connect(":memory:")
cs = conn.cursor()
cs.execute("create table tmp (contact_id, field_id, field_name, value);")

data = [[1, 1, 'address', 'one-address'],
 [1, 2, 'telnumber', 'one-telephone'],
 [1, 3, 'email', '[EMAIL PROTECTED]'],
 [2, 1, 'address','two-address'],
 [2, 3, 'email','[EMAIL PROTECTED]']]

cs.executemany("insert into tmp values (?, ?, ?, ?)", data)

def make_query(field_defs, table="tmp"):
field_defs = [("alias%s" % index, id, name)
  for index, (id, name) in enumerate(field_defs)]
fields = ", ".join("%s.value as %s" % (alias, name)
   for alias, id, name in field_defs)

format = ("left outer join %(table)s as %(alias)s "
  "on main.contact_id = %(alias)s.contact_id "
  "and %(alias)s.field_id=%(field_id)s ")
joins = "\n".join(format
  % dict(table=table, alias=alias, field_id=id)
  for alias, id, name in field_defs)

return ("select distinct main.contact_id, %(fields)s "
"from %(table)s as main\n %(joins)s" % dict(
table=table, fields=fields, joins=joins))

field_defs = list(
cs.execute("select distinct field_id, field_name from tmp"))

# XXX sanitize field ids and names

sql = make_query(field_defs)
for row in cs.execute(sql):
print row

Note that you get None for empty fields, not "".

Peter

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


Re: How to get an object's name as a string?

2008-10-29 Thread ShanMayne
Indeed they do. My delighted thanks. You have most precisely addressed
the problem I intended to convey.

I should have given the case of module attributes a moments further
thought, an obvious answer. The locals() was unknown to me (rookie
gaps).

Thank you for the elaborated illustration.

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


Re: parsing MS word docs -- tutorial request

2008-10-29 Thread Mike Driscoll
On Oct 29, 4:32 am, Okko Willeboordsed <[EMAIL PROTECTED]>
wrote:
> Get a copy of;  Python Programming on Win32, ISBN 1-56592-621-8
> Use Google and VBA for help
>
> [EMAIL PROTECTED] wrote:
> > All,
>
> > I am trying to write a script that will parse and extract data from a
> > MS Word document.  Can / would anyone refer me to a tutorial on how to
> > do that?  (perhaps from tables).  I am aware of, and have downloaded
> > the pywin32 extensions, but am unsure of how to proceed -- I'm not
> > familiar with the COM API for word, so help for that would also be
> > welcome.
>
> > Any help would be appreciated.  Thanks for your attention and
> > patience.
>
> > ::bp::

Also check out MSDN as the win32 module is a thin wrapper so most of
the syntax on MSDN or in VB examples can be directly translated to
Python. There's also a PyWin32 mailing list which is quite helpful:

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

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


Re: Tkinter: How to get Label wraplength functionality in Text Box

2008-10-29 Thread Guilherme Polo
On 10/29/08, Mudcat <[EMAIL PROTECTED]> wrote:
> Sounds like that would work really well. Problem is I can't get it to
>  work.
>
>  ...
>  AttributeError: Text instance has no attribute 'count'
>  ...
>

Yep, it is not there yet.

>  I think my usage is correct. I don't have any params at the moment,
>  but I was just checking the functionality.
>
>  numlines = widget.count()
>
>  According to the Tk 8.5 documentation it's used just like a normal
>  command.
>  WIDGET COMMAND
> pathName count ?options? index1 index2
> -chars
> -displaychars
> -displayindices
> -displaylines
> -indices
> -lines
> -xpixels
> -ypixels
>
>
>  As for the environment, I thought I had everything set up correctly.
>  I've got the latest stable version of Python 2.6 (r26:66721, Oct  2
>  2008, 11:35:03). I'm implementing the TTK wrappers to access Tk 8.5.

Implementing a ttk wrapper won't give you this "count" command, since
this is a command for an already existing widget (the text widget), it
is not part of the ttk widgets. Also, there is already a ttk wrapper
at http://pypi.python.org/pypi/pyttk which is being proposed to be
included in python's stdlib.

>  Although when I check the wrapper I don't see any mods to the Text
>  Box. I also don't see this option in the Tkinter.py file.
>
>  Is there something else I need to add to access this new feature?
>

You would need to wrap it and add it as a method to the Text class in
Tkinter. Fortunately it is easily done:

import Tkinter

def text_count(self, index1, index2, *options):
args = ["-%s" % opt for opt in options]
args.extend([index1, index2])
return self.tk.call(self._w, "count", *args)

Tkinter.Text.count = text_count


Then to try it:


root = Tkinter.Tk()
text = Tkinter.Text()
text.pack()

text.insert("1.0", "a\nb\c\nd")
print text.count("1.0", "end", "displaylines", "lines")

root.mainloop()


Note that I inverted the order of the arguments here, indices and then
the options or no options. If it doesn't work saying "count" is not an
acceptable command then your tkinter is not compiled against tcl/tk
8.5 or later.

>
>
>  On Oct 28, 6:51 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>
>  >
>  > Are you looking for something like the new "count" command for the
>  > text widget in tk 8.5 ? "count" can count the number of logical lines
>  > (irrespective of wrapping), display lines (counts one for each time a
>  > line wraps) and some other things.
>  >
>
> > >  Thanks
>  >
>  > > --
>  > >  http://mail.python.org/mailman/listinfo/python-list
>  >
>
> > --
>  > -- Guilherme H. Polo Goncalves
>
>
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>


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


Re: How to get an object's name as a string?

2008-10-29 Thread alex23
On Oct 29, 11:31 pm, ShanMayne <[EMAIL PROTECTED]> wrote:
> However this does not help me to use the reference/name of an object I
> imported instead of created.

I've never really understood these requests (and they come up a lot).
Unless you're doing a '*' import, you'll already know the bound names
of the objects you're importing. If you -are- doing a '*' import and
you -don't- know what objects are being imported, how will you refer
to the object to find out its name?

However, maybe one of the following examples will be of use.

Assume a module 'items' that contains:

a = 1
b = 'string'

The best way would be to use the module as it is intended, as a
namespace:

>>> import items
>>> names = [x for x in dir(items) if not '__' in x] # ignore
special objects
>>> names
['a', 'b']
>>> one = getattr(items, names[0])
>>> two = getattr(items, names[1])
>>> one
1
>>> two
'string'

Another way is to look through the variables in the current scope:

>>> before = set(locals())
>>> before.add('before') # you want to ignore this object too
>>> from items import *
>>> names = list(set(locals()).difference(before))
>>> names
['a', 'b']
>>> one = locals()[names[0]]
>>> two = locals()[names[1]]
>>> one
1
>>> two
'string'

Do either of these help with your problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Improving interpreter startup speed

2008-10-29 Thread Paul Boddie
On 29 Okt, 13:55, [EMAIL PROTECTED] wrote:
> Terry Reedy:
>
> > The current developers, most of whom use Python daily, [...]
>
> Thank you for bringing some light in this thread so filled with worse
> than useless comments.

Indeed. Observing that CGI is old-fashioned, aside from not really
helping people who choose or are obliged to use that technology,
doesn't detract from arguments noting various other areas where start-
up performance is worth improving (in build environments, for example,
as someone suggested), nor does it address the more basic issue of why
Python issues as many system calls as it does when starting up,
something which has actually been looked at by the core developers
(indicating that it isn't a waste of time as one individual claimed)
as well as by developers in other projects where application start-up
time has been criticised.

Although people are using multi-GHz CPUs on the desktop, there are
environments where it is undesirable for Python to go sniffing around
the filesystem just for the fun of it. In fact, various embedded
projects have employed some kind of daemon for Python in order to get
Python-based programs started quickly enough - something that I'm sure
plenty of people would ridicule if, say, Java were involved. The
better solution would just involve improving the obvious: the start-up
performance.

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


  1   2   >