Re: wikipedia with python

2009-06-24 Thread ZeLegolas

On Mon, 22 Jun 2009 19:23:59 +0200, Andre Engels 
wrote:
> On Mon, Jun 22, 2009 at 6:58 PM, zelegolas wrote:
>> Let me know if it's the right place to ask.
>>
>> I'm looking for wiki writen with python where I can import all
>> wikipedia site.
>> If you have any links please let me know.
> 
> I don't think that's possible. If you wnat to import Wikipedia in a
> wiki, it will probably have to be MediaWiki - and that's written in
> PHP.
> 
> What do you want to use the material for?

Well sorry I was not clear. I have a wiki running with mediawiki and I want
to import in a wiki written with python. 

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


Re: Reading a large csv file

2009-06-24 Thread Chris Withers

Terry Reedy wrote:

Mag Gam wrote:

Yes, the system has 64Gig of physical memory.


drool ;-).


Well, except that, dependent on what OS he's using, the size of one 
process may well still be limited to 2GB...


Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.NONE

2009-06-24 Thread John Machin
On Jun 23, 8:35 am, 1x7y2z9 <1x7y...@gmail.com> wrote:
> I am currently using python v2.5.2.
>
> Not sure if this is defined in a later version, but it would be nice
> to define re.NONE = 0 in the re module.  This would be useful in cases
> such as:
> flags = re.DOTALL if dotall else re.NONE
>
> Also useful for "building up" flags by ORing with other flags.

-1

0 is even more useful. YAGNI.

BTW everybody try typing NONE a few times fast ... if your fingers
don't fight your brain and produce None anyway, you haven't been using
Python long enough :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wikipedia with python

2009-06-24 Thread Tim Harig
On 2009-06-22, ZeLegolas  wrote:
> On Mon, 22 Jun 2009 19:23:59 +0200, Andre Engels 
> wrote:
>> On Mon, Jun 22, 2009 at 6:58 PM, zelegolas wrote:
>>> I'm looking for wiki writen with python where I can import all
>>> wikipedia site.
>> PHP.
>> What do you want to use the material for?
> Well sorry I was not clear. I have a wiki running with mediawiki and I want
> to import in a wiki written with python. 

To clarify, check one:

[ ] A. You already have mediawiki wiki running on a web server; but, you
would prefer to have your wiki power by Python.

[ ] B. You already have mediawiki running on a web server and you have
another wiki powered by Python; and, you would like to take the
information from the python powered wiki and copy it to the
mediawiki.

[ ] C. You already have mediawiki running on a web server and you would
also like to use the functionality of a wiki which is written in
Python.  Somehow, you would like to somehow access some of the
Python's functionality and use it from inside of mediawiki.
Perhaps making them work side by side.

[ ] D. You already have mediawiki running on a webserver; but, you would
like to get data from another mediawiki server that you don't have
direct database access to; so, you would like to write a script in
Python to scrape the data off of the other mediawiki's website.

[ ] E. You already have a wiki running in python on a webserver and you
would like to import data from another wiki that is powered by
mediawiki.  You might or might not have direct access to the
database used by the wikimedia server.  You would like a Python
script to convert/scrap the data.

[ ] F. Other
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wikipedia with python

2009-06-24 Thread Andre Engels
On Wed, Jun 24, 2009 at 9:17 AM, Tim Harig wrote:

> [ ] D. You already have mediawiki running on a webserver; but, you would
>        like to get data from another mediawiki server that you don't have
>        direct database access to; so, you would like to write a script in
>        Python to scrape the data off of the other mediawiki's website.

In case D (and more general, to anyone who wants to do something to a
Mediawiki wiki using Python), you can use the Python Wikipediabot
Framework, http://pywikipediabot.sourceforge.net/


-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: walking a directory with very many files

2009-06-24 Thread Lie Ryan
Lawrence D'Oliveiro wrote:
> In message , Steven 
> D'Aprano wrote:
> 
>> On Tue, 23 Jun 2009 10:29:21 -0400, Mel wrote:
>>
>>> Steven D'Aprano wrote:
>>>
 Lawrence D'Oliveiro wrote:

>> Ok, now pipe ls to less, take three days to browse through all the
>> filenames to locate the file you want to see.
> Sounds like you're approaching the issue with a GUI-centric mentality,
> which is completely hopeless at dealing with this sort of situation.
 Piping the output of ls to less is a GUI-centric mentality?
>>> Yeah.  The "dump it on the user" idea, or more politely "can't decide
>>> anything until the user has seen everything" is evident in the most
>>> "characteristic" GUIs.
>> Perhaps you're using different GUIs to me. In my experience, most GUIs
>> tend to *hide* data from the user rather than give them everything under
>> the sun.
> 
> Which is getting a bit away from what we're discussing here, but certainly 
> it is characteristic of GUIs to show you all 400,000 files in a directory, 
> or at least try to do so, and either hang for half an hour or run out of 
> memory and crash, rather than give you some intelligent way of prefiltering 
> the file display up front.

In many debugging cases, you don't even know what to filter, which is
what I was referring to when I said "Even with glob and grep ..."

For example, when the problem mysteriously disappears when the file is
isolated
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wikipedia with python

2009-06-24 Thread Lie Ryan
ZeLegolas wrote:
> On Mon, 22 Jun 2009 19:23:59 +0200, Andre Engels 
> wrote:
>> On Mon, Jun 22, 2009 at 6:58 PM, zelegolas wrote:
>>> Let me know if it's the right place to ask.
>>>
>>> I'm looking for wiki writen with python where I can import all
>>> wikipedia site.
>>> If you have any links please let me know.
>> I don't think that's possible. If you wnat to import Wikipedia in a
>> wiki, it will probably have to be MediaWiki - and that's written in
>> PHP.
>>
>> What do you want to use the material for?
> 
> Well sorry I was not clear. I have a wiki running with mediawiki and I want
> to import in a wiki written with python. 
> 

Is there anything insufficient in mediawiki, that you think could be
satisfied with a python-based wiki? MediaWiki is one of the best wiki
software around, so any features not found in MediaWiki or its plugins
isn't likely to be available in another wiki (unless "written in a
language I know" is considered a feature).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.NONE

2009-06-24 Thread John Machin
On Jun 24, 5:18 pm, John Machin  wrote:
> On Jun 23, 8:35 am, 1x7y2z9 <1x7y...@gmail.com> wrote:
>
> > I am currently using python v2.5.2.
>
> > Not sure if this is defined in a later version, but it would be nice
> > to define re.NONE = 0 in the re module.  This would be useful in cases
> > such as:
> > flags = re.DOTALL if dotall else re.NONE
>
> > Also useful for "building up" flags by ORing with other flags.
>
> -1
>
> 0 is even more useful. YAGNI.
>
> BTW everybody try typing NONE a few times fast ... if your fingers
> don't fight your brain and produce None anyway, you haven't been using
> Python long enough :-)

Oh and I forgot to mention that if this proposal goes ahead it will
need a one-letter version -- perhaps re.Z -- and maybe even a PEP. It
could end up rivalling the legendary IEFBR14 in the ratio-of-overhead-
to-functionality stakes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to enumerate classes in a module

2009-06-24 Thread Carl Banks
On Jun 23, 10:02 pm, Дамјан Георгиевски  wrote:
> I need to programmaticaly enumerate all the classes in a given module.
> Currently I'm using dir(module) but the Notice on the documentation page
> [1]  says "dir() is supplied primarily as a convenience for use at an
> interactive prompt" so that kind of scares me.
>
> Is there a better approach?
>
> If there is, how do I get all the classes of the current module?


You can use module.__dict__.values() (or .itervalues()) to retrieve
the contents of the module (and of course .keys() if you want names).
If you want to check the same module that the code appears in, use
globals() instead of module.__dict__.

Something makes me think that module.__dict__ was only added to Python
fairly recently, but I'm not sure.

A word of warning (although I would guess you are already aware of
these issues, but for other readers): this method can't tell the
difference between a class defined in the module and a class imported
into it.

Finally, despite the warning, I think you are ok to use dir() for that
purpose.  It's not likely to change.


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


Re: GNUstep and Python

2009-06-24 Thread Lele Gaifax
Eric Brunel  writes:

> Diez B. Roggisch wrote:
>> Paul Watson schrieb:
>> There is the pyobjc-binding for OSX, maybe that's suitable for GNUStep.
>
> Apparently, it's not: There was some compatibility in earlier versions, but
> it's been officially removed in version 2.0. See
> http://pyobjc.sourceforge.net/NEWS-2.0.html :
> "GNUstep support has been removed because this has never worked properly,
> nobody seems interested in fixing that and the internal APIs of PyObjC have
> changed greatly."

It's been a lot of time ago, but that is wrong: when I initially
implemented PyObjC I put a lot of effort in understanding the
differences between the NeXT and the GNU ObjC runtimes, and PyObjC used
to work ok on both, with a slight bias toward the GNU runtime (having
the source at hands helps, as you know :-)

Version 2.0 brought major changes to the internals, mainly to support
the new MacOS frameworks, with tools to automatically create the needed
glue interfaces between the two worlds.

Too bad I wasn't involved/motivated enough to keep the GNU runtime
support up-to-date, and it was finally declared obsolete and removed.

Just a few cents of clarity,
ciao, lele.
-- 
nickname: Lele Gaifax| Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas| comincerò ad aver paura di chi mi copia.
l...@nautilus.homeip.net | -- Fortunato Depero, 1929.

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


RE: Converting Python code to C/C++

2009-06-24 Thread Couper, Tim T
Your prof. may find this thread of interest

http://mail.python.org/pipermail/python-list/2000-June/039779.html

My experience is that developers who know C and C++ can be productive in
less than 1 week in python, and find it liberating, and educational, to
do so. And at the same time they will have added a second language to
their toolbox. As Kurt points out, learning C/C++ takes considerably
longer (weeks/months to attain a level of competence). 

Python is now used in a number of universities as the language in which
to teach comp sci undergraduate courses (I know of Leeds, & MIT),
biomathematics, and my daughter just finished her PhD in speech and
language processing at Edinburgh .. using python and Matplotlib .. as
the extensive C/C++ libraries in that infomatics world are wrapped in
python - and the MSc Comp Sci course has replaced Java as the language
for teaching with Python.

Dr Tim Couper 

-Original Message-
From: python-list-bounces+tim.couper=standardbank@python.org
[mailto:python-list-bounces+tim.couper=standardbank@python.org] On
Behalf Of Kurt Smith
Sent: 23 June 2009 16:50
Cc: python-list@python.org
Subject: Re: Converting Python code to C/C++

On Mon, Jun 22, 2009 at 9:49 PM, Andras
Pikler wrote:
> Hi!
>
>
>
> Short: I need to turn a Python program that I (mostly) wrote into C 
> code, and I am at a loss.
>
>
>
> Long: I'm doing research/programming for a professor, and we are 
> working with MIDI files (a type of simple music file). The research 
> deals with generating variations from a musical melody; currently, my 
> Python code uses a Python midi package I found online to read the 
> notes in question from a midi file, about 350 lines of my own code to 
> generate a variation based on these notes and the professor's 
> algorithms, and finally the package again to write the new melody to
another midi file.
>
>
>
> Now, my professor would like to have this exact code in C/C++, as she 
> believes C is more compatible with MATLAB, and wants the code to be 
> available in multiple languages in case a programmer works for her in 
> the future who knows C but not Python. While I know a tiny bit of C 
> (emphasis on the tiny), I would much prefer if there were some sort of

> automatic compiler I could use to turn my Python code into C than 
> taking a week or two or three to learn the minimum I need about C, 
> find a way to access MIDI files in it, and rewrite all of my code.
>
>
>
> After some googling, I found and tried Shedskin, but it doesn't work, 
> as the Python midi package I'm using uses modules which Shedskin does
not support.
> Otherwise, I haven't found much. Is there anything out there to help 
> me do this? If not, from anyone who has experience in this regard, how

> daunting should I expect this to be?


Taking on C from a cold start and being able to handle the ins and outs
of interfacing with Python isn't something that's feasible in 'two or
three weeks'.  Here are a couple of options -- take 'em or leave 'em:

1) Put the code in Cython: http://www.cython.org/  (full disclosure:
I'm doing a GSoC project with Cython).  It will convert pretty much any
python code into C code (even closures are supported in the most recent
version, I think), and the C code can then be compiled into an extension
module.

The only problem with the above is the C code isn't, at first blush,
easy to read.  Nor is it supposed to be changed by the user.  So that
leads us to option...

2) Write the core functionality in C yourself, and then wrap those C
functions in Cython.  You'll want to take a look at the documentation:

http://docs.cython.org/

and, more specifically on wrapping C code:

http://docs.cython.org/docs/external_C_code.html

I don't think you'll be able to avoid learning C, though.

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


*
This communication is sent by the Standard Bank Plc or one of its affiliates
The registered details of Standard Bank Plc are: 
Registered in England No. 2130447, Registered Office 25 Dowgate Hill London 
EC4R 2SB
Authorised and Regulated by the Financial Services Authority. 

More information on Standard Bank is available at www.standardbank.com
 
Everything in this email and any attachments relating to the official business 
of Standard Bank Group Limited and any or all subsidiaries, the Company, is 
proprietary to the Company. It is confidential, legally privileged and 
protected by relevant laws. The Company does not own and endorse any other 
content. Views and opinions are those of the sender unless clearly stated as 
being that of the Company.
 
The person or persons addressed in this email are the sole authorised 
recipient. Please notify the sender immediately if it has unintentionally, or 
inadvertently reached you and do not read, disclose or use the content in any 
way and delete this e-mail from your system.  

The Company cannot ensure th

Re: Meta question: disappearing posts (was Re: calculating aself.value, self.randomnum = normalvariate(x, y))

2009-06-24 Thread Hendrik van Rooyen
"Aahz"  wrote:

> While that's also a bug in Mailman (I have a long-standing to-do item to
> fix that), there are also plenty of posts that simply aren't showing up
> in c.l.py.  As I said, I'm pretty sure (based on what was happening with
> c.l.py.announce) that it's some kind of weird problem with the mail->news
> gateway with MIME posts.

I have lately had some posts returned with a "seems to be forged" message.
Two reasons for that:
- first is if I use the smtp server from our local telco - saix - then there is
  no apparent relationship between where the message comes from and
  where it comes from, if you follow my Irish...
- Second is if the same telco assigns me an IP that has been put on a list
  of bad boy IPs.

So it is kind of pot luck if you see this message or not.

- Hendrik


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


Re: Measuring Fractal Dimension ?

2009-06-24 Thread pdpi
On Jun 23, 6:49 pm, Lie Ryan  wrote:
> Mark Dickinson wrote:
> > On Jun 23, 3:52 am, Steven D'Aprano
> >  wrote:
> >> On Mon, 22 Jun 2009 13:43:19 -0500, David C. Ullrich wrote:
> >>> In my universe the standard definition of "log" is different froim what
> >>> log means in a calculus class
> >> Now I'm curious what the difference is.
>
> > It's just the usual argument about whether 'log' means
> > log base 10 or log base e (natural log).  At least in the
> > US, most[*] calculus texts (and also most calculators),
> > for reasons best known to themselves, use 'ln' to mean
> > natural log and 'log' to mean log base 10.  But most
> > mathematicians use 'log' to mean natural log:  pick up a
> > random pure mathematics research paper that has the word
> > 'log' in it, and unless it's otherwise qualified, it's
> > safe to assume that it means log base e.  (Except in the
> > context of algorithmic complexity, where it might well
> > mean log base 2 instead...)
>
> I usually use log without explicit base only when the base isn't
> relevant in the context (i.e. when whatever sane base you put in it
> wouldn't really affect the operations). In algorithmic complexity, a
> logarithm's base doesn't affect the growth shape and, like constant
> multiplier, is considered irrelevant to the complexity.
>
> > Python also suffers a bit from this confusion:  the
> > Decimal class defines methods 'ln' and 'log10', while
> > the math module and cmath modules define 'log' and
> > 'log10'.  
>
> In fact, in the Decimal class there is no log to an arbitrary base.
>
> > (But the Decimal module has other problems,
> > like claiming that 0**0 is undefined while
> > infinity**0 is 1.)
>
> Well, in math inf**0 is undefined. Since python is programming language,
> and in language standards it is well accepted that undefined behavior
> means implementations can do anything they like including returning 0,
> 1, 42, or even spitting errors, that doesn't make python non-conforming
> implementation.
>
> A more serious argument: in IEEE 745 float, inf**0 is 1. Mathematic
> operation in python is mostly a wrapper for the underlying C library's
> sense of math.
>
>
>
> > [*] A notable exception is Michael Spivak's 'Calculus', which also
> > happens to be the book I learnt calculus from many years ago.

Well, AFAIK Python defines CPython as the standard. So whatever
CPython does is the defined behaviour.

Regarding inf ** 0, why does IEEE745 define it as 1, when there is a
perfectly fine NaN value?
-- 
http://mail.python.org/mailman/listinfo/python-list


Dictionary self lookup

2009-06-24 Thread Norberto Lopes
Hi all.
Assuming that python dictionaries already provide a bit of "shoot
yourself in the foot", I think what I have in mind would not be so
bad.

What do you think of dictionaries having a self lookup in their
declaration?

Be able to do this:

a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax

instead of:

a = { "foo" : "foo1" }
a["bar"] = a["foo"]

Maybe I'm murdering python syntax/philosophy right here so let me know
if that's the case.
I was thinking this could probably be done in python abstract tree but
as I never looked into it I may be wrong. I'm willing to make the
effort, provided I get some directions and that this idea is worth it.

Any feedback is welcome.

Cheers,
Norberto
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open source python projects

2009-06-24 Thread saurabh

Thanks a lot everyone for your prompt replies. I am really glad to see so
many options for me.
I am sure joining any of the above projects will enrich my understanding
of python and programming.I will just have to find out , to which project
I will be most useful.I will definitely join one of them.


-Saurabh


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


Re: Dictionary self lookup

2009-06-24 Thread Diez B. Roggisch
Norberto Lopes wrote:

> Hi all.
> Assuming that python dictionaries already provide a bit of "shoot
> yourself in the foot", I think what I have in mind would not be so
> bad.

What kind of foot-shooting do you have in mind?
> 
> What do you think of dictionaries having a self lookup in their
> declaration?
> 
> Be able to do this:
> 
> a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
> 
> instead of:
> 
> a = { "foo" : "foo1" }
> a["bar"] = a["foo"]
> 
> Maybe I'm murdering python syntax/philosophy right here so let me know
> if that's the case.
> I was thinking this could probably be done in python abstract tree but
> as I never looked into it I may be wrong. I'm willing to make the
> effort, provided I get some directions and that this idea is worth it.
> 
> Any feedback is welcome.

Obviously the proposed syntax can't work, as at the time of the dictionary
construction the name the dict is bound to is either not known, or even
bound to *another* dict. 

Additionally, the code would be by no means more efficient than the
above "long" version, as whatever notation you chose, it won't help to deal
with the fact that the dict-object itself, and also a potentially reference
key, aren't already available.

So behind the curtain, the exact same logic would apply, with all
runtime-costs.

Which leaves us with the question: why the heck do you want this? 

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


Re: Python 3.0.1 and mingw

2009-06-24 Thread smartmobili
On 24 juin, 05:06, Kay Schluehr  wrote:
> On 24 Jun., 00:59, smartmobili  wrote:
>
>
>
>
>
>
>
> > I wanted to know if you have some patch to compile python 3.x on mingw
> > platform because I found some
> > but doesn't work very well :
>
> >     make
>
> > gcc   -o python.exe \
> > Modules/python.o \
> > libpython3.0.a    -lm
> > Could not find platform independent libraries 
> > Could not find platform dependent libraries 
> > Consider setting $PYTHONHOME to [:]
> > Fatal Python error: Py_Initialize: can't initialize sys standard
> > streams
> > ImportError: No module named encodings.utf_8
>
> > I have some questions about posixmodule.c, config.c and makesetup,
> > I can see in posixmodule that you define a INITFUNC like this :
>
> > #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined
> > (__BORLANDC__)) &&
> > !defined(__QNX__)
> > #define INITFUNC PyInit_nt
> > #define MODNAME "nt"
>
> > #elif defined(PYOS_OS2)
> > #define INITFUNC PyInit_os2
> > #define MODNAME "os2"
>
> > #else
> > #define INITFUNC PyInit_posix
> > #define MODNAME "posix"
> > #endif
>
> > So first I tried to add || defined(MINGW32) to declare a
> > PyInit_nt
> > but after config.c
> > was still using PyInit_posix. How does makesetup choose to include one
> > function or another ?
> > So finally python is using PyInit_posix...
>
> > and after any idea why I got the compilation error ?
>
> Why on earth do you want to compile Python 3.0.1?

Because I need python to be able to compile other libraries on mingw
(subcersion, ).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary self lookup

2009-06-24 Thread Diez B. Roggisch
Norberto Lopes wrote:

> Hi all.
> Assuming that python dictionaries already provide a bit of "shoot
> yourself in the foot", I think what I have in mind would not be so
> bad.
> 
> What do you think of dictionaries having a self lookup in their
> declaration?
> 
> Be able to do this:
> 
> a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
> 
> instead of:
> 
> a = { "foo" : "foo1" }
> a["bar"] = a["foo"]
> 
> Maybe I'm murdering python syntax/philosophy right here so let me know
> if that's the case.
> I was thinking this could probably be done in python abstract tree but
> as I never looked into it I may be wrong. I'm willing to make the
> effort, provided I get some directions and that this idea is worth it.
> 
> Any feedback is welcome.

I doubt this will ever be accepted, but out of curiosity: *why* do you want
this?

And if you are willing to put some constraints on you keys, it would be easy
enough to do this:

def wicked_dict(**kwargs):
mappings = [(name, source) for name, source in kwargs.iteritems() if
name.startswith("_")
res = dict((key, value) for key, value in kwarges.iteritems() if not
name.startswith("_"))
for name, source in mappings:
res[name] = res[source]
return res


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


Re: Dictionary self lookup

2009-06-24 Thread Chris Rebert
On Wed, Jun 24, 2009 at 2:39 AM, Norberto Lopes wrote:
> Hi all.
> Assuming that python dictionaries already provide a bit of "shoot
> yourself in the foot", I think what I have in mind would not be so
> bad.
>
> What do you think of dictionaries having a self lookup in their
> declaration?
>
> Be able to do this:
>
> a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
>
> instead of:
>
> a = { "foo" : "foo1" }
> a["bar"] = a["foo"]
>
> Maybe I'm murdering python syntax/philosophy right here so let me know
> if that's the case.

The idea sounds quite confusing and seems unnecessary.

Specifically, your proposal appears to contravene the following points
of the holy Zen of Python:

- Explicit is better than implicit.
- Readability counts.
- Special cases aren't special enough to break the rules.
- In the face of ambiguity, refuse the temptation to guess.
- If the implementation is hard to explain, it's a bad idea.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary self lookup

2009-06-24 Thread Norberto Lopes
On Jun 24, 11:59 am, "Diez B. Roggisch"  wrote:
> Norberto Lopes wrote:
> > Hi all.
> > Assuming that python dictionaries already provide a bit of "shoot
> > yourself in the foot", I think what I have in mind would not be so
> > bad.
>
> What kind of foot-shooting do you have in mind?
>

a = { "foo" : { "bar" : "moo" }}
a["bar"] = a["foo"]
print a
{'foo': {'bar': 'moo'}, 'bar': {'bar': 'moo'}}
a["foo"]["bar"] = a["foo"]
print a
{'foo': {'bar': {...}}, 'bar': {'bar': {...}}}

(I know it's not a C shoot in the foot or something but still...)
>
>
>
>
>
>
> > What do you think of dictionaries having a self lookup in their
> > declaration?
>
> > Be able to do this:
>
> > a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
>
> > instead of:
>
> > a = { "foo" : "foo1" }
> > a["bar"] = a["foo"]
>
> > Maybe I'm murdering python syntax/philosophy right here so let me know
> > if that's the case.
> > I was thinking this could probably be done in python abstract tree but
> > as I never looked into it I may be wrong. I'm willing to make the
> > effort, provided I get some directions and that this idea is worth it.
>
> > Any feedback is welcome.
>
> Obviously the proposed syntax can't work, as at the time of the dictionary
> construction the name the dict is bound to is either not known
With just more thatn syntactic sugar this could be done

>, or even bound to *another* dict.
>
doh! Didn't thought about that one. Nice catch.

> Additionally, the code would be by no means more efficient than the
> above "long" version, as whatever notation you chose, it won't help to deal
> with the fact that the dict-object itself, and also a potentially reference
> key, aren't already available.
>
> So behind the curtain, the exact same logic would apply, with all
> runtime-costs.
>
> Which leaves us with the question: why the heck do you want this?
>
Syntactic sugar basically. I'm not ranting about performance, just
easier write up.

config = {"home" : "/home/test", "user1": config["home"] + "/user1",
"user2" : config["home"] + "/user2", "python-dev" : config["user1"] +
"/Projects/py-dev" }

config = {"home" : "/home/test"}
config["user1"] = config["home"] + "/user1"
config["user2"] = config["home"] + "/user2"
config["python-dev"] = config["user1"] + "/py-dev"


Now, if you change config["home"] you'd have to redo all of the other
entries. With the first one (assuming pointers to the entries)
everything would get updated. Although python does not handles dict
keys/values this way. Now that I think of this there would be a lot
more than just syntactic sugar for this.

(ignore the path concatenation without os.path)


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


Re: Dictionary self lookup

2009-06-24 Thread Norberto Lopes
On Jun 24, 12:05 pm, Chris Rebert  wrote:
> On Wed, Jun 24, 2009 at 2:39 AM, Norberto Lopes wrote:
> > Hi all.
> > Assuming that python dictionaries already provide a bit of "shoot
> > yourself in the foot", I think what I have in mind would not be so
> > bad.
>
> > What do you think of dictionaries having a self lookup in their
> > declaration?
>
> > Be able to do this:
>
> > a = {"foo" : "foo1", "bar" : a["foo"]} # or with another syntax
>
> > instead of:
>
> > a = { "foo" : "foo1" }
> > a["bar"] = a["foo"]
>
> > Maybe I'm murdering python syntax/philosophy right here so let me know
> > if that's the case.
>
> The idea sounds quite confusing and seems unnecessary.
>
> Specifically, your proposal appears to contravene the following points
> of the holy Zen of Python:
>
> - Explicit is better than implicit.
> - Readability counts.
> - Special cases aren't special enough to break the rules.
> - In the face of ambiguity, refuse the temptation to guess.
> - If the implementation is hard to explain, it's a bad idea.
>
> Cheers,
> Chris
> --http://blog.rebertia.com


Ok, no arguments against this one :(

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


fileinput.input, readlines and ...

2009-06-24 Thread Przemyslaw Bak
Hello,

I many files with log data. The structure of the file is quite
inconvenience and similar to the following example:
Data1
  ValueA
Data2
  ValueB
Data3
  ValueC
...
To get the values I need to find Data* and then get to the next line.
I tried to use fileinput.input :
...
for line in fileinput.input(filename):
if line.find("Data2") >= 0:
(now what ?)

So I can find the requested line (Data2) but how to get value from the
next line ?
Is the fileinput.input the most convenient for this type of task ?
Maybe
readline or readlines would be better ?
What can you recommend ?

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


Windows: open() -> "[Errno 38] Filename too long"

2009-06-24 Thread robert

When doing open/os.stat/...(dirpath+filename)
and total path > 250 chars then

OSError: "[Errno 38] Filename too long"

is there a way to access the file without changing to that 
directory (its in a thread and a fast iteration of many file too) ?

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


Re: Windows: open() -> "[Errno 38] Filename too long"

2009-06-24 Thread Tim Golden

robert wrote:

When doing open/os.stat/...(dirpath+filename)
and total path > 250 chars then

OSError: "[Errno 38] Filename too long"

is there a way to access the file without changing to that directory 
(its in a thread and a fast iteration of many file too) ?


Change filename 


 r"c:\temp\long.txt"

to

 ur"\\?\c:\temp\long.txt"


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


Re: Measuring Fractal Dimension ?

2009-06-24 Thread Mark Dickinson
On Jun 24, 10:12 am, pdpi  wrote:
> Regarding inf ** 0, why does IEEE745 define it as 1, when there is a
> perfectly fine NaN value?

Have a look at:

http://www.eecs.berkeley.edu/~wkahan/ieee754status/ieee754.ps

(see particularly page 9).

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


Re: Dictionary self lookup

2009-06-24 Thread Diez B. Roggisch
Norberto Lopes wrote:

> On Jun 24, 11:59 am, "Diez B. Roggisch"  wrote:
>> Norberto Lopes wrote:
>> > Hi all.
>> > Assuming that python dictionaries already provide a bit of "shoot
>> > yourself in the foot", I think what I have in mind would not be so
>> > bad.
>>
>> What kind of foot-shooting do you have in mind?
>>
> 
> a = { "foo" : { "bar" : "moo" }}
> a["bar"] = a["foo"]
> print a
> {'foo': {'bar': 'moo'}, 'bar': {'bar': 'moo'}}
> a["foo"]["bar"] = a["foo"]
> print a
> {'foo': {'bar': {...}}, 'bar': {'bar': {...}}}
> 
> (I know it's not a C shoot in the foot or something but still...)

And something working alike for lists and objects. Cyclic references are a
fact of (programming)-life unless you go fully functional - and then you'd
certainly miss it sometimes..

> config = {"home" : "/home/test"}
> config["user1"] = config["home"] + "/user1"
> config["user2"] = config["home"] + "/user2"
> config["python-dev"] = config["user1"] + "/py-dev"
> 
> 
> Now, if you change config["home"] you'd have to redo all of the other
> entries. With the first one (assuming pointers to the entries)
> everything would get updated. Although python does not handles dict
> keys/values this way. Now that I think of this there would be a lot
> more than just syntactic sugar for this.

Things that are re-done usually are useful being put into a function. Then
redoing becomes easier :)

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


Re: Dictionary self lookup

2009-06-24 Thread Norberto Lopes
On Jun 24, 1:21 pm, "Diez B. Roggisch"  wrote:
> Norberto Lopes wrote:
> > On Jun 24, 11:59 am, "Diez B. Roggisch"  wrote:
> >> Norberto Lopes wrote:
> >> > Hi all.
> >> > Assuming that python dictionaries already provide a bit of "shoot
> >> > yourself in the foot", I think what I have in mind would not be so
> >> > bad.
>
> >> What kind of foot-shooting do you have in mind?
>
> > a = { "foo" : { "bar" : "moo" }}
> > a["bar"] = a["foo"]
> > print a
> > {'foo': {'bar': 'moo'}, 'bar': {'bar': 'moo'}}
> > a["foo"]["bar"] = a["foo"]
> > print a
> > {'foo': {'bar': {...}}, 'bar': {'bar': {...}}}
>
> > (I know it's not a C shoot in the foot or something but still...)
>
> And something working alike for lists and objects. Cyclic references are a
> fact of (programming)-life unless you go fully functional - and then you'd
> certainly miss it sometimes..
>
Yes. (and sometimes you miss functional :D)

> > config = {"home" : "/home/test"}
> > config["user1"] = config["home"] + "/user1"
> > config["user2"] = config["home"] + "/user2"
> > config["python-dev"] = config["user1"] + "/py-dev"
>
> > Now, if you change config["home"] you'd have to redo all of the other
> > entries. With the first one (assuming pointers to the entries)
> > everything would get updated. Although python does not handles dict
> > keys/values this way. Now that I think of this there would be a lot
> > more than just syntactic sugar for this.
>
> Things that are re-done usually are useful being put into a function. Then
> redoing becomes easier :)
>
> Diez

True.
In any case, reading from your pov, it seems that the solution would
cause more problems than solving one.

Thanks for the feedback though.
Much appreciated :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fileinput.input, readlines and ...

2009-06-24 Thread Peter Otten
Przemyslaw Bak wrote:

> Hello,
> 
> I many files with log data. The structure of the file is quite
> inconvenience and similar to the following example:
> Data1
>   ValueA
> Data2
>   ValueB
> Data3
>   ValueC
> ...
> To get the values I need to find Data* and then get to the next line.
> I tried to use fileinput.input :
> ...
> for line in fileinput.input(filename):
> if line.find("Data2") >= 0:
> (now what ?)
> 
> So I can find the requested line (Data2) but how to get value from the
> next line ?

lines = fileinput.input(filename)
for line in lines:
if "Data2" in line:
print line.strip(), "-->", next(lines).strip()

> Is the fileinput.input the most convenient for this type of task ?
> Maybe
> readline or readlines would be better ?
> What can you recommend ?

If you need more than a few name value pairs it pays to put the data in a 
dictionary first:

# assuming that values always consist of a single line
with open(filename) as instream:
lines = (line.strip() for line in lines)
lookup =  dict(zip(lines, lines))
print lookup["Data2"]
print lookup["Data3"]

Peter

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


Re: Reading a large csv file

2009-06-24 Thread Mag Gam
Sorry for the delayed response. I was trying to figure this problem
out. The OS is Linux, BTW


Here is some code I have:
import numpy as np
from numpy import *

import gzip
import h5py
import re
import sys, string, time, getopt
import os

src=sys.argv[1]
fs = gzip.open(src)
x=src.split("/")
filename=x[len(x)-1]

#Get /MM/DD format
=(filename.rsplit(".",2)[0])[0:4]
MM=(filename.rsplit(".",2)[0])[4:6]
DD=(filename.rsplit(".",2)[0])[6:8]

f=h5py.File('/tmp/test_foo/FE.hdf5','w')

grp="/"+
try:
  f.create_group(grp)
except ValueError:
  print "Year group already exists"

grp=grp+"/"+MM
try:
  f.create_group(grp)
except ValueError:
  print "Month group already exists"

grp=grp+"/"+DD
try:
  group=f.create_group(grp)
except ValueError:
  print "Day group already exists"


str_type=h5py.new_vlen(str)
mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1',
'f4', 'f4')}
print "Filename is: ",src
fs = gzip.open(src)

dset = f.create_dataset ('Foo',data=arr,compression='gzip')

s=0

#Takes the longest here
for y in fs:
 continue
  a=y.split(',')
  s=s+1
  dset.resize(s,axis=0)
fs.close()

f.close()


This works but just takes a VERY long time.

Any way to optimize this?

TIA


On Wed, Jun 24, 2009 at 12:13 AM, Chris Withers wrote:
> Terry Reedy wrote:
>>
>> Mag Gam wrote:
>>>
>>> Yes, the system has 64Gig of physical memory.
>>
>> drool ;-).
>
> Well, except that, dependent on what OS he's using, the size of one process
> may well still be limited to 2GB...
>
> Chris
>
> --
> Simplistix - Content Management, Zope & Python Consulting
>           - http://www.simplistix.co.uk
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0.1 and mingw

2009-06-24 Thread lkcl
On Jun 23, 10:59 pm, smartmobili  wrote:
> I wanted to know if you have some patch to compile python 3.x on mingw
> platform because I found some
> but doesn't work very well :

 you should compile a 2.N version.

 despite efforts and proof that the efforts passed all but about 8-12
regression tests, the python development core team deemed the 2.5 and
the 2.7 mingw port efforts to be a waste of time.

 if you or anyone else disagrees with this, please do say so, on the
python-dev mailing list and also in the bugtracker.  at least one
person has already done so:

   http://bugs.python.org/issue4954#msg85994



  http://bugs.python.org/issue5046 states that i am not allowed to
post "work in progress", despite it being significantly complete, and
despite it being worthwhile to have added in as-is into the standard
python repository.

 http://bugs.python.org/issue4954 is where a python2.5 mingw native
_and_ cross-compile was successfully built.

 http://bugs.python.org/issue3871 is where roumen continues to provide
the benefits of the continuous work that he is doing.  when i last
checked, he wasn't able to do native mingw32 builds but only cross-
compiles, but that may have changed.

 the most significant difference between 4954 and 3871 at the time
when my efforts were terminated due to python developer hostility is
that i spent considerable time reducing the size of configure.

 firing up a new /bin/sh under MSYS, native, takes 0.7 seconds (and <
0.01 on a gnu/linux box). firing up a new /bin/sh under MSYS, running
under Wine, took _well_ over two seconds.

 consequently, running an "unmodified" version of configure would take
well over half an hour.

 by cutting most of configure out and going with a pre-prepared
Config.h i was able to reduce that time down to (only) about 10
minutes.

 which is just about tolerable.

 like all free software projects, there is considerable additional
work to be done: everything is "work in progress", but thanks to the
python developers applying one standard to themselves on what
constitutes "work in progress" and another for contributors, you will
not get the benefit of my input and expertise until you (python users)
can get the python developers to treat my efforts to help users with a
little more respect.

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


Re: Newbie queue question

2009-06-24 Thread Чеширский Кот
1. say me dbf files count?
2. why dbf ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring Fractal Dimension ?

2009-06-24 Thread Steven D'Aprano
On Mon, 22 Jun 2009 13:43:19 -0500, David C. Ullrich wrote:

> In my universe the standard definition of "log" is different froim what
> log means in a calculus class

Now I'm curious what the difference is.


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


Re: Measuring Fractal Dimension ?

2009-06-24 Thread Mark Dickinson
On Jun 24, 10:12 am, pdpi  wrote:
> Regarding inf ** 0, why does IEEE745 define it as 1, when there is a
> perfectly fine NaN value?

Other links:  the IEEE 754 revision working group mailing list
archives are public;  there was extensive discussion about
special values of pow and similar functions.  Here's a relevant
Google search:

http://www.google.com/search?q=site:grouper.ieee.org++pow+annex+D

The C99 rationale document has some explanations for the
choices for special values in Annex F.  Look at pages 179--182
in:

http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf

Note that the original IEEE 754-1985 didn't give specifications
for pow and other transcendental functions;  so a complete
specification for pow appeared in the C99 standard before it
appeared in the current IEEE standard, IEEE 754-2008.  Thus
C99 Annex F probably had at least some small influence on the
choices made for IEEE 754-2008 (and in turn, IEEE 754-1985
heavily influenced C99 Annex F).

My own take on all this, briefly:

 - floating-point numbers are not real numbers, so mathematics
   can only take you so far in deciding what the 'right' values
   are for special cases;  pragmatics has to play a role too.

 - there's general consensus in the numerical and mathematical
   community that it's useful to define pow(0.0, 0.0) to be 1.

 - once you've decided to define pow(0.0, 0.0) to be 1.0, it's
   easy to justify taking pow(inf, 0.0) to be 1.0:  the same
   limiting arguments can be used as justification;  or one can
   use reflection formulae like pow(1/x, y) = 1/pow(x, y), or...

 - one piece of general philosophy used for C99 and IEEE 754
   seems to have been that NaN results should be avoided
   when it's possible to give a meaningful non-nan value instead.

 - part of the reason that pow is particularly controversial
   is that it's really trying to be two different functions
   at once:  it's trying to be both a generalization of the
   `analytic' power function x**y = exp(y*log(x)), for
   real y and positive real x, and in this context one can
   make a good argument that 0**0 should be undefined; but
   at the same time it's also used in contexts where y is
   naturally thought of as an integer; and in the latter
   context bad things happen if you don't define pow(0, 0)
   to be 1.

I really should get back to work now.

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


Decode a barcode ?

2009-06-24 Thread Stephane Wirtel

Hi all,

I would like to know if there is a way to decode a barcode with a library ?

Thank you so much,

Stephane
--
Stephane Wirtel - "As OpenERP is OpenSource, please feel free to contribute."
Developper - Technical Lecturer OpenERP
OpenERP - Tiny SPRL
Chaussee de Namur, 40
B-1367 Gerompont
Tel: +32.81.81.37.00
Web: http://www.tiny.be
Web: http://www.openerp.com
Planet: http://www.openerp.com/planet/
Blog: http://stephane-wirtel-at-tiny.blogspot.com
begin:vcard
fn:Stephane Wirtel
n:Wirtel;Stephane
org:OpenERP - Tiny sprl
adr;quoted-printable;quoted-printable:;;Chauss=C3=A9e de Namur, 40;G=C3=A9rompont;;1367;Belgium
email;internet:s...@tinyerp.com
title:Developer
tel;work:+32.81.81.37.00
note;quoted-printable:OpenERP is an Open Source enterprise management software=0D=0A=
	=0D=0A=
	http://www.openerp.com
x-mozilla-html:FALSE
url:http://www.tiny.be
version:2.1
end:vcard

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


Re: dynamically associate radio buttons with droplists

2009-06-24 Thread Shoryuken
On Jun 21, 8:43 pm, a...@pythoncraft.com (Aahz) wrote:
> In article 
> ,LeoBrugud 
>  wrote:
>
>
>
> >Not being very familiar with python, nor with cgi/http,  I intend to
> >have 3 of buttons in a webpage, each of them is associate with a file
> >(so I have 3 files, too)
>
> >What I would like to have is, when users choose a button, the droplist
> >update automatically to load the contents of the associated file.
>
> >Can someone educate me the approach of this?
>
> Are you trying to do this without requiring the user to click the submit
> button?  If yes, you need to learn JavaScript (although I think there are
> web frameworks that will auto-generate the JavaScript, you need to know
> JavaScript in order to do debugging).
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> "as long as we like the same operating system, things are cool." --piranha

Thanks, and yes I want to do it without the submit button

So python alone cannot do this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decode a barcode ?

2009-06-24 Thread Chris Withers

Stephane Wirtel wrote:

I would like to know if there is a way to decode a barcode with a library ?


What do you mean by decode?
Do you mean starting with a .gif or something containing a barcode?

Most barcode readers just act as keyboards, so you don't often need to 
do this ;-)


If you mean something else, please elaborate!

Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decode a barcode ?

2009-06-24 Thread Marco Bizzarri
If you're looking for a library in python to find barcodes inside an image,
and then decoding it,  I'm afraid you're out of luck; as far as I can tell,
there is no such a library available.

In case you're looking for the theory on how to do that, I think this group
is not the best suited to post such a question :)

(( Despite the fact that many people could know the answer ))

regards
Marco

On Wed, Jun 24, 2009 at 3:06 PM, Stephane Wirtel wrote:

> Hi all,
>
> I would like to know if there is a way to decode a barcode with a library ?
>
> Thank you so much,
>
> Stephane
> --
> Stephane Wirtel - "As OpenERP is OpenSource, please feel free to
> contribute."
> Developper - Technical Lecturer OpenERP
> OpenERP - Tiny SPRL
> Chaussee de Namur, 40
> B-1367 Gerompont
> Tel: +32.81.81.37.00
> Web: http://www.tiny.be
> Web: http://www.openerp.com
> Planet: http://www.openerp.com/planet/
> Blog: http://stephane-wirtel-at-tiny.blogspot.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
Marco Bizzarri
http://code.google.com/p/qt-asterisk/
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Guppy-PE/Heapy 0.1.9 released

2009-06-24 Thread Sverker Nilsson
I am happy to announce Guppy-PE 0.1.9

Guppy-PE is a library and programming environment for Python,
currently providing in particular the Heapy subsystem, which supports
object and heap memory sizing, profiling and debugging. It also
includes a prototypical specification language, the Guppy
Specification Language (GSL), which can be used to formally specify
aspects of Python programs and generate tests and documentation from a
common source.

The main news in this release:

o A patch by Chad Austin to compile with Visual Studio 2003 and Python
  2.5 C compilers. I think this may fix similar problems with other
  Microsoft compilers.

o Interactive help system, providing a .doc attribute that can be used
  to get info on available attributes in text form and also by
  invoking a browser.

o New documentation file, heapy_tutorial.html.  It contains for now an
  example of how to get started and use the interactive help.

o Bug fix wrt pop for mutable bitset. (Not used in heapy, only in
  sets/test.py)

o guppy.hpy().test() now includes the set-specific tests.

o Remote monitor does not longer require readline library being
installed.


License: MIT

Guppy-PE 0.1.9 is available in source tarball format on the Python
Package Index (a.k.a. Cheeseshop):

http://pypi.python.org/pypi/guppy/0.1.9

The project homepage is on Sourceforge:

http://guppy-pe.sourceforge.net

Enjoy,

Sverker Nilsson

Expertise in Linux, embedded systems, image processing, C, Python...
http://sncs.se
-- 
http://mail.python.org/mailman/listinfo/python-list


IMPORTANT: I NEED TO HELP WITH ONE OF THE CORE DEVELOPERS

2009-06-24 Thread Pegasus
I need help with an implementation of your
interpreter under PSPE/PSP.

I need to know something about the C
functions that are recalled by the interpreter
when it executes a .pyc file.

Our version of ndPython is very slow in
execution respect to Carlos's StackLess
Python (another product for PSP).

We believe that the trouble is in a routine
of our Nanodesktop libc that can be
a bottleneck. But we don't know
which can be the interested routine
(string ? memory allocation ?)


Please, help us. The product is complete,
but we cannot release cause this problem.

Thank you in advance.
Filippo Battaglia


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


Re: IDLE / Python 2.5 under Jaunty

2009-06-24 Thread Michiel Overtoom


Duncan Smith wrote:

> IDLE now refuses to

respond to left click events (for code editing, menus etc. respond as
expected).  If I right click, then left click I can move the cursor, but
that's not ideal. 

>

So, has anybody else had the left click issue with IDLE (and solved it)?


Irritating problem, isn't it?  I experience the same on FreeBSD with Tk8.5.
I had to downgrade to Tk8.4, which has ugly fonts.

See http://bugs.python.org/issue2995

"Moving the mouse over the text widget changes the cursor to the I-beam
as expected, but click on text doesn't position the beam at the mouse
position.  It is also impossible to select text with the mouse.
Selecting text with shift-arrow keys works, however."

It's closed because it doesn't seem related to Python.

Greetings,



--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Meta question: disappearing posts (was Re: calculating a self.value, self.randomnum = normalvariate(x, y))

2009-06-24 Thread Ross Ridge
Ross Ridge   wrote:
>I'm not sure what MIME would have to do with it, but Piet van Oostrum's
>problem is almost certainly as result of the python.org mail to news
>gateway mangling the References header.  The missing postings he's looking
>for don't actually exist.  Just go up the thread one more posting and
>you'll find the message that was being replied to.

In article , Aahz  wrote:
>While that's also a bug in Mailman (I have a long-standing to-do item to
>fix that), there are also plenty of posts that simply aren't showing up
>in c.l.py.

Well, the message IDs that Piet van Oostrum gave are symptomatic of
the References header bug and and just like he described, my newsreader
also shows Dennis Lee Bieber always replying to posts that don't exist.
Other messages might be getting eaten by the gateway, but the missing
posts that Piet is complaining about almost certainly never existed.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring Fractal Dimension ?

2009-06-24 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:


>On Mon, 22 Jun 2009 13:43:19 -0500, David C. Ullrich wrote:
>
>> In my universe the standard definition of "log" is different froim what
>> log means in a calculus class
>
>Now I'm curious what the difference is.
>

Maybe he is a lumberjack, and quite all right...

- Hendrik



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


Re: C-extension 2 times slower than exe

2009-06-24 Thread Rolf Wester
Hello,

thank you all very much for your replies.

I tried to simplify things and make the two versions as comparable as
possible. I put the C++ part of the program into a shared object
libff.so. For the exe the main function is linked against this shared
object. For the python stuff I made an interface consiting of only one
function call_solver with the same code that has the main function used
for the exe. Then I created a wrapper for this interface using swig and
linked interface.o, ff_warp.o and libff.so into _ff.so. The Python code
just imports _ff and calls call_solver wich creates an object of the
class Solver and calls its member solve (the main function of the exe
does the same).

I included some code for timing into the C++-code.

#include 

//beginning of solve
clock_t t0 = clock();
...
clock_t t1 = clock();
//end of solve
cout << "time used = " << (t1-t0)/CLOCKS_PER_SEC << endl;

I'm using gcc4.5 (latest snapshot) and Python2.6 under Suse 10.3. The
sources are compiled using the flags -fPIC -O3.

Timing:

1) time python ff.py
time used = 3.74
real0m3.234s
user0m3.712s
sys 0m0.192s
2) time ff
time used = 2.19
real0m3.170s
user0m2.088s
sys 0m0.168s

I tried some other optimizations:

-O0:

1)
time used = 21.91
real0m21.568s
user0m22.001s
sys 0m0.160s

2)
time used = 20.87
real0m22.206s
user0m20.989s
sys 0m0.148s

-O1
1)
time used = 4.04
real0m3.660s
user0m4.000s
sys 0m0.160s

2)
time used = 2.72
real0m3.454s
user0m2.648s
sys 0m0.164s

It seems that there is an overhead of about 2 secs within the C++-code.
I'm going to try this out with a problem that takes much more time than
the present one.

Regards

Rolf

Carl Banks wrote:
> On Jun 23, 7:20 am, Rolf Wester  wrote:
>> Philip Semanchuk wrote:
>>
>>> On Jun 23, 2009, at 9:51 AM, Rolf Wester wrote:
 Hi,
 I have a C++ program that I would like to steer using Python. I made the
 wrapper using swig and linked the code (without the main function) into
 a shared object. My Python script loads the extension and calls a
 function of the C-extension, the rest runs entirely within the
 C-extension. For comparison I compiled the code including the main
 function with the same compilation options and linked all into an exe.
 The main function of the exe calls the same function as my Python script
 does. Surprisingly the code in the Python C-extension runs twice as long
 as the same code in the exe. Does anyone know what could be the reason
 for this behaviour?
>>> If the runtime of the C/C++ code is short, the time spent initializing
>>> the Python interpreter might have a big impact on the runtime of the
>>> Python version.
>> The runtime is about 2.5 sec and 5.0 sec respectively. I not only use
>> the time command to measure the time consumed but I also measure the
>> time within the C-code using clock() and get similar result. So the
>> Python startup time is not the reason for the runtime difference I
>> found. Thank you anyway.
> 
> We can't really help you much unless you give us more details about
> what you did (how did you built it, how did you time it, and how are
> you calling the C extension from Python).  All we can do is throw out
> possible ideas, and I will toss out a few, but if that's not it you'll
> have to post details.
> 
> Are you building the extension with the same optimization flags as the
> compiler?
> 
> Are you calling the C code repeatedly from inside a Python loop?
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Python code to C/C++

2009-06-24 Thread Grant Edwards
On 2009-06-24, Couper, Tim T  wrote:

> Your prof. may find this thread of interest
>
> http://mail.python.org/pipermail/python-list/2000-June/039779.html
>
> My experience is that developers who know C and C++ can be productive in
> less than 1 week in python, and find it liberating, and educational, to
> do so. And at the same time they will have added a second language to
> their toolbox. As Kurt points out, learning C/C++ takes considerably
> longer (weeks/months to attain a level of competence).

I agree.  Your professor is deluded and knows nothing about
software development [not that either is particularly unusual
in an academic setting].  Converting a Python program to C or
C++ is a complete waste of time (both now _and_ later) unless
there are severe, insurmountable performance problems with the
Python version.

Python is a far, far better language for both real-world
production application development and for algorithm R&D.  With
Python, you spend your time working on algorithms and solving
real-world problems.  In C or C++, you spend your time fighting
with the bugs in your code that are preventing the program from
running.  An algorithm that takes a few hours to implement and
test in Python will take weeks in C or C++.

That said, you'll be niether the first nor last person to be
forced by a professor or manager to waste weeks or months of
time doing something that's obviously stupid and futile from a
technical point of view.

-- 
Grant Edwards   grante Yow! What's the MATTER
  at   Sid? ... Is your BEVERAGE
   visi.comunsatisfactory?
-- 
http://mail.python.org/mailman/listinfo/python-list


Reading then sending new parts of a log file

2009-06-24 Thread Chuck Connors
Hey guys.  I'm trying to work up a little program that will send any
new lines written to a file (log file from my home automation
software) to me via instant message.  I've gotten the instant message
sending part figured out using xmpppy.

I've done a few things with Python in the past but I am in no means
more than a beginner/hacker.  Can someone tell me what commands/
modules/etc exist for monitoring and parsing a file for new
information that I can then send to my IM sending function?  I am not
asking for anyone to write the code but merely a push in the right
direction.

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


Re: Measuring Fractal Dimension ?

2009-06-24 Thread pdpi
On Jun 24, 2:58 pm, "Hendrik van Rooyen"  wrote:
> "Steven D'Aprano"  wrote:
> >On Mon, 22 Jun 2009 13:43:19 -0500, David C. Ullrich wrote:
>
> >> In my universe the standard definition of "log" is different froim what
> >> log means in a calculus class
>
> >Now I'm curious what the difference is.
>
> Maybe he is a lumberjack, and quite all right...
>
> - Hendrik

Or perhaps he works in a sewage facility.

But yeah, Log2 and LogE are the only two bases that make "natural"
sense except in specialized contexts. Base 10 (and, therefore, Log10)
is an artifact of having that 10 fingers (in fact, whatever base you
use, you always refer to it as base 10).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamically associate radio buttons with droplists

2009-06-24 Thread Aahz
In article <16b382ee-a3ae-46ee-88fd-d87fc40d2...@g20g2000vba.googlegroups.com>,
Shoryuken   wrote:
>On Jun 21, 8:43=A0pm, a...@pythoncraft.com (Aahz) wrote:
>> In article .com>,LeoBrugud=A0 wrote:
>>>
>>>Not being very familiar with python, nor with cgi/http, =A0I intend to
>>>have 3 of buttons in a webpage, each of them is associate with a file
>>>(so I have 3 files, too)
>>>
>>>What I would like to have is, when users choose a button, the droplist
>>>update automatically to load the contents of the associated file.
>>
>> Are you trying to do this without requiring the user to click the submit
>> button? =A0If yes, you need to learn JavaScript (although I think there a=
>re
>> web frameworks that will auto-generate the JavaScript, you need to know
>> JavaScript in order to do debugging).
>
>Thanks, and yes I want to do it without the submit button
>
>So python alone cannot do this?

Correct; you need to have code run in the browser, and few browsers
support Python.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0.1 and mingw

2009-06-24 Thread Gabriel Genellina
En Wed, 24 Jun 2009 08:55:07 -0300, lkcl   
escribió:

On Jun 23, 10:59 pm, smartmobili  wrote:



I wanted to know if you have some patch to compile python 3.x on mingw
platform because I found some
but doesn't work very well :


 you should compile a 2.N version.
 [...]
  http://bugs.python.org/issue5046 states that i am not allowed to
post "work in progress", despite it being significantly complete, and
despite it being worthwhile to have added in as-is into the standard
python repository.


What you've been told is not to use the Python bug tracker as a blog. You  
could write about your progresses in *another* place, and maybe from time  
to time post a link here so interested people is aware of it.



 by cutting most of configure out and going with a pre-prepared
Config.h i was able to reduce that time down to (only) about 10
minutes.


That's fine, the "official" Windows build uses a hand written config.h too.


 like all free software projects, there is considerable additional
work to be done: everything is "work in progress", but thanks to the
python developers applying one standard to themselves on what
constitutes "work in progress" and another for contributors, you will
not get the benefit of my input and expertise until you (python users)
can get the python developers to treat my efforts to help users with a
little more respect.


If you expect your work to be taken seriously, work seriously. Randomly  
changing code until some symptom disappears isn't a very good practice,  
I'd say. Try to polish the patches a little until you are happy with them,  
and only then submit them.


--
Gabriel Genellina

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


isinstance(obj, type(obj)) == True?

2009-06-24 Thread Art
I have the following problem:

ipdb> p type(self)


ipdb> isinstance(self, component.BiasComponent)
False

I thought that isinstance(obj, type(obj)) == True.

The specific problem is when I try to call the super of a class and it
only occurs after 'reload'ing the file in the interpreter. What am I
messing up by reloading? It doesn't occur if I using for the first
time in a fresh interpreter session.

---> 32 class BiasComponent(ModelComponent):
  33 def __init__(self, g, model):
  34 super(BiasComponent, self).__init__(g, model)

TypeError: super(type, obj): obj must be an instance or subtype of
type

Seems like the self passed to __init__ is messed up in some way.

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


Animate Surface / Clear Scene (vpython)

2009-06-24 Thread Philip Gröger
Hi there!
I just found a nice vpython example program on how to create surfaces (its
one of the standard examples if you download vpython ... called
"faces_heightfield" - just search for that).

Is there a way to animate this surface?
All my attempts resulted in creating just another surface without deleting
the old one.
Or is there a "clear scene from all objects" command?

If animating such a surface in vpython is too complicated / slow / etc ... I
have to try mayavi. But I already know vpython ;)


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


A superclass using a child classes' methods

2009-06-24 Thread Kurt Schwehr
I'm trying to build an OO system for encoding and decoding
datapackets.  I'd like the parent class to have an encode function
that uses each of the child classes' packing methods.  It appears that
this works for attributes of children accessed by the parent, but not
for methods.  Is that right?  For attributes I found this example,
where the alphabet attribute is set in the child, but used in the
parent.

http://www.pasteur.fr/formation/infobio/python/ch19s04.html

Should I just set an attribute in the child class and then call the
super's functionality making is pull the data from the attribute?

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


Re: A superclass using a child classes' methods

2009-06-24 Thread Michael Torrie
Kurt Schwehr wrote:
> I'm trying to build an OO system for encoding and decoding
> datapackets.  I'd like the parent class to have an encode function
> that uses each of the child classes' packing methods.  It appears that
> this works for attributes of children accessed by the parent, but not
> for methods.  Is that right?  For attributes I found this example,
> where the alphabet attribute is set in the child, but used in the
> parent.

There is no difference between an attribute and a method.  They are both
attributes.  One happens to be callable and is a method call.

I just tried it and it seemed to work fine.  In my old C++ days, I
believe you would call this scenario virtual classes.  In python, since
everything is dynamic and computed at runtime, I think you can just
refer to any attribute in the instance and as long as someone down the
road provides it, it would work.

For example:

class parent(object):
def test(self):
print self.child_attribute
self.child_method()

class child(parent):
def __init__(self):
self.child_attribute = 'child'

def child_method(self):
print 'child method is called'


c=child()
c.test()

This should display "child" and "child method is called"


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


Re: IMPORTANT: I NEED TO HELP WITH ONE OF THE CORE DEVELOPERS

2009-06-24 Thread Brian Quinlan

You could start by reading this:
http://catb.org/~esr/faqs/smart-questions.html

Cheers,
Brian

Pegasus wrote:

I need help with an implementation of your
interpreter under PSPE/PSP.

I need to know something about the C
functions that are recalled by the interpreter
when it executes a .pyc file.

Our version of ndPython is very slow in
execution respect to Carlos's StackLess
Python (another product for PSP).

We believe that the trouble is in a routine
of our Nanodesktop libc that can be
a bottleneck. But we don't know
which can be the interested routine
(string ? memory allocation ?)


Please, help us. The product is complete,
but we cannot release cause this problem.

Thank you in advance.
Filippo Battaglia




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


Re: IDLE / Python 2.5 under Jaunty

2009-06-24 Thread duncan smith
Michiel Overtoom wrote:
> 
> Duncan Smith wrote:
> 
>> IDLE now refuses to
>> respond to left click events (for code editing, menus etc. respond as
>> expected).  If I right click, then left click I can move the cursor, but
>> that's not ideal. 
>>
>> So, has anybody else had the left click issue with IDLE (and solved it)?
> 
> Irritating problem, isn't it?  I experience the same on FreeBSD with Tk8.5.
> I had to downgrade to Tk8.4, which has ugly fonts.
> 
> See http://bugs.python.org/issue2995
> 
> "Moving the mouse over the text widget changes the cursor to the I-beam
> as expected, but click on text doesn't position the beam at the mouse
> position.  It is also impossible to select text with the mouse.
> Selecting text with shift-arrow keys works, however."
> 
> It's closed because it doesn't seem related to Python.
> 
> Greetings,
> 

Thanks for the responses.  I searched far and wide, and couldn't find
anyone else having the same problem.  I have Tk 8.4.19-2 and 8.5.6-3 on
this machine.  I remember changing the font a while back (before
upgrading to Jaunty) because it was barely readable.  I guess the issue
is with Tk 8.5.6-3.  Just found I can move the cursor (by left clicking)
if I hold the control key down.  Shift arrow keys works for selection.
Still not so good.  Cheers.

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


Re: Converting Python code to C/C++

2009-06-24 Thread bobicanprogram
On Jun 23, 11:49 am, Kurt Smith  wrote:
> On Mon, Jun 22, 2009 at 9:49 PM, Andras
>
>
>
> Pikler wrote:
> > Hi!
>
> > Short: I need to turn a Python program that I (mostly) wrote into C code,
> > and I am at a loss.
>
> > Long: I’m doing research/programming for a professor, and we are working
> > with MIDI files (a type of simple music file). The research deals with
> > generating variations from a musical melody; currently, my Python code uses
> > a Python midi package I found online to read the notes in question from a
> > midi file, about 350 lines of my own code to generate a variation based on
> > these notes and the professor’s algorithms, and finally the package again to
> > write the new melody to another midi file.
>
> > Now, my professor would like to have this exact code in C/C++, as she
> > believes C is more compatible with MATLAB, and wants the code to be
> > available in multiple languages in case a programmer works for her in the
> > future who knows C but not Python. While I know a tiny bit of C (emphasis on
> > the tiny), I would much prefer if there were some sort of automatic compiler
> > I could use to turn my Python code into C than taking a week or two or three
> > to learn the minimum I need about C, find a way to access MIDI files in it,
> > and rewrite all of my code.
>
> > After some googling, I found and tried Shedskin, but it doesn’t work, as the
> > Python midi package I’m using uses modules which Shedskin does not support.
> > Otherwise, I haven’t found much. Is there anything out there to help me do
> > this? If not, from anyone who has experience in this regard, how daunting
> > should I expect this to be?
>
> Taking on C from a cold start and being able to handle the ins and
> outs of interfacing with Python isn't something that's feasible in
> 'two or three weeks'.  Here are a couple of options -- take 'em or
> leave 'em:
>
> 1) Put the code in Cython:http://www.cython.org/ (full disclosure:
> I'm doing a GSoC project with Cython).  It will convert pretty much
> any python code into C code (even closures are supported in the most
> recent version, I think), and the C code can then be compiled into an
> extension module.
>
> The only problem with the above is the C code isn't, at first blush,
> easy to read.  Nor is it supposed to be changed by the user.  So that
> leads us to option...
>
> 2) Write the core functionality in C yourself, and then wrap those C
> functions in Cython.  You'll want to take a look at the documentation:
>
> http://docs.cython.org/
>
> and, more specifically on wrapping C code:
>
> http://docs.cython.org/docs/external_C_code.html
>
> I don't think you'll be able to avoid learning C, though.
>
> Kurt


3) use Python-SIMPL to connect your C module to your Python module
using a 5 function API without any need for wrappers.  ie. have your
cake and eat it too

http://www.icanprogram.com/06py/main.html

bob

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


Re: Converting Python code to C/C++

2009-06-24 Thread Scott David Daniels

Couper, Tim T wrote:

... My experience is that developers who know C and C++ can be productive
in less than 1 week in python, and find it liberating, and educational, to
do so. And at the same time they will have added a second language to
their toolbox. As Kurt points out, learning C/C++ takes considerably
longer (weeks/months to attain a level of competence). 


Yup.  Remember that "be productive" is not quite the same as "master."
The nice thing is that the mastery comes on a gentle slope, adding to
your productivity without requiring drastic rethinking of all you
understood (as is done to physics students, for example).


Python is now used in a number of universities as the language in which
to teach comp sci undergraduate courses (I know of Leeds, & MIT),
biomathematics, and my daughter just finished her PhD in speech and
language processing at Edinburgh .. using python and Matplotlib .. as
the extensive C/C++ libraries in that infomatics world are wrapped in
python - and the MSc Comp Sci course has replaced Java as the language
for teaching with Python.


As a data point, Georgia Tech (I believe) had a two-semester Computer
Science intro course in C++.  In introducing a Python intro course, they
provided for a few years both the Python and the C++ first semester,
and kept the C++ second semester.  They found no measurable difference
in the performance on the second course (still in C++) even though the
Python course people had to learn a new language in addition to learning
the rest of the coursework.  The first course is now in Python, since
at the end of the two-semester sequence they know two languages and 
apparently suffer no compensating loss.


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Why is it that str.replace doesn't work sometimes?

2009-06-24 Thread humn
I'm writing a script to convert Latex commands to bbcode by using the
str.replace function and I'm confused as to why this works:

if '\chapter' in line:
line = line.replace('\chapter{', '[b][u]')
line = line.replace('}', '[/b][/u]')

but this doesn't:

if '\title' in line:
line = line.replace('\title{', '[size=150][b]')
line = line.replace('}', '[/b][/size]')

Here is the short version of the script:

infile = open('test.tex')

outfilename = infile.name.partition('.')[0] + '.bbcode'
outfile = open(outfilename, 'w')

for line in infile:

if '\title' in line:
line = line.replace('\title{', '[size=150][b]')
line = line.replace('}', '[/b][/size]\n')

if '\chapter' in line:
line = line.replace('\chapter{', '[b][u]')
line = line.replace('}', '[/u][/b]')

outfile.write(line)

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


Get name of class without instance

2009-06-24 Thread Bryan
Given a class:

class Foo(object):
pass

How can I get the name "Foo" without having an instance of the class?

str(Foo) gives me more than just the name Foo.   "__main__.Account"
Foo.__class__.__name__ gives me "type"

I don't want to do:
Foo().__class__.__name__ if possible.  I would rather avoid the
constructor.  I just want to get a string "Foo"

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


Re: Dictionary self lookup

2009-06-24 Thread Scott David Daniels

Norberto Lopes wrote:

On Jun 24, 1:21 pm, "Diez B. Roggisch"  wrote:

Norberto Lopes wrote: ...

config = {"home" : "/home/test"}
config["user1"] = config["home"] + "/user1"
config["user2"] = config["home"] + "/user2"
config["python-dev"] = config["user1"] + "/py-dev"


I'd write this as:
   home = "/home/test"
   config = {"home" : home, "user1" : home + "/user1",
 "user2" : home + "/user2", "python-dev" : home + "/py-dev"}

or even (if the list gets much longer):

   home = "/home/test"
   config = {"home" : "", "user1" : "/user1", "user2" : "/user2",
 "python-dev" : "/py-dev"}
   for key, entry in config.iteritems():
   config[key] = home + entry

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a large csv file

2009-06-24 Thread skip

Mag> s=0

Mag> #Takes the longest here
Mag> for y in fs:
Mag>  continue
Mag>   a=y.split(',')
Mag>   s=s+1
Mag>   dset.resize(s,axis=0)
Mag> fs.close()

Mag> f.close()

Mag> This works but just takes a VERY long time.

Mag> Any way to optimize this?

I sort of suspect you're missing something there.  Is there nothing between
the for loop and the overly indented continue statement?

At any rate, try using the csv module to read in your records:

import csv

reader = csv.reader(fs)
...

for s, row in enumerate(reader):
dset.resize(s, axis=0)

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
when i wake up with a heart rate below 40, i head right for the espresso
machine. -- chaos @ forums.usms.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A superclass using a child classes' methods

2009-06-24 Thread Jean-Michel Pichavant

Kurt Schwehr wrote:

I'm trying to build an OO system for encoding and decoding
datapackets.  I'd like the parent class to have an encode function
that uses each of the child classes' packing methods.  It appears that
this works for attributes of children accessed by the parent, but not
for methods.

hell no, this works for methods as well.

  Is that right?  For attributes I found this example,
where the alphabet attribute is set in the child, but used in the
parent.

http://www.pasteur.fr/formation/infobio/python/ch19s04.html

Should I just set an attribute in the child class and then call the
super's functionality making is pull the data from the attribute?

Thanks,
-kurt
  

class Parent:
   def foo(self):
  raise NotImplementedError() # virtual method, it has to be 
overriden by childs


   def bar(self):
  self.foo()

class Son(Parent):
   def foo(self):
  print "I'm your son"

class Daughter(Parent):
   def foo(self):
  print "I'm your daughter"

Son().bar()
"I'm your son"

Declaring the foo method at the Parent level is not required. But it's a 
good practice: explicit > implicit and it helps to write proper 
documentation.


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


Re: Get name of class without instance

2009-06-24 Thread Jean-Michel Pichavant

Bryan wrote:

Given a class:

class Foo(object):
pass

How can I get the name "Foo" without having an instance of the class?

str(Foo) gives me more than just the name Foo.   "__main__.Account"
Foo.__class__.__name__ gives me "type"

I don't want to do:
Foo().__class__.__name__ if possible.  I would rather avoid the
constructor.  I just want to get a string "Foo"

  

>>> Foo.__name__
'Foo'

8-)

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


Unable to get Tkinter menubar to appear under OS X

2009-06-24 Thread Eric Winter
Hi all. I've googled this issue several times and come up dry. Here's
the situation:

I have a X-windows build of Tkinter for Python built on an OS X
machine (10.4 or 10.5, same issue). This is not the Aqua version of
Tk, but Tk built from source using X-Window support. I also use a from-
source build of Python, not the system Python. I don't like this
arrangement, but project requirements (allegedly) dictate this
approach.

When I run any application using that copy of Tkinter and that copy of
Python, everything seems to work fine except menus - the code which
creates the menus runs, but no menus appear, either in the window or
at the top of the screen.

Am I required to use the Aqua version of Tk on OS X? If not, do I need
to do something special on OS X when I built Tk and/or Python? Any
hints here would be greatly appreciated.

Thanks,
Eric Winter
Fermi Science Support Center
NASA Goddard Space Flight Center
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get name of class without instance

2009-06-24 Thread Tim Golden

Bryan wrote:

Given a class:

class Foo(object):
pass

How can I get the name "Foo" without having an instance of the class?

str(Foo) gives me more than just the name Foo.   "__main__.Account"
Foo.__class__.__name__ gives me "type"

I don't want to do:
Foo().__class__.__name__ if possible.  I would rather avoid the
constructor.  I just want to get a string "Foo"



You are going to kick yourself:

class Foo (object): pass

print Foo.__name__


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


Re: Why is it that str.replace doesn't work sometimes?

2009-06-24 Thread unayok
On Jun 24, 12:11 pm, humn  wrote:
> but this doesn't:
>
> if '\title' in line:
>         line = line.replace('\title{', '[size=150][b]')
>         line = line.replace('}', '[/b][/size]')

\t is an escaped  character. so, '\title' will look for
'itle'

Two ways to fix this:

1. use r'\title'

2. use '\\title'

\c does not represent a known escape sequence so it remains two
characters.

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


Re: Get name of class without instance

2009-06-24 Thread Bryan
On Jun 24, 9:25 am, Tim Golden  wrote:
> Bryan wrote:
> > Given a class:
>
> > class Foo(object):
> >     pass
>
> > How can I get the name "Foo" without having an instance of the class?
>
> > str(Foo) gives me more than just the name Foo.   "__main__.Account"
> > Foo.__class__.__name__ gives me "type"
>
> > I don't want to do:
> > Foo().__class__.__name__ if possible.  I would rather avoid the
> > constructor.  I just want to get a string "Foo"
>
> You are going to kick yourself:
>
> class Foo (object): pass
>
> print Foo.__name__
>
> TJG

Whoops.

How come dir(Foo) does not show __name__?  That is how I was
investigating the possibilities.

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


Re: fileinput.input, readlines and ...

2009-06-24 Thread Scott David Daniels

Peter Otten wrote:

...
If you need more than a few name value pairs it pays to put the data in a 
dictionary first:


# assuming that values always consist of a single line
with open(filename) as instream:
lines = (line.strip() for line in lines)
lookup =  dict(zip(lines, lines))
print lookup["Data2"]
print lookup["Data3"]


Little bit of a fluff-up here.  Perhaps something like:

with open(filename) as instream:
lines = (line.strip() for line in instream)
lookup = dict(zip(lines[::2], lines[1::2]))

The other way to do it is:

lookup = {}
with open(filename) as instream:
gen = (line.strip() for line in instream)
for key in gen:
lookup[key] = next(gen)

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get name of class without instance

2009-06-24 Thread J. Cliff Dyer
On Wed, 2009-06-24 at 09:17 -0700, Bryan wrote:
> Given a class:
> 
> class Foo(object):
> pass
> 
> How can I get the name "Foo" without having an instance of the class?
> 
> str(Foo) gives me more than just the name Foo.   "__main__.Account"
> Foo.__class__.__name__ gives me "type"
> 
> I don't want to do:
> Foo().__class__.__name__ if possible.  I would rather avoid the
> constructor.  I just want to get a string "Foo"
> 

I'll give you a hint:

>>> Foo().__class__ is Foo
True


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


Re: A superclass using a child classes' methods

2009-06-24 Thread Kurt Schwehr
Jean-Michel,

Thanks for the excellent response setting me straight.  Now to figure
out what dumb thing I did to make my code not work...

-kurt

On Jun 24, 12:23 pm, Jean-Michel Pichavant 
wrote:
> Kurt Schwehr wrote:
> > I'm trying to build an OO system for encoding and decoding
> > datapackets.  I'd like the parent class to have an encode function
> > that uses each of the child classes' packing methods.  It appears that
> > this works for attributes of children accessed by the parent, but not
> > for methods.
>

[clear example of it working]

>
> Declaring the foo method at the Parent level is not required. But it's a
> good practice: explicit > implicit and it helps to write proper
> documentation.
>
> Jean-Michel

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


Re: Why is it that str.replace doesn't work sometimes?

2009-06-24 Thread Ken Dyck
On Jun 24, 12:11 pm, humn  wrote:
> I'm confused as to why this works:
>
> if '\chapter' in line:
>         line = line.replace('\chapter{', '[b][u]')
>         line = line.replace('}', '[/b][/u]')
>
> but this doesn't:
>
> if '\title' in line:
>         line = line.replace('\title{', '[size=150][b]')
>         line = line.replace('}', '[/b][/size]')

In string literals---whether they use single or double quotes---
backslashes are used as escape characters to denote special
characters. The '\t' in '\title' is interpreted as the tab character
so the string that your code is trying to find and replace is actually
'itle'. There isn't any special meaning for '\c', so python
interprets that to mean a backslash followed by the character 'c',
which is why the first case works.

There are two ways to solve the problem:

1. Prefix the string literal with an 'r', indicating that backslashes
should not be treated as escape characters (eg. r'\title'), or
2. Use a double backslash in the string literal to indicate that you
mean a literal backslash, not an escape character (eg. '\\title')

The official documentation, including a list of the special escape
sequences, is here:
http://docs.python.org/reference/lexical_analysis.html#string-literals

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


Re: Why is it that str.replace doesn't work sometimes?

2009-06-24 Thread humn
On Jun 24, 12:28 pm, unayok  wrote:
> On Jun 24, 12:11 pm, humn  wrote:
>
> > but this doesn't:
>
> > if '\title' in line:
> >         line = line.replace('\title{', '[size=150][b]')
> >         line = line.replace('}', '[/b][/size]')
>
> \t is an escaped  character. so, '\title' will look for
> 'itle'
>
> Two ways to fix this:
>
> 1. use r'\title'
>
> 2. use '\\title'
>
> \c does not represent a known escape sequence so it remains two
> characters.

Thank you! Didn't know that it would escape characters with single
quotes. I thought it only did that with double quotes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get name of class without instance

2009-06-24 Thread David Stanek
Try Foo.__name__ if Foo is a class object.

On 6/24/09, Bryan  wrote:
> Given a class:
>
> class Foo(object):
> pass
>
> How can I get the name "Foo" without having an instance of the class?
>
> str(Foo) gives me more than just the name Foo.   "__main__.Account"
> Foo.__class__.__name__ gives me "type"
>
> I don't want to do:
> Foo().__class__.__name__ if possible.  I would rather avoid the
> constructor.  I just want to get a string "Foo"
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
Sent from my mobile device

David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading then sending new parts of a log file

2009-06-24 Thread Scott David Daniels

Chuck Connors wrote:

Hey guys.  I'm trying to work up a little program that will send any
new lines written to a file (log file from my home automation
software) to me via instant message.  I've gotten the instant message
sending part figured out using xmpppy.

I've done a few things with Python in the past but I am in no means
more than a beginner/hacker.  Can someone tell me what commands/
modules/etc exist for monitoring and parsing a file for new
information that I can then send to my IM sending function?  I am not
asking for anyone to write the code but merely a push in the right
direction.

Thanks!

What OS and version, what Python and version.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is it that str.replace doesn't work sometimes?

2009-06-24 Thread MRAB

humn wrote:

On Jun 24, 12:28 pm, unayok  wrote:

On Jun 24, 12:11 pm, humn  wrote:


but this doesn't:
if '\title' in line:
line = line.replace('\title{', '[size=150][b]')
line = line.replace('}', '[/b][/size]')

\t is an escaped  character. so, '\title' will look for
'itle'

Two ways to fix this:

1. use r'\title'

2. use '\\title'

\c does not represent a known escape sequence so it remains two
characters.


Thank you! Didn't know that it would escape characters with single
quotes. I thought it only did that with double quotes.


There's no difference between the two types of quote character. Python
itself prefers to show ' when printing, unless " would be clearer:

>>> # The empty string.
>>> ''
''
>>> ""
''
>>> # Quoting the other type.
>>> '"'
'"'
>>> "'"
"'"
>>> # Quoting the same type.
>>> '\''
"'"
>>> "\""
'"'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to enumerate classes in a module

2009-06-24 Thread Terry Reedy

Дамјан Георгиевски wrote:
I need to programmaticaly enumerate all the classes in a given module. 
Currently I'm using dir(module) but the Notice on the documentation page 
[1]  says "dir() is supplied primarily as a convenience for use at an 
interactive prompt" so that kind of scares me.


That notice primarily refers to the fact that the special names (of 
__xxx__ form) returned are implementation and version dependent, and may 
not be complete in the sense that dir(ob) may not return __xyz__ even 
though ob.__xyz__ exists and can be retrieved.


If you are only interested in regular-name attribute of ob, let your 
fear fly away.


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


Re: Measuring Fractal Dimension ?

2009-06-24 Thread pdpi
On Jun 24, 1:32 pm, Mark Dickinson  wrote:
> On Jun 24, 10:12 am, pdpi  wrote:
>
> > Regarding inf ** 0, why does IEEE745 define it as 1, when there is a
> > perfectly fine NaN value?
>
> Other links:  the IEEE 754 revision working group mailing list
> archives are public;  there was extensive discussion about
> special values of pow and similar functions.  Here's a relevant
> Google search:
>
> http://www.google.com/search?q=site:grouper.ieee.org++pow+annex+D
>
> The C99 rationale document has some explanations for the
> choices for special values in Annex F.  Look at pages 179--182
> in:
>
> http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf
>
> Note that the original IEEE 754-1985 didn't give specifications
> for pow and other transcendental functions;  so a complete
> specification for pow appeared in the C99 standard before it
> appeared in the current IEEE standard, IEEE 754-2008.  Thus
> C99 Annex F probably had at least some small influence on the
> choices made for IEEE 754-2008 (and in turn, IEEE 754-1985
> heavily influenced C99 Annex F).
>
> My own take on all this, briefly:
>
>  - floating-point numbers are not real numbers, so mathematics
>    can only take you so far in deciding what the 'right' values
>    are for special cases;  pragmatics has to play a role too.
>
>  - there's general consensus in the numerical and mathematical
>    community that it's useful to define pow(0.0, 0.0) to be 1.
>
>  - once you've decided to define pow(0.0, 0.0) to be 1.0, it's
>    easy to justify taking pow(inf, 0.0) to be 1.0:  the same
>    limiting arguments can be used as justification;  or one can
>    use reflection formulae like pow(1/x, y) = 1/pow(x, y), or...
>
>  - one piece of general philosophy used for C99 and IEEE 754
>    seems to have been that NaN results should be avoided
>    when it's possible to give a meaningful non-nan value instead.
>
>  - part of the reason that pow is particularly controversial
>    is that it's really trying to be two different functions
>    at once:  it's trying to be both a generalization of the
>    `analytic' power function x**y = exp(y*log(x)), for
>    real y and positive real x, and in this context one can
>    make a good argument that 0**0 should be undefined; but
>    at the same time it's also used in contexts where y is
>    naturally thought of as an integer; and in the latter
>    context bad things happen if you don't define pow(0, 0)
>    to be 1.
>
> I really should get back to work now.
>
> Mark

Thanks for the engrossing read (and damn you for making me waste
valuable work hours). After perusing both C99 and the previous
presentation on IEEE754, I find myself unconvinced regarding the
special cases. It just stinks of bug-proneness, and I fail to see how
assuming common values for exceptional cases relieves you from testing
for those special cases and getting them behaving right (in an
application-specific way) just the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: isinstance(obj, type(obj)) == True?

2009-06-24 Thread Chris Rebert
On Wed, Jun 24, 2009 at 7:57 AM, Art wrote:
> I have the following problem:
>
> ipdb> p type(self)
> 
>
> ipdb> isinstance(self, component.BiasComponent)
> False
>
> I thought that isinstance(obj, type(obj)) == True.
>
> The specific problem is when I try to call the super of a class and it
> only occurs after 'reload'ing the file in the interpreter. What am I
> messing up by reloading? It doesn't occur if I using for the first
> time in a fresh interpreter session.
>
> ---> 32 class BiasComponent(ModelComponent):
>      33     def __init__(self, g, model):
>      34         super(BiasComponent, self).__init__(g, model)
>
> TypeError: super(type, obj): obj must be an instance or subtype of
> type
>
> Seems like the self passed to __init__ is messed up in some way.

I would guess you're running into one of the caveats of using
reload(); see http://docs.python.org/library/functions.html#reload

Printing out id(BiasComponent) and id(type(obj)) both before and after
the reload() call should be instructive.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reply to OT diversion (was: What is the best method to match a pattern in set of lines

2009-06-24 Thread Ross Ridge
a...@pythoncraft.com (Aahz) writes:
> Guess what?  Prior to DejaNews, discussions on Usenet *were* ephemeral,
> and it all worked.

Not really, Usenet was archived before DejaNews arrived on the scene.
I can find plenty of my posts from before then.  Regardless, Usenet
works better now that searchable archives are available on the WWW.

Dennis Lee Bieber   wrote:
>   If there were an "X-no-google" option I'd switch... I have no real
>concerns about archives /accessed via NNTP through some paid-traceable
>account/... But look at how much effort Google has to go through in the
>attempt of obliterating email addresses in the attempt at minimizing
>collection of such by spammers...

Uh... this makes no sense.  X-No-Archive does nothing to prevent spammers
from harvesting your e-mail address.  Your current posts are available
to spammers for free on NNTP and WWW servers all over the 'net with or
without the header.  At least Google does try to hide your e-mail address,
other WWW sites don't bother:


http://www.rhinocerus.net/forum/lang-python/571842-re-pyserial-question.html

You'd be more protected from spammers with an X-Google-Only option.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Python code to C/C++

2009-06-24 Thread Terry Reedy


Short: I need to turn a Python program that I (mostly) wrote into C 
code, and I am at a loss.


Now, my professor would like to have this exact code in C/C++, as she 
believes C is more compatible with MATLAB, and wants the code to be 
available in multiple languages in case a programmer works for her in 
the future who knows C but not Python. While I know a tiny bit of C 
(emphasis on the tiny),


Your professor should wait until your Python version is complete and in 
final form and until a C version is needed. Then hire someone competent 
in both languages to do the translation.


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


Re: IMPORTANT: I NEED TO HELP WITH ONE OF THE CORE DEVELOPERS

2009-06-24 Thread Chris Rebert
On Wed, Jun 24, 2009 at 6:22 AM, Pegasus wrote:
> I need help with an implementation of your
> interpreter under PSPE/PSP.
>
> I need to know something about the C
> functions that are recalled by the interpreter
> when it executes a .pyc file.
>
> Our version of ndPython is very slow in
> execution respect to Carlos's StackLess
> Python (another product for PSP).
>
> We believe that the trouble is in a routine
> of our Nanodesktop libc that can be
> a bottleneck. But we don't know
> which can be the interested routine
> (string ? memory allocation ?)
>
>
> Please, help us. The product is complete,
> but we cannot release cause this problem.
>
> Thank you in advance.
> Filippo Battaglia

In the future, also NOTE THAT SHOUTING TYPICALLY DOES NOT EARN ONE SYMPATHY.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fileinput.input, readlines and ...

2009-06-24 Thread Peter Otten
Scott David Daniels wrote:

> Peter Otten wrote:

>> with open(filename) as instream:
>> lines = (line.strip() for line in lines)
>> lookup =  dict(zip(lines, lines))

> Little bit of a fluff-up here.  

Sorry, it should have been

with open(filename) as instream:
lines = (line.strip() for line in instream)
lookup =  dict(zip(lines, lines))

> Perhaps something like:
> 
>  with open(filename) as instream:
>  lines = (line.strip() for line in instream)
>  lookup = dict(zip(lines[::2], lines[1::2]))

Tu quoque ;)

Peter

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


urllib2.urlopen issue

2009-06-24 Thread David
hello,

I have a url that is "http://query.directrdr.com/ptrack?
pid=225&v_url=http://
www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said".
If I open it on a browser, I can get its contents without any
problem.
However, if I use following code,


import urllib2


url = 'http://query.directrdr.com/ptrack?pid=225&v_url=http://
www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said'


xml = urllib2.urlopen(url).read()


then I get an exception of


 File "/usr/lib/python2.5/urllib2.py", line 1082, in do_open
raise URLError(err)
urllib2.URLError: 


I think this is caused by the embedded "v_url=..." in the url.
Anybody
knows how to fix this? By the way, this code works well if I change
the value of url to something like "www.yahoo.com" or
"www.google.com".


Thanks so much.


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


Re: Dictionary self lookup

2009-06-24 Thread Norberto Lopes
On Jun 24, 6:26 pm, Scott David Daniels  wrote:
> Norberto Lopes wrote:
> > On Jun 24, 1:21 pm, "Diez B. Roggisch"  wrote:
> >> Norberto Lopes wrote: ...
> >>> config = {"home" : "/home/test"}
> >>> config["user1"] = config["home"] + "/user1"
> >>> config["user2"] = config["home"] + "/user2"
> >>> config["python-dev"] = config["user1"] + "/py-dev"
>
> I'd write this as:
>     home = "/home/test"
>     config = {"home" : home, "user1" : home + "/user1",
>               "user2" : home + "/user2", "python-dev" : home + "/py-dev"}
>
> or even (if the list gets much longer):
>
>     home = "/home/test"
>     config = {"home" : "", "user1" : "/user1", "user2" : "/user2",
>               "python-dev" : "/py-dev"}
>     for key, entry in config.iteritems():
>         config[key] = home + entry
>
> --Scott David Daniels
> scott.dani...@acm.org

Yeah, there are a lot of options. That was just an example. Btw, I had
"python-dev" depending on "user1" and "user1" depending on "home"
precisely so that the way you suggested would get complicated. Yours
examples fail in the python-dev key-value. You'd need an "extra"
step ;)

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


talk of concurrency by Anders Hejlsberg and Guy Steele

2009-06-24 Thread Xah Lee
of recent talks about concurrency, this video interview would be of
interest:

http://channel9.msdn.com/posts/Charles/Anders-Hejlsberg-and-Guy-Steele-Concurrency-and-Language-Design/

Anders Hejlsberg and Guy Steele: Concurrency and Language Design
Posted By: Charles | Oct 6th, 2008 @ 6:27 AM | 75,079 Views | 19
Comments

  Xah
∑ http://xahlee.org/

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


Re: urllib2.urlopen issue

2009-06-24 Thread Aahz
In article <854313cf-6323-4ca9-b883-65ca8f414...@v23g2000pro.googlegroups.com>,
David   wrote:
>
>import urllib2
>url = 'http://query.directrdr.com/ptrack?pid=225&v_url=http://
>www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said'
>xml = urllib2.urlopen(url).read()
>
>then I get an exception of
>
> File "/usr/lib/python2.5/urllib2.py", line 1082, in do_open
>raise URLError(err)
>urllib2.URLError: 
>
>I think this is caused by the embedded "v_url=..." in the url.

urllib.quote_plus()
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2.urlopen issue

2009-06-24 Thread Chris Rebert
On Wed, Jun 24, 2009 at 10:50 AM, David wrote:
> hello,
>
> I have a url that is "http://query.directrdr.com/ptrack?
> pid=225&v_url=http://
> www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said".
> If I open it on a browser, I can get its contents without any
> problem.
> However, if I use following code,
>
>
> import urllib2
>
>
> url = 'http://query.directrdr.com/ptrack?pid=225&v_url=http://
> www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said'
>
>
> xml = urllib2.urlopen(url).read()
>
>
> then I get an exception of
>
>
>  File "/usr/lib/python2.5/urllib2.py", line 1082, in do_open
>    raise URLError(err)
> urllib2.URLError: 

Unable to reproduce with either urllib or urllib2's urlopen(). I get
some XML back without error both ways. Using Python 2.6.2 on Mac OS X.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: isinstance(obj, type(obj)) == True?

2009-06-24 Thread Terry Reedy

Art wrote:

I have the following problem:

ipdb> p type(self)


ipdb> isinstance(self, component.BiasComponent)
False

I thought that isinstance(obj, type(obj)) == True.


Yes, but that is not what you entered ;-).
The name 'component.BiasComponent' is not bound to type(self),
but to another object, probably with the same .__name__ attribute.


The specific problem is when I try to call the super of a class and it
only occurs after 'reload'ing the file in the interpreter. What am I
messing up by reloading?


The relationship between namespace names and definition names. My guess 
is that you have two class objects with the same definition name. This 
happens when you reload the code for a class and have instances that 
keep the original class object alive. This sort of problem is why reload 
was *removed* from Py3. It did not work the way people wanted it to and 
expected it to. I recommend not to use it.


> It doesn't occur if I using for the first

time in a fresh interpreter session.


Starting fresh is the right thing to do. IDLE has a 'Restart Shell' 
command for this reason. It automatically restarts when you run a file. 
You have already wasted more time with reload than most people would 
ever save in a lifetime of using reload, even if it worked as expected.


Terry Jan Reedy

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


Re: Converting Python code to C/C++

2009-06-24 Thread Grant Edwards
On 2009-06-24, Terry Reedy  wrote:

> Your professor should wait until your Python version is complete and in 
> final form and until a C version is needed. Then hire someone competent 
> in both languages to do the translation.

Professor...  hire...

Good one!  :)

-- 
Grant Edwards   grante Yow! BARRY ... That was
  at   the most HEART-WARMING
   visi.comrendition of "I DID IT MY
   WAY" I've ever heard!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Matplotlib - an odd problem

2009-06-24 Thread koranthala
Hi,
I am using Matplotlib with Django to display charts on the web page.
I am facing an odd problem in that, everytime I do a refresh on the
web page, the image darkens - and the text becomes little unreadable.
5/6 refreshes later, the text becomes completely unreadable.
Since I am using Django test server, the same process is being used.
i.e. every refresh does not create a new process. When I tried killing
the process, the image again cleared.
So I think it is sort of memory leak or a saved value which is messing
up something.
But I cannot seem to find the issue at all.

The code is as follows -

import pylab
from cStringIO import StringIO

def print_pie_chart(request):
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
data = [15,30,45, 10]
pylab.figure(1, figsize=(2,2))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data, explode=None, labels=labels, autopct='%1.1f%%',
shadow=True)
out = StringIO()
pylab.savefig(out, format="PNG")
out.seek(0)
response = HttpResponse()
response['Content-Type'] = 'image/png'
response.write(out.read())
return response

Can anyone help me out here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get name of class without instance

2009-06-24 Thread Terry Reedy

Bryan wrote:


How come dir(Foo) does not show __name__?  That is how I was
investigating the possibilities.


Interesting question. Seems like an oversight. dir(some_module) and 
dir(some_function) include '__name__'. I suggest you search the tracker 
for existing issues on this subject and add a feature request if there 
is none.



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


Re: Reading then sending new parts of a log file

2009-06-24 Thread Chuck Connors
On Jun 24, 11:57 am, Scott David Daniels 
wrote:
> What OS and version, what Python and version.

Win XP, Python 2.6.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2.urlopen issue

2009-06-24 Thread David
On Jun 24, 11:27 am, Chris Rebert  wrote:
> On Wed, Jun 24, 2009 at 10:50 AM, David wrote:
> > hello,
>
> > I have a url that is "http://query.directrdr.com/ptrack?
> > pid=225&v_url=http://
> >www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said".
> > If I open it on a browser, I can get its contents without any
> > problem.
> > However, if I use following code,
>
> > import urllib2
>
> > url = 'http://query.directrdr.com/ptrack?pid=225&v_url=http://
> >www.plentyoffish.com&keyword=flowers&feed=1&ip=12.2.2.2&said=$said'
>
> > xml = urllib2.urlopen(url).read()
>
> > then I get an exception of
>
> >  File "/usr/lib/python2.5/urllib2.py", line 1082, in do_open
> >    raise URLError(err)
> > urllib2.URLError: 
>
> Unable to reproduce with either urllib or urllib2's urlopen(). I get
> some XML back without error both ways. Using Python 2.6.2 on Mac OS X.
>
> Cheers,
> Chris
> --http://blog.rebertia.com- Hide quoted text -
>
> - Show quoted text -

Thanks Aahz. And thanks Chris. The XML content is what I am looking
for. I use Python 2.5. Maybe I should update to 2.6.2? Python version
problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading then sending new parts of a log file

2009-06-24 Thread unayok
On Jun 24, 10:23 am, Chuck Connors  wrote:
> Hey guys.  I'm trying to work up a little program that will send any
> new lines written to a file (log file from my home automation
> software) to me via instant message.  I've gotten the instant message
> sending part figured out using xmpppy.
>
> I've done a few things with Python in the past but I am in no means
> more than a beginner/hacker.  Can someone tell me what commands/
> modules/etc exist for monitoring and parsing a file for new
> information that I can then send to my IM sending function?  I am not
> asking for anyone to write the code but merely a push in the right
> direction.

Here's a little nudge: http://code.activestate.com/recipes/157035/

In place of its "print" line, you'd make your call into your existing
code to send the message.

Some of the comments offer some improvements on it (always read the
comments on the recipes), but this is likely the direction you will
want to head.

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


It's ...

2009-06-24 Thread Angus Rodgers

... my first Python program!  So please be gentle (no fifty ton
weights on the head!), but tell me if it's properly "Pythonic",
or if it's a dead parrot (and if the latter, how to revive it).

I'm working from Beazley's /Python: Essential Reference/ (2nd
ed. 2001), so my first newbie question is how best to find out
what's changed from version 2.1 to version 2.5. (I've recently
installed 2.5.4 on my creaky old Win98SE system.) I expect to 
be buying the 4th edition when it comes out, which will be soon,
but before then, is there a quick online way to find this out?

Having only got up to page 84 - where we can actually start to
read stuff from the hard disk - I'm emboldened to try to learn
to do something useful, such as removing all those annoying hard
tab characters from my many old text files (before I cottoned on
to using soft tabs in my text editor).

This sort of thing seems to work, in the interpreter (for an 
ASCII text file, named 'h071.txt', in the current directory):

stop = 3   # Tab stops every 3 characters
from types import StringType   # Is this awkwardness necessary?
detab = lambda s : StringType.expandtabs(s, stop)  # Or use def
f = open('h071.txt')   # Do some stuff to f, perhaps, and then:
f.seek(0)
print ''.join(map(detab, f.xreadlines()))
f.close()

Obviously, to turn this into a generally useful program, I need
to learn to write to a new file, and how to parcel up the Python
code, and write a script to apply the "detab" function to all the
files found by searching a Windows directory, and replace the old
files with the new ones; but, for the guts of the program, is this
a reasonable way to write the code to strip tabs from a text file?

For writing the output file, this seems to work in the interpreter:

g = open('temp.txt', 'w')
g.writelines(map(detab, f.xreadlines()))
g.close()

In practice, does this avoid creating the whole string in memory
at one time, as is done by using ''.join()? (I'll have to read up
on "opaque sequence objects", which have only been mentioned once
or twice in passing - another instance perhaps being an xrange()?)
Not that that matters much in practice (in this simple case), but
it seems elegant to avoid creating the whole output file at once.

OK, I'm just getting my feet wet, and I'll try not to ask too many
silly questions!

First impressions are: (1) Python seems both elegant and practical;
and (2) Beazley seems a pleasantly unfussy introduction for someone 
with at least a little programming experience in other languages.

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


Re: Reading a large csv file

2009-06-24 Thread Lie Ryan
Mag Gam wrote:
> Sorry for the delayed response. I was trying to figure this problem
> out. The OS is Linux, BTW

Maybe I'm just being pedantic, but saying your OS is Linux means little
as there are hundreds of variants (distros) of Linux. (Not to mention
that Linux is a kernel, not a full blown OS, and people in GNU will
insist to call Linux-based OS GNU/Linux)

> Here is some code I have:
> import numpy as np
> from numpy import *

Why are you importing numpy twice as np and as *?

> import gzip
> import h5py
> import re
> import sys, string, time, getopt
> import os
> 
> src=sys.argv[1]
> fs = gzip.open(src)
> x=src.split("/")
> filename=x[len(x)-1]
> 
> #Get /MM/DD format
> =(filename.rsplit(".",2)[0])[0:4]
> MM=(filename.rsplit(".",2)[0])[4:6]
> DD=(filename.rsplit(".",2)[0])[6:8]

> 
> f=h5py.File('/tmp/test_foo/FE.hdf5','w')

this particular line would make it impossible to have more than one
instance of the program open. May not be your concern...

> 
> grp="/"+
> try:
>   f.create_group(grp)
> except ValueError:
>   print "Year group already exists"
> 
> grp=grp+"/"+MM
> try:
>   f.create_group(grp)
> except ValueError:
>   print "Month group already exists"
> 
> grp=grp+"/"+DD
> try:
>   group=f.create_group(grp)
> except ValueError:
>   print "Day group already exists"
> 

> str_type=h5py.new_vlen(str)

> mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1',
> 'f4', 'f4')}
> print "Filename is: ",src
> fs = gzip.open(src)

> dset = f.create_dataset ('Foo',data=arr,compression='gzip')

What is `arr`?

> s=0
> 
> #Takes the longest here
> for y in fs:
>  continue
>   a=y.split(',')

>   s=s+1
>   dset.resize(s,axis=0)

You increment s by 1 for each iteration, would this copy the dataset? (I
never worked with h5py, so I don't know how it works)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fileinput.input, readlines and ...

2009-06-24 Thread Private Private
On Jun 24, 1:32 pm, Peter Otten <__pete...@web.de> wrote:
> Przemyslaw Bak wrote:
> > Hello,
>
> > I many files with log data. The structure of the file is quite
> > inconvenience and similar to the following example:
> > Data1
> >   ValueA
> > Data2
> >   ValueB
> > Data3
> >   ValueC
> > ...
> > To get the values I need to find Data* and then get to the next line.
> > I tried to use fileinput.input :
> > ...
> > for line in fileinput.input(filename):
> >     if line.find("Data2") >= 0:
> >         (now what ?)
>
> > So I can find the requested line (Data2) but how to get value from the
> > next line ?
>
> lines = fileinput.input(filename)
> for line in lines:
>     if "Data2" in line:
>         print line.strip(), "-->", next(lines).strip()

I get an error:

...
print line.strip(), "-->", next(lines).strip()
NameError: global name 'next' is not defined

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


Re: fileinput.input, readlines and ...

2009-06-24 Thread Scott David Daniels

Peter Otten wrote:

Scott David Daniels wrote:

Peter Otten wrote:

with open(filename) as instream:
lines = (line.strip() for line in lines)
lookup =  dict(zip(lines, lines))


Little bit of a fluff-up here.  


Sorry, it should have been

with open(filename) as instream:
lines = (line.strip() for line in instream)
lookup =  dict(zip(lines, lines))


Perhaps something like:

 with open(filename) as instream:
 lines = (line.strip() for line in instream)
 lookup = dict(zip(lines[::2], lines[1::2]))


Tu quoque ;)


You are exactly right (and my vocabulary expands a bit); I must go
wipe the egg off of my face now.  I still am thinking lists even
though I am writing generators.  I should have written:
with open(filename) as instream:
lines = [line.strip() for line in instream]
lookup = dict(zip(lines[::2], lines[1::2]))
But, your example does in fact work as written.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: It's ...

2009-06-24 Thread Angus Rodgers
On Wed, 24 Jun 2009 20:53:49 +0100, I wrote:

>[...] my first newbie question is how best to find out
>what's changed from version 2.1 to version 2.5.
>[...] is there a quick online way to find this out?

One way seems to be:





... although there doesn't seem to be any


... ah! ...

"What's New in Python 2.2"

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


Re: How to find info about python 3.x extension module availability?

2009-06-24 Thread Aahz
In article <2838671f-d582-4af1-b850-ccc18ff9d...@a36g2000yqc.googlegroups.com>,
Francesco Bochicchio   wrote:
>
>is there any site that reports the current porting (to Python 3.x)
>status of the main non-standard extension modules (such as pygtk,
>pywin32, wxpython, ...) ?

Feel free to create a wiki page on python.org...
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: It's ...

2009-06-24 Thread J. Cliff Dyer
On Wed, 2009-06-24 at 20:53 +0100, Angus Rodgers wrote:
> ... my first Python program!  So please be gentle (no fifty ton
> weights on the head!), but tell me if it's properly "Pythonic",
> or if it's a dead parrot (and if the latter, how to revive it).
> 

Yay.  Welcome to Python.


> I'm working from Beazley's /Python: Essential Reference/ (2nd
> ed. 2001), so my first newbie question is how best to find out
> what's changed from version 2.1 to version 2.5. (I've recently
> installed 2.5.4 on my creaky old Win98SE system.) I expect to 
> be buying the 4th edition when it comes out, which will be soon,
> but before then, is there a quick online way to find this out?
> 

Check here: http://docs.python.org/whatsnew/index.html

It's not designed to be newbie friendly, but it's in there.

> Having only got up to page 84 - where we can actually start to
> read stuff from the hard disk - I'm emboldened to try to learn
> to do something useful, such as removing all those annoying hard
> tab characters from my many old text files (before I cottoned on
> to using soft tabs in my text editor).
> 
> This sort of thing seems to work, in the interpreter (for an 
> ASCII text file, named 'h071.txt', in the current directory):
> 
> stop = 3   # Tab stops every 3 characters
> from types import StringType   # Is this awkwardness necessary?

Not anymore.  You can just use str for this.

> detab = lambda s : StringType.expandtabs(s, stop)  # Or use def

First, use def.  lambda is a rarity for use when you'd rather not assign
your function to a variable.  

Second, expandtabs is a method on string objects.  s is a string object,
so you can just use s.expandtabs(stop)

Third, I'd recommend passing your tabstops into detab with a default
argument, rather than defining it irrevocably in a global variable
(which is brittle and ugly)

def detab(s, stop=3):
#do stuff

Then you can do

three_space_version = detab(s)
eight_space_version = detab(s, 8)

> f = open('h071.txt')   # Do some stuff to f, perhaps, and then:
> f.seek(0)

f is not opened for writing, so if you do stuff to the contents of f,
you'll have to put the new version in a different variable, so f.seek(0)
doesn't help.  If you don't do stuff to it, then you're at the beginning
of the file anyway, so either way, you shouldn't need to f.seek(0).

> print ''.join(map(detab, f.xreadlines()))

Sometime in the history of python, files became iterable, which means
you can do the following:

for line in f:
print detab(line)

Much prettier than running through join/map shenanigans.  This is also
the place to modify the output before passing it to detab:

for line in f:
# do stuff to line
print detab(line)

Also note that you can iterate over a file several times:

f = open('foo.txt')
for line in f:
print line[0]  # prints the first character of every line
for line in f:
print line[1]  #prints the second character of every line
> f.close()
> 


> Obviously, to turn this into a generally useful program, I need
> to learn to write to a new file, and how to parcel up the Python
> code, and write a script to apply the "detab" function to all the
> files found by searching a Windows directory, and replace the old
> files with the new ones; but, for the guts of the program, is this
> a reasonable way to write the code to strip tabs from a text file?
> 
> For writing the output file, this seems to work in the interpreter:
> 
> g = open('temp.txt', 'w')
> g.writelines(map(detab, f.xreadlines()))
> g.close()
> 

Doesn't help, as map returns a list.  You can use itertools.imap, or you
can use a for loop, as above.

> In practice, does this avoid creating the whole string in memory
> at one time, as is done by using ''.join()? (I'll have to read up
> on "opaque sequence objects", which have only been mentioned once
> or twice in passing - another instance perhaps being an xrange()?)
> Not that that matters much in practice (in this simple case), but
> it seems elegant to avoid creating the whole output file at once.

The terms to look for, rather than opaque sequence objects are
"iterators" and "generators".

> 
> OK, I'm just getting my feet wet, and I'll try not to ask too many
> silly questions!
> 
> First impressions are: (1) Python seems both elegant and practical;
> and (2) Beazley seems a pleasantly unfussy introduction for someone 
> with at least a little programming experience in other languages.
> 

Glad you're enjoying Beazley.  I would look for something more
up-to-date.  Python's come a long way since 2.1.  I'd hate for you to
miss out on all the iterators, booleans, codecs, subprocess, yield,
unified int/longs, decorators, decimals, sets, context managers and
new-style classes that have come since then.


> -- 
> Angus Rodgers

Cheers,
Cliff


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


  1   2   >