Re: Reading XML namespaces

2010-05-16 Thread Stefan Behnel

Adam Tauno Williams, 16.05.2010 06:00:

Given that XML documents can be very large I'd rather avoid a parsing of
the document [beyond what lxml/etree] has already done] just to retrieve
the namespaces and their prefixes.


In order to find out which prefixes are used in the document and which set 
of namespace URIs each of them is mapped to, you need to traverse the 
entire document and aggregate all namespace definitions on all Elements. 
However, the result will be mostly useless, as a prefix is only meaningful 
within the scope of its definition. It doesn't have any sensible meaning 
for the entire document.


Stefan

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


Re: Reading XML namespaces

2010-05-16 Thread Stefan Behnel

Adam Tauno Williams, 15.05.2010 23:04:

On Sat, 2010-05-15 at 22:58 +0200, Stefan Behnel wrote:

Adam Tauno Williams, 15.05.2010 22:40:

On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:

Adam Tauno Williams, 15.05.2010 20:37:

Say I have an XML document that begins with:

http://www.dsml.org/DSML";>
How can one access the namespaces define in this node?  I've done a fair
amount of XML in Python, but haven't been able to uncover the call to
enumerate the namespaces.
Primarily I am using etree from lxml.

What do you need the namespaces for?

One needs to know the defined namespace in order to perform xpath
operations.

Well, yes, but unless you already know the namespace (URI), you can't know
what the tag you find signifies in the first place.
Unless, obviously, you are confusing namespaces with namespace prefixes.
But you don't need to know the prefixes for XPath.
Does this help?
http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes


I know that.


I just remembered that there's also this:

http://codespeak.net/lxml/FAQ.html#how-can-i-find-out-which-namespace-prefixes-are-used-in-a-document

Stefan

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


joining files

2010-05-16 Thread mannu jha
Hi,

I have few files like this:
file1:
22 110.1  
33 331.5 22.7 
5 271.9 17.2 33.4
4 55.1 

file1 has total 4 column but some of them are missing in few row.

file2:
5 H
22 0

file3:
4 T
5 B
22 C
121 S

in all these files first column is the main source of matching their entries. 
So What I want in the output is only those entries which is coming in all three 
files.
output required:
5 271.9 17.2 33.4 5 H  5 T
22 110.1 22 0 22 C




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


Re: Reading XML namespaces

2010-05-16 Thread Martin v. Loewis
> Well, there's an "nsmap" property on each Element that provides the
> mapping of prefixes to namespace URIs that form the scope of the
> Element. However, while this is what the OP asked for, it is not what
> the OP wants, simply because it doesn't solve the problem.

Well, it solves the problem at hand: he gets some prefix mapping.

He probably could have used a hard-coded prefix mapping for the 20 or so
namespaces in his application instead (with a different set of flaws in
that approach).

> That's why I asked for more details in order to understand what the
> actual problem is that the OP is trying to solve, because the approach
> that the OP is apparently trying to follow is clearly misguided.

I completely agree. However, I recommend that we let him find out on his
 own. I suspect he has some idiomatic usage of XML, perhaps with all
namespace prefixes defined in the root element. He'll find out that his
approach is flawed in the general case when he encounters such a case.
It's probably pointless trying to convince him in the abstract.

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


Re: Reading XML namespaces

2010-05-16 Thread Stefan Behnel

Martin v. Loewis, 16.05.2010 09:07:

the approach that the OP is apparently trying to follow is
clearly misguided.


I completely agree. However, I recommend that we let him find out on his
  own. I suspect he has some idiomatic usage of XML, perhaps with all
namespace prefixes defined in the root element. He'll find out that his
approach is flawed in the general case when he encounters such a case.
It's probably pointless trying to convince him in the abstract.


Probably, yes. It's just that I prefer it if broken code doesn't get 
written in the first place, rather than having to fix it later on, which in 
this case even seems to imply breaking a user visible feature. But you're 
right, let's leave the decision to the OP.


Stefan

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


Re: parsing XML

2010-05-16 Thread Jake b
Check out Amara: http://www.xml3k.org/Amara/QuickRef

It looks promising. For a pythonic solution over sax / dom.

>>> Iter(doc.team.player)
# or
>>> doc.team.player[0].name

[ new to the list, so I'm not sure why my previous response failed. Is
it on me? Because using iPod, vs thunderbird?

However, looking at superpollo, the reply-to didn't include
python-list. Or even a valid address ?

Message below. Ty.

On Saturday, May 15, 2010, Mail Delivery Subsystem
 wrote:
> Delivery to the following recipient failed permanently:
>
>      [email protected]
>
> Technical details of permanent failure:
> Google tried to deliver your message, but it was rejected by the recipient 
> domain. We recommend contacting the other email provider for further 
> information about the cause of this error. The error that the other server 
> returned was: 554 554 : Relay access denied (state 14).
>
> - Original message -
>
> MIME-Version: 1.0
> Received: by 10.91.208.24 with SMTP id k24mr18590agq.155.1273969257113; Sat,
>         15 May 2010 17:20:57 -0700 (PDT)
> Received: by 10.90.80.20 with HTTP; Sat, 15 May 2010 17:20:57 -0700 (PDT)
> In-Reply-To: <[email protected]>
> References: 
> 
>          <[email protected]>
> Date: Sat, 15 May 2010 19:20:57 -0500
> Message-ID: 
> Subject: Re: parsing XML
> From: Jake b 
> To: superpollo 
> Content-Type: text/plain; charset=ISO-8859-1
>
> Check out Amara: http://www.xml3k.org/Amara/QuickRef
> For a pythonic solution over sax / dom.
>>> Iter(doc.team.player)
> or
>>> doc.team.player[0].name
>
> --
> Jake
>

--
Jake

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


Re: joining files

2010-05-16 Thread James Mills
On Sun, May 16, 2010 at 5:02 PM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

This had better not be yet another assignment
you're asking us to help you with ? *sigh*

Break your problem down!

Since you haven't really asked a specific question
I can't give you a specific answer.

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


[ANN] Oktest 0.3.0 released - a new style testing library

2010-05-16 Thread kwatch
Hi,
I released Oktest 0.3.0.

http://packages.python.org/Oktest/
http://pypi.python.org/pypi/Oktest/


Overview


Oktest is a new-style testing library for Python.
::

from oktest import ok
ok (x) > 0 # same as assert_(x > 0)
ok (s) == 'foo'# same as assertEqual(s, 'foo')
ok (s) != 'foo'# same as assertNotEqual(s, 'foo')
ok (f).raises(ValueError)  # same as assertRaises(ValueError, f)
ok (u'foo').is_a(unicode)  # same as assert_(isinstance(u'foo',
unicode))
not_ok (u'foo').is_a(int)  # same as assert_(not
isinstance(u'foo', int))
ok ('A.txt').is_file() # same as
assert_(os.path.isfile('A.txt'))
not_ok ('A.txt').is_dir()  # same as assert_(not
os.path.isdir('A.txt'))

You can use ok() instead of 'assertXxx()' in unittest.

Oktest requires Python 2.3 or later. Oktest is ready for Python 3.

NOTICE!! Oktest is a young project and specification may change in the
future.

See http://packages.python.org/Oktest/ for details.


Changes
---

* enhanced 'ok (s1) == s2' to display unified diff (diff -u)
* changed to call 'before()/after()' instead of 'before_each()/
after_each()'
  (currently 'before_each()/after_each()' is also enabled but they
will be
   disabled in the future)
* improved compatibility with unittest module
* (internal) 'ValueObject' class is renamed to 'AssertionObject'
* (internal) 'Reporter#before_each()' and '#after_each()' are renamed
into
  '#before()' and '#after()'


Have fun!

--
regards,
makoto kuwata
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parsing XML

2010-05-16 Thread Stefan Behnel

Jake b, 16.05.2010 09:40:

Check out Amara: http://www.xml3k.org/Amara/QuickRef

It looks promising. For a pythonic solution over sax / dom.

>>> Iter(doc.team.player)
# or
>>> doc.team.player[0].name


Ah, right, and there's also lxml.objectify:

from lxml.objectify import parse

root = parse('teamfile.xml').getroot()

for player in root.player:
print(player.attrib)

Prints an attribute dict for each player.

Stefan

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



Re: joining files

2010-05-16 Thread Chris Rebert
On Sun, May 16, 2010 at 12:02 AM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

Outline of approach:
1. For each file, create a dict mapping the first number on each line
to that line.
2. Take the set intersection of the key sets of the dictionaries.
3. For each key in the intersection, get the values associated with it
from all the dicts and combine them, then output the combination.

HTH, but you're not gonna get any code out of me.
Some trivial parsing and knowledge of Python's datatypes is involved;
you should already know that or be able to readily figure it out from
the docs.

Cheers,
Chris
--

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


Re: joining files

2010-05-16 Thread Dave Angel

mannu jha wrote:

Hi,

I have few files like this:
file1:
22 110.1  
33 331.5 22.7 
5 271.9 17.2 33.4
4 55.1 


file1 has total 4 column but some of them are missing in few row.

file2:
5 H
22 0

file3:
4 T
5 B
22 C
121 S

in all these files first column is the main source of matching their entries. 
So What I want in the output is only those entries which is coming in all three 
files.
output required:
5 271.9 17.2 33.4 5 H  5 T
22 110.1 22 0 22 C


  
Do you have a spec?  Have you added any code to the last assignment to 
deal with this question, and in what way isn't it working?  Why don't 
you post your code?


Generally, you seem to have lines where the first "word" is a key to the 
line.  The word appears to be distinguished by whitespace.  So finding 
the key from a line would be just   line.split()[0]Then you build a 
dictionary from each file.  You didn't specify whether a given file 
might have multiple lines with the same key, so I'll just say to watch 
out for that, as a dictionary will cheerfully overwrite entries with new 
ones.


Since your rule on multiple files is apparently to throw out any line 
whose key isn't in all files, you'd need to make a dictionary for each 
file, then analyze all  of them in a later pass.  That pass could 
involve iterating through one of the dictionaries, and for each key 
deciding if it's in all of the others.  One way to do that is to build a 
list and run all() on it.


DaveA



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


Re: Setup global variables settings for the entire applications

2010-05-16 Thread Chris Rebert
On Fri, May 14, 2010 at 7:32 AM, AON LAZIO  wrote:
> Hi,
>    Say I have an application which requires a global settings for the user.
> When the user finishes setting those global variables for the app. Any class
> can use that variables (which are the same for all), something like that.
> What is the suitable mechanism for this solution?

Have a module that either contains the variables directly or contains
a configuration object that has the variables. Then just import the
module wherever you need to access the variables.

For example:

#config.py
power_user_mode = True
user_avatar = "bacon.jpg"

#elsewhere.py
import mypackage.config as config

class Foo(object):
#...
def whatever(self):
self.set_avatar(config.user_avatar)
if config.power_user_mode:
self.show_advanced_interface()
#...
def something(self):
new_avatar = self.avatar_chooser()
config.user_avatar = new_avatar
self.set_avatar(new_avatar)

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


Re: Reading XML namespaces

2010-05-16 Thread Martin v. Loewis
> Maybe true technically, but false in practice.  If I receive XML data
> from source XYZ or service XYZ the use of namespaces and their prefixes
> is extremely consistent [in practice] and very customary (for example:
> I've never seen the DSML namespace abbreviated as anything other than
> "dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
> than "D").  The odds that a customer or vendors ERP will generate
> different namespaces and abbreviations between requests is ludicrously
> remote [I don't recall ever seeing it happen].

In that case, you could also hard-code all prefixes in your application;
no need to traverse the input document.

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


Using site-packages with alt-installed Python version

2010-05-16 Thread Tuomas Vesterinen
I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native 
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.


Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py
$ sudo ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
  File "gui_utils.py", line 57, in ?
import gtk
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line 
30, in ?

import gobject as _gobject
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py", 
line 26, in ?
from glib import spawn_async, idle_add, timeout_add, 
timeout_add_seconds, \
  File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line 
22, in ?

from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol: 
_PyObject_CallFunction_SizeT


What I should say more to get access to the GTK?

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


Re: huh??? weird problem

2010-05-16 Thread Paul Hankin
On May 15, 3:41 am, Dave Angel  wrote:
> cerr wrote:
> > Hi There,
>
> > I got following code:
> > start=time.time()
> > print 'warnTimeout '+str(WarnTimeout)
> > print 'critTimeout '+str(CritTimeout)
> > print 'start',str(start)
> > while wait:
> >     passed =  time.time()-start
> >     print 'passed ',str(passed)
> >     if passed >= WarnTimeout:
> >       print ' Warning!'
> >  ...
> > ...
> > ...
> > which basically means that the loops should go until the warning time
> > has been reached and then i want it to print 'warning!' and execute
> > some warning code. But weirdly enough i get following screen output:
> > warnTimeout 3
> > critTimeout 5
> > start 1273882010.43
> > passed  7.60555267334e-05
> > passed  0.998471975327
> > passed  1.99847102165
> > passed  2.9984691143
> > passed  3.99847006798
> > passed  4.998472929
> > ...
> > ...
> > any one a clue why after 3 seconds it doesn't go into the the if an
> > print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(
>
> we're not seeing all the relevant code.  While I can ignore the missing
> import, I don't see any creation of the variables WarnTimeout and
> CritTimeout.  Simplest explanation that fits your sample run is that
> they are not of type float.

Yes, and most likely str. A good debugging tip is to use repr rather
than str to print out debugging messages.

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


Re: Using site-packages with alt-installed Python version

2010-05-16 Thread Alister
On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:

> I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
> Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.
> 
> Aplication GUI uses:
> import pygtk
> pygtk.require('2.0')
> import gtk
> import gobject
> 
> I go to:
> $ cd /usr/local/lib/python2.4/site-packages
> 
> and say:
> $ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
> ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0
> 
> and try:
> $ python2.4 gui_utils.py
> Traceback (most recent call last):
>File "gui_utils.py", line 57, in ?
>  import gtk
>File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
> 30, in ?
>  import gobject as _gobject
>File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
> line 26, in ?
>  from glib import spawn_async, idle_add, timeout_add,
> timeout_add_seconds, \
>File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
> 22, in ?
>  from glib._glib import *
> ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
> _PyObject_CallFunction_SizeT
> 
> What I should say more to get access to the GTK?
> 
> Tuomas Vesterinen

I am not a great expert on this But I think you need to use the Redhat 
alternatives system to switch between versions rather than trying to 
change things manually.

as i understand it the Alternatives system sets up and changes various 
symlinks to ensure everything works correctly. 



-- 
"When the going gets tough, the tough get empirical."
-- Jon Carroll
-- 
http://mail.python.org/mailman/listinfo/python-list


Fw: Re: Re: joining files

2010-05-16 Thread mannu jha
Note: Forwarded message attached

-- Original Message --

From: "mannu jha"[email protected]
To: [email protected]
Subject: Re: Re: joining files--- Begin Message ---


On Sun, 16 May 2010 13:52:31 +0530  wrote
>mannu jha wrote:

> Hi,

>

> I have few files like this:
> file1:
> 22 110.1 
> 33 331.5 22.7 
> 5 271.9 17.2 33.4
> 4 55.1 

> file1 has total 4 column but some of them are missing in few row.

> file2:
> 5 H
> 22 0

> file3:
> 4 T
> 5 B
> 22 C
> 121 S

>

> in all these files first column is the main source of matching their entries. 
> So What I want in the output is only those entries which is coming in all 
> three files.

> output required:

> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

>
I am trying with this :

from collections import defaultdict

def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]

if __name__ == "__main__":
a = open("input1.txt")

c = open("input2.txt")

def key(line):
return line[:2]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,c]]):
print "|".join(c.ljust(10) for c in m)

but with input1.txt:
1877.79   122.27   54.37   4.26   179.75
1948.00   121.23   54.79   4.12   180.06
158.45   119.04   55.02   4.08   178.89
1767.78   118.68   54.57   4.20   181.06
1807.50   119.21   53.93  179.80
1907.58   120.44   54.62   4.25   180.02
1528.39   120.63   55.10   4.15   179.10
1547.79   119.62   54.47   4.22   180.46
1758.42   120.50   55.31   4.04   180.33
and input2.txt:
 15   H 
 37   H 
 95   T
124   H 
130   H 
152   H 
154   H 
158   H 
164   H
175   H 
176   H 
180   H
187   H 
190   T
194   C
196   H 
207   H 
210   H 
232   H 
it is giving output as:
  |
  |124   H
  |130   H
1547.79   119.62   54.47   4.22   180.46|158   H
  |164   H
1758.42   120.50   55.31   4.04   180.33|176   H
1807.50   119.21   53.93  179.80|187   H
1907.58   120.44   54.62   4.25   180.02|196   H
  |207   H
  |210   H
  |232   H
  |37   H
  |95   T
so it not matching it properly, can anyone please suggest where I am doing 
mistake.


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


Re: Picking a license

2010-05-16 Thread Ed Keith
--- On Sat, 5/15/10, Robert Kern  wrote:

> From: Robert Kern 
> Subject: Re: Picking a license
> To: [email protected]
> Date: Saturday, May 15, 2010, 1:10 PM
> On 2010-05-14 21:37 , Steven D'Aprano
> wrote:
> > On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:
> > 
> >> I am not a lawyer, but as I understand the LGPL,
> If I give someone
> >> something that used any LGPLed code I must give
> them the ability to
> >> relink it with any future releases of the LGPLed
> code. I think that
> >> means that I need to give them a linker and teach
> them how to use it,
> >> and I do not want to go there.
> > 
> > Surely you're joking?
> > 
> > Does this mean that if they lose their hands in an
> accident, you have to
> > come sit at their computer and do their typing?
> > 
> > The LGPL and GPL don't grant people "the ability" to
> do anything, since
> > that's not within our power to grant. Some people
> don't want to, or
> > can't, program, or don't have time. It's not like the
> LGPL is the bite of
> > a radioactive spider that can grant superpowers. It is
> a licence which
> > grants *permissions*.
> 
> No, the LGPL requires you to do something extra to enable
> your users to be able to relink your program. You need to
> provide the ability to do this, up to some unspecified and
> untested limit of reasonableness (your example is obviously
> beyond the limit of reasonableness). You can't just give
> them, say, a statically linked program and nothing else. You
> can't require for-fee, proprietary linkers. This is usually
> not hard to do (just give them unlinked .o or .obj files and
> a Makefile or project file), but it is *not* just a matter
> of granting permissions.
> 
> But you're right, you don't have to teach them how to do
> it.
> 
> -- Robert Kern
> 
> "I have come to believe that the whole world is an enigma,
> a harmless enigma
>  that is made terrible by our own mad attempt to interpret
> it as though it had
>  an underlying truth."
>   -- Umberto Eco
> 
> -- http://mail.python.org/mailman/listinfo/python-list
> 

But most of my clients run MS-Windows, and I do most of my development in C++, 
so they would need to use a proprietary linker.

-EdK

Ed Keith
[email protected]

Blog: edkeith.blogspot.com





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


Re: joining files

2010-05-16 Thread Dave Angel
(You forgot to include the python-list in your response.  So it only 
went to me.  Normally, you just do reply-all to the message)


mannu jha wrote:

On Sun, 16 May 2010 13:52:31 +0530  wrote
  

mannu jha wrote:



  

Hi,



  

  

I have few files like this:
file1:
22 110.1 
33 331.5 22.7 
5 271.9 17.2 33.4
4 55.1 



  

file1 has total 4 column but some of them are missing in few row.



  

file2:
5 H
22 0



  

file3:
4 T
5 B
22 C
121 S



  

  

in all these files first column is the main source of matching their entries. 
So What I want in the output is only those entries which is coming in all three 
files.



  

output required:



  

5 271.9 17.2 33.4 5 H 5 T
22 110.1 22 0 22 C



  
I am trying with this :


from collections import defaultdict

def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]

if __name__ == "__main__":
a = open("input1.txt")

c = open("input2.txt")


def key(line):
return line[:2]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,c]]):
print "|".join(c.ljust(10) for c in m)

but with input1.txt:
1877.79   122.27   54.37   4.26   179.75
1948.00   121.23   54.79   4.12   180.06
158.45   119.04   55.02   4.08   178.89
1767.78   118.68   54.57   4.20   181.06
1807.50   119.21   53.93  179.80
1907.58   120.44   54.62   4.25   180.02
1528.39   120.63   55.10   4.15   179.10
1547.79   119.62   54.47   4.22   180.46
1758.42   120.50   55.31   4.04   180.33
and input2.txt:
 15   H 
 37   H 
 95   T
124   H 
130   H 
152   H 
154   H 
158   H 
164   H
175   H 
176   H 
180   H
187   H 
190   T

194   C
196   H 
207   H 
210   H 
232   H 
it is giving output as:

  |
  |124   H
  |130   H
1547.79   119.62   54.47   4.22   180.46|158   H
  |164   H
1758.42   120.50   55.31   4.04   180.33|176   H
1807.50   119.21   53.93  179.80|187   H
1907.58   120.44   54.62   4.25   180.02|196   H
  |207   H
  |210   H
  |232   H
  |37   H
  |95   T
so it not matching it properly, can anyone please suggest where I am doing 
mistake.



  

I'm about to travel all day, so my response will be quite brief.

Not sure what you mean by the blank and key values that source() takes, 
since they're just passed on to its return value.


I don't see any place where you compare the items from the various 
files, so you aren't checking if an item is in multiple files.


DaveA

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


Re: Picking a license

2010-05-16 Thread Ed Keith
--- On Sat, 5/15/10, Lawrence D'Oliveiro  
wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: [email protected]
> Date: Saturday, May 15, 2010, 11:06 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > On Fri, 5/14/10, Lawrence D'Oliveiro
> > 
> wrote:
> > 
> >> In message ,
> >> Ed Keith wrote:
> >> 
> >>> Yes, under the GPL every one has one set of
> freedoms,
> >>> under the MIT or Boost license every one has
> more freedoms. Under other
> >>> licenses they have fewer freedoms.
> >> 
> >> But what about the “freedom” to take away
> other
> >> people’s freedom? Is that really “freedom”?
> > 
> > Yes.
> 
> But that’s a “freedom” that non-GPL licences do not
> give you, that the GPL 
> does. So which licence gives you more “freedoms”,
> again?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


? You just answered your own question. The The GPL does not give you the 
freedoms to take away other people freedom, so the the less restrictive license 
have less restrictions (which is why they are called "less restrictive" by the 
way) "Less restrictions" is a synonym for "more freedoms". To the extent that 
something is "restricted" it is not "free". To the extent which something if 
"free" it is not "restricted". 

There is clearly some kind of communication problem here. Either were are 
speaking different languages with some faulty transaction program interviewing, 
or one of is is either stupid or senile (seems a bit early for me, but it is 
possible); or you are being disingenuous. 

If you type the word 'restrict' into thesaurus.com you will get the following 
antonyms: enlarge, expand, free, let go, release, Note the second word on the 
list. Please do not take my word for it, try it yourself. Try other sites, if 
you think I may have rigged this one.

 -EdK

Ed Keith
[email protected]

Blog: edkeith.blogspot.com





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


Re: joining files

2010-05-16 Thread Aahz
In article ,
Chris Rebert   wrote:
>
>--
>

That's not funny.  I'm sure I'd have little difficulty finding poor
programmers of whatever demographic groups you belong to.  Or perhaps you
haven't noticed that PEBKACs are everywhere?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to comp.lang.python

2010-05-16 Thread cjw

On 16-May-10 01:31 AM, James Mills wrote:

On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:

It's also at least partly due to problems with mail<->news gateways and
the differing fields used to maintain threading.


Some blame goes on MUAs too :)


Thanks for the responses.

Is it possible to connect a newsreader to gmane?  Or is web access required?

Is Thunderbird known to have problems?

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


Re: Access to comp.lang.python

2010-05-16 Thread Grant Edwards
On 2010-05-16, cjw  wrote:
> On 16-May-10 01:31 AM, James Mills wrote:
>> On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
>>> It's also at least partly due to problems with mail<->news gateways and
>>> the differing fields used to maintain threading.
>>
>> Some blame goes on MUAs too :)
>
> Thanks for the responses.
>
> Is it possible to connect a newsreader to gmane?

nntp://news.gmane.org/

-- 
Grant

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


Re: Reading XML namespaces

2010-05-16 Thread Stefan Behnel

Martin v. Loewis, 16.05.2010 11:05:

Maybe true technically, but false in practice.  If I receive XML data
from source XYZ or service XYZ the use of namespaces and their prefixes
is extremely consistent [in practice] and very customary (for example:
I've never seen the DSML namespace abbreviated as anything other than
"dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
than "D").  The odds that a customer or vendors ERP will generate
different namespaces and abbreviations between requests is ludicrously
remote [I don't recall ever seeing it happen].


In that case, you could also hard-code all prefixes in your application;
no need to traverse the input document.


+1. Hard-coding the prefixes is the best way to make the interface of your 
code consistent and predictable.


Stefan

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


Re: Access to comp.lang.python

2010-05-16 Thread John Bokma
cjw  writes:

> Is it possible to connect a newsreader to gmane?

http://johnbokma.com/mexit/2005/01/14/gmane-mail-to-news.html

> Is Thunderbird known to have problems?

It worked good for me, but that was 5+ years ago. (Time flies)

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to comp.lang.python

2010-05-16 Thread Jim Byrnes

Grant Edwards wrote:

On 2010-05-16, cjw  wrote:

On 16-May-10 01:31 AM, James Mills wrote:

On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:

It's also at least partly due to problems with mail<->news gateways and
the differing fields used to maintain threading.


Some blame goes on MUAs too :)


Thanks for the responses.

Is it possible to connect a newsreader to gmane?


nntp://news.gmane.org/



Could someone please explain how to subscribe to this list on gmane.  I 
subscribe to a couple of other groups there but can't find this one.


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


Object-oriented (was: Is Python a functional programming language?)

2010-05-16 Thread Teemu Likonen
* 2010-05-15 09:42 (-0700), travis wrote:

> PS: Why do people call LISP object-oriented?  Are they smoking crack?
> No classes, no methods, no member variables... WTF?

Maybe because Common Lisp has a strong support for object-oriented
programming.


Peter Seibel: Practical Common Lisp

Generic functions and methods (chapter 16)
http://www.gigamonkeys.com/book/object-reorientation-generic-functions.html

Classes (chapter 17)
http://www.gigamonkeys.com/book/object-reorientation-classes.html

Paul Graham: On Lisp

Object-Oriented Lisp (chapter 25)
http://www.bookshelf.jp/texi/onlisp/onlisp_26.html#SEC156

Wikipedia: Common Lisp Object System

http://en.wikipedia.org/wiki/Common_Lisp_Object_System
-- 
http://mail.python.org/mailman/listinfo/python-list


Updating values in a dictionary

2010-05-16 Thread Thomas
Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursively remove all the directories and files which begin with '.'

2010-05-16 Thread Sean DiZazzo
On May 14, 8:27 am, albert kao  wrote:
> On May 14, 11:01 am, J  wrote:
>
>
>
> > On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > > C:\python>rmdir.py
> > > C:\test\com.comp.hw.prod.proj.war\bin
> > > ['.svn', 'com']
> > > d .svn
> > > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > > Traceback (most recent call last):
> > >  File "C:\python\rmdir.py", line 14, in 
> > >    rmtree(os.path.join(curdir, d))
> > >  File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > >    onerror(os.remove, fullname, sys.exc_info())
> > >  File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > >    os.remove(fullname)
> > > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > You don't have permissions to remove the subdir or file entries in the
> > .svn directory...
>
> > Maybe that file is still open, or still has a lock attached to it?
>
> I reboot my windows computer and run this script as administrator.
> Do my script has a bug?

Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

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


Re: Updating values in a dictionary

2010-05-16 Thread Chris Rebert
On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:
> Greetings
>
> I am having a darn awful time trying to update a matrix:
>
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])

All the columns refer to the very same row dict (`row` obviously).
Python doesn't do any copying unless you explicitly request it.

Try:
matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in range(-3,4,1)])

This way, the row-creation code gets called for each column and thus
fresh row dicts are created rather than all just referencing the exact
same one row dict.
Nested comprehensions may be hard to understand, so you may wish to
write it using a function instead:

def make_row():
return dict([(x,0) for x in range(3)])

matrix = dict([(x,make_row()) for x in range(-3,4,1)])

See also 
http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

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


Global variables for python applications

2010-05-16 Thread AON LAZIO
Hi,
   How can I set up global variables for the entire python applications?
Like I can call and set this variables in any .py files.
   Think of it as a global variable in a single .py file but this is for the
entire application.
   Thanks

-- 
Aonlazio
'Peace is always the way.' NW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Updating values in a dictionary

2010-05-16 Thread superpollo

Thomas ha scritto:

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.


clone the row:

>>> row = dict([(x,0) for x in range(3)])
>>> import copy
>>> matrix = dict([(x,copy.copy(row)) for x in range(-3,4,1)])
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> import pprint
>>> pp = pprint.PrettyPrinter()
>>> pp.pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
 0: {0: 0, 1: 0, 2: 0},
 1: {0: 0, 1: 0, 2: 0},
 2: {0: 0, 1: 1, 2: 0},
 3: {0: 0, 1: 0, 2: 0}}
>>>

bye

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


Re: Global variables for python applications

2010-05-16 Thread James Mills
On Mon, May 17, 2010 at 3:50 AM, AON LAZIO  wrote:
> Hi,
>    How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
>    Think of it as a global variable in a single .py file but this is for the
> entire application.

If you have to use global variables in your application you are
designing it WRONG!

Python has powerful support for object orientated programming. Use it!

I highly recommend the Python tutorial - especially the section on classes.

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


Re: recursively remove all the directories and files which begin with '.'

2010-05-16 Thread Irmen de Jong

On 16-5-2010 19:41, Sean DiZazzo wrote:

On May 14, 8:27 am, albert kao  wrote:

On May 14, 11:01 am, J  wrote:




On Fri, May 14, 2010 at 10:53, albert kao  wrote:



C:\python>rmdir.py
C:\test\com.comp.hw.prod.proj.war\bin
['.svn', 'com']
d .svn
dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
Traceback (most recent call last):
  File "C:\python\rmdir.py", line 14, in
rmtree(os.path.join(curdir, d))
  File "C:\Python31\lib\shutil.py", line 235, in rmtree
onerror(os.remove, fullname, sys.exc_info())
  File "C:\Python31\lib\shutil.py", line 233, in rmtree
os.remove(fullname)
WindowsError: [Error 5] Access is denied: 'C:\\test\
\com.comp.hw.prod.proj.war\\bin\\.svn\\entries'



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



You don't have permissions to remove the subdir or file entries in the
.svn directory...



Maybe that file is still open, or still has a lock attached to it?


I reboot my windows computer and run this script as administrator.
Do my script has a bug?


Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

~Sean


You should be able to do this with os.chmod as well (no extra modules 
required). I'm not sure what the mode should be though. Perhaps 0777 
does the trick.


-irmen

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


Re: Global variables for python applications

2010-05-16 Thread Krister Svanlund
On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> Hi,
>    How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
>    Think of it as a global variable in a single .py file but this is for the
> entire application.
>    Thanks
>
> --
> Aonlazio
> 'Peace is always the way.' NW

First: Do NOT use global variables, it is bad practice and will
eventually give you loads of s**t.

But if you want to create global variables in python I do believe it
is possible to specify them in a .py file and then simply import it as
a module in your application. If you change one value in a module the
change will be available in all places you imported that module in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables for python applications

2010-05-16 Thread Chris Rebert
On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
> Hi,
>    How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
>    Think of it as a global variable in a single .py file but this is for the
> entire application.

Thankfully, there is no such thing (can you say spaghetti code?). The
closest approximation, as I said in my previous reply, is to use the
namespace of a designated module for this purpose, and import that
module wherever you need to access/modify these "superglobal"
variables.

Example:
#g.py:
#this module exists to hold superglobal vars
global1 = "foo"
global2 = "bar"


#elsewhere.py:
#this is some other module in the same program
import mypackage.g as g

print "global #1 = ", g.global1
print "global #2 =", g.global2
g.global1 = "baz" # modify a superglobal
g.global3 = "qux" # create a new superglobal


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


Re: Updating values in a dictionary

2010-05-16 Thread Peter Otten
Chris Rebert wrote:

> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
> 
> def make_row():
> return dict([(x,0) for x in range(3)])
> 
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])

Another way to skin the cat:

>>> row = dict.fromkeys(range(3), 0)
>>> matrix = dict((x, row.copy()) for x in range(-3, 4))
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> from pprint import pprint
>>> pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
 0: {0: 0, 1: 0, 2: 0},
 1: {0: 0, 1: 0, 2: 0},
 2: {0: 0, 1: 1, 2: 0},
 3: {0: 0, 1: 0, 2: 0}}

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


Re: joining files

2010-05-16 Thread Tuomas Vesterinen

On 05/16/2010 05:04 PM, Dave Angel wrote:

(You forgot to include the python-list in your response.  So it only
went to me. Normally, you just do reply-all to the message)

mannu jha wrote:

On Sun, 16 May 2010 13:52:31 +0530 wrote

mannu jha wrote:



Hi,




I have few files like this:
file1:
22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
4 55.1



file1 has total 4 column but some of them are missing in few row.



file2:
5 H
22 0



file3:
4 T
5 B
22 C
121 S




in all these files first column is the main source of matching their
entries. So What I want in the output is only those entries which is
coming in all three files.



output required:



5 271.9 17.2 33.4 5 H 5 T
22 110.1 22 0 22 C


I am trying with this :

from collections import defaultdict

def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]

if __name__ == "__main__":
a = open("input1.txt")
c = open("input2.txt")

def key(line):
return line[:2]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,c]]):
print "|".join(c.ljust(10) for c in m)

but with input1.txt:
187 7.79 122.27 54.37 4.26 179.75
194 8.00 121.23 54.79 4.12 180.06
15 8.45 119.04 55.02 4.08 178.89
176 7.78 118.68 54.57 4.20 181.06
180 7.50 119.21 53.93 179.80
190 7.58 120.44 54.62 4.25 180.02
152 8.39 120.63 55.10 4.15 179.10
154 7.79 119.62 54.47 4.22 180.46
175 8.42 120.50 55.31 4.04 180.33
and input2.txt:
15 H 37 H 95 T
124 H 130 H 152 H 154 H 158 H 164 H
175 H 176 H 180 H
187 H 190 T
194 C
196 H 207 H 210 H 232 H it is giving output as:
|
|124 H
|130 H
154 7.79 119.62 54.47 4.22 180.46|158 H
|164 H
175 8.42 120.50 55.31 4.04 180.33|176 H
180 7.50 119.21 53.93 179.80|187 H
190 7.58 120.44 54.62 4.25 180.02|196 H
|207 H
|210 H
|232 H
|37 H
|95 T
so it not matching it properly, can anyone please suggest where I am
doing mistake.




I'm about to travel all day, so my response will be quite brief.

Not sure what you mean by the blank and key values that source() takes,
since they're just passed on to its return value.

I don't see any place where you compare the items from the various
files, so you aren't checking if an item is in multiple files.

DaveA


import os

def merge_sources(sources):
# sources is a list of tuples (source_name, source_data)
data = []
keysets = []
for nme, sce in sources:
lines = {}
for line in sce.split(os.linesep):
lst = line.split()
lines[lst[0]] = (nme, lst)
keysets.append(set(lines.keys()))
data.append(lines)
common_keys = keysets[0]
for keys in keysets[1:]:
common_keys = common_keys.intersection(keys)
result = {}
for key in common_keys:
result[key] = dict(d[key] for d in data if key in d)
return result

if __name__ == "__main__":
# Your test files here are replaced by local strings
print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])

print merge_sources([("input1", input1), ("input2", input2)])

Test_results = '''
{'22': {'file3': ['22', 'C'],
'file2': ['22', '0'],
'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
  '17.2', '33.4']}}

{'194': {'input2': ['194', 'C'],
 'input1': ['194', '8.00', '121.23', '54.79', '4.12',
'180.06']},
 '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
 'input1': ['175', '8.42', '120.50', '55.31', '4.04',
'180.33']},
  '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
 'input1': ['15', '8.45', '119.04', '55.02', '4.08',
'178.89']},
 '187': {'input2': ['187', 'H', '190', 'T'],
 'input1': ['187', '7.79', '122.27', '54.37', '4.26',
'179.75']}}
'''

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


Re: Global variables for python applications

2010-05-16 Thread James Mills
On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
 wrote:
> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
>>    How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>>    Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> First: Do NOT use global variables, it is bad practice and will
> eventually give you loads of s**t.
>
> But if you want to create global variables in python I do believe it
> is possible to specify them in a .py file and then simply import it as
> a module in your application. If you change one value in a module the
> change will be available in all places you imported that module in.

The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.

Anything else should be an object that you share. Don't get into the
habit of using global variables!

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


Qt and progressBar - how to update

2010-05-16 Thread OMS
I am quite new to Python and Qt and need very urgently advice on how
to update Qt progressBar while executing a process. I have went thrugh
number of 'google' stuff and saw different solution, hence none worked
for me. The best idea I have seen is the usage of QThread and emiting
signal from thread to MainWindow. I do not know however why the code I
have written is not working. Most likely a stupid 'beginner related'
error but as far as I am beginner I can't get it. There is a code
below:

#!/opt/local/bin/python2.6

import os
import sys
import time
from PyQt4 import QtCore
from PyQt4 import QtGui

from uiTest import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
self.runWorker)

def runWorker(self):
self.worker = Worker()
self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
self.updateWorkerProgress)
self.worker.start()

def updateWorkerProgress(self, min, max, progress):
self.ui.progressBar.setMinimum = min
self.ui.progressBar.setMaximum = max
self.ui.progressBar.setValue = progress
self.ui.progressBar.repaint()
#print min, progress, max

class Worker(QtCore.QThread):
__pyqtSignals__ = ("progressUpdated")
def __init__(self):
QtCore.QThread.__init__(self)
self.min = 0
self.max = 1000
self.progress = 0
def run(self):
for self.progress in range(self.min, self.max):
self.emit(QtCore.SIGNAL("progressUpdated"), self.min,
self.max, self.progress)
time.sleep(0.005)

def main():
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()

the uiTest is generated by pyuic4 and for reference can be found
below:

# Form implementation generated from reading ui file 'test.ui'
#
# Created: Sun May 16 19:54:59 2010
#  by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 40, 113, 32))
self.pushButton.setObjectName("pushButton")
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(50, 80, 431, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)

self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
 
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8))
 
self.pushButton.setText(QtGui.QApplication.translate("MainWindow",
"PushButton", None, QtGui.QApplication.UnicodeUTF8))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using site-packages with alt-installed Python version

2010-05-16 Thread Tuomas Vesterinen

On 05/16/2010 02:38 PM, Alister wrote:

On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:


I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.

Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
File "gui_utils.py", line 57, in ?
  import gtk
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
30, in ?
  import gobject as _gobject
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
line 26, in ?
  from glib import spawn_async, idle_add, timeout_add,
timeout_add_seconds, \
File
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
22, in ?
  from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
_PyObject_CallFunction_SizeT

What I should say more to get access to the GTK?

Tuomas Vesterinen


I am not a great expert on this But I think you need to use the Redhat
alternatives system to switch between versions rather than trying to
change things manually.

as i understand it the Alternatives system sets up and changes various
symlinks to ensure everything works correctly.



Yes, my first trial is not the solution because byte compiled .pyc files 
must be produced by the corresponding Python version.


PEP 3147 http://www.python.org/dev/peps/pep-3147 suggests a common 
solution, but only for Python 3.2 and perhaps 2.7. So I am still looking 
for hints. Have You some helpful links to those "Alternatives system"?


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


Re: recursively remove all the directories and files which begin with '.'

2010-05-16 Thread Walter Wefft

Irmen de Jong wrote:

On 16-5-2010 19:41, Sean DiZazzo wrote:

On May 14, 8:27 am, albert kao  wrote:

On May 14, 11:01 am, J  wrote:




On Fri, May 14, 2010 at 10:53, albert kao  wrote:



C:\python>rmdir.py
C:\test\com.comp.hw.prod.proj.war\bin
['.svn', 'com']
d .svn
dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
Traceback (most recent call last):
  File "C:\python\rmdir.py", line 14, in
rmtree(os.path.join(curdir, d))
  File "C:\Python31\lib\shutil.py", line 235, in rmtree
onerror(os.remove, fullname, sys.exc_info())
  File "C:\Python31\lib\shutil.py", line 233, in rmtree
os.remove(fullname)
WindowsError: [Error 5] Access is denied: 'C:\\test\
\com.comp.hw.prod.proj.war\\bin\\.svn\\entries'



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



You don't have permissions to remove the subdir or file entries in the
.svn directory...



Maybe that file is still open, or still has a lock attached to it?


I reboot my windows computer and run this script as administrator.
Do my script has a bug?


Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

~Sean


You should be able to do this with os.chmod as well (no extra modules 
required). I'm not sure what the mode should be though. Perhaps 0777 
does the trick.


-irmen



def make_readable(fpath):
'''
On windows, this will make a read-only file readable.
'''
mode = os.stat(fpath)[stat.ST_MODE] | stat.S_IREAD | stat.S_IWRITE
chmod(fpath, mode)

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


Re: Updating values in a dictionary

2010-05-16 Thread Thomas

Chris

Wow, that was a very fast response.
Thank you, it works  (of course)...

Cheers

"Chris Rebert"  wrote in message 
news:[email protected]...

On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])


All the columns refer to the very same row dict (`row` obviously).
Python doesn't do any copying unless you explicitly request it.

Try:
matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in 
range(-3,4,1)])


This way, the row-creation code gets called for each column and thus
fresh row dicts are created rather than all just referencing the exact
same one row dict.
Nested comprehensions may be hard to understand, so you may wish to
write it using a function instead:

def make_row():
   return dict([(x,0) for x in range(3)])

matrix = dict([(x,make_row()) for x in range(-3,4,1)])

See also 
http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list


Cheers,
Chris
--
http://blog.rebertia.com 


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


Re: Qt and progressBar - how to update

2010-05-16 Thread Robert Kern

On 2010-05-16 13:28 , OMS wrote:

I am quite new to Python and Qt and need very urgently advice on how
to update Qt progressBar while executing a process. I have went thrugh
number of 'google' stuff and saw different solution, hence none worked
for me. The best idea I have seen is the usage of QThread and emiting
signal from thread to MainWindow. I do not know however why the code I
have written is not working. Most likely a stupid 'beginner related'
error but as far as I am beginner I can't get it. There is a code
below:

#!/opt/local/bin/python2.6

import os
import sys
import time
from PyQt4 import QtCore
from PyQt4 import QtGui

from uiTest import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
 def __init__(self):
 QtGui.QMainWindow.__init__(self)
 self.ui=Ui_MainWindow()
 self.ui.setupUi(self)
 self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
self.runWorker)

 def runWorker(self):
 self.worker = Worker()
 self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
self.updateWorkerProgress)
 self.worker.start()

 def updateWorkerProgress(self, min, max, progress):
 self.ui.progressBar.setMinimum = min
 self.ui.progressBar.setMaximum = max
 self.ui.progressBar.setValue = progress


These should be

self.ui.progressBar.setMinimum(min)
self.ui.progressBar.setMaximum(max)
self.ui.progressBar.setValue(progress)

--
Robert Kern

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

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


imports and exec

2010-05-16 Thread Paul Carter
We are using python for our build system. Each subproject dir has a
python script that builds it. Parent dirs have python scripts that
recurse into their children and use exec to invoke the python scripts.
Recently we discovered that one of the python scripts works when
invoked directly, but fails when invoked with exec. I've created a
very simple pair of python scripts that demonstrates the problem.
(We're using python 2.6)

Can someone explain or point to a good explanation of why this problem
occurs?

I have two python files: prim.py and sec.py.
prim.py:
-
#!/usr/bin/env python

##sec2 = open('sec.py')
##exec sec2

def invoke():
  sec = open('sec.py')
  exec sec

invoke()
--

and sec.py:
--
import sys

def sec():
  print('Inside sec(): ' +  str(sys.argv))

print('Outside sec(): ' + str(sys.argv))
sec()
--

When I run prim.py, I get an error:

Outside sec(): ['./prim.py']
Traceback (most recent call last):
  File "./prim.py", line 10, in 
invoke()
  File "./prim.py", line 8, in invoke
exec sec
  File "sec.py", line 7, in 
sec()
  File "sec.py", line 4, in sec
print('Inside sec(): ' +  str(sys.argv))
NameError: global name 'sys' is not defined
--

I don't understand why the sys import is not visible in the sec()
function. I can fix this by adding a:
  global sys
or
  import sys
inside the sec() function. But I would like to understand why this is
necessary, especially since sys is visible in sec.py outside of the
sec() function. I found this page discussing exec

http://docs.python.org/reference/executionmodel.html

but I'm afraid I couldn't quite follow it. It makes me think that a
free variable is involved, but I don't see how. It did made me try
invoking exec in prim.py outside of the invoke() function (see the
commented out code). Everything worked fine when I did that.

Can someone set me straight? Suggestions on avoiding this problem are
welcome as well!

Thanks in advance.

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


Re: Access to comp.lang.python

2010-05-16 Thread Robert Kern

On 2010-05-16 11:47 , Jim Byrnes wrote:

Grant Edwards wrote:

On 2010-05-16, cjw wrote:

On 16-May-10 01:31 AM, James Mills wrote:

On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:

It's also at least partly due to problems with mail<->news gateways
and
the differing fields used to maintain threading.


Some blame goes on MUAs too :)


Thanks for the responses.

Is it possible to connect a newsreader to gmane?


nntp://news.gmane.org/



Could someone please explain how to subscribe to this list on gmane. I
subscribe to a couple of other groups there but can't find this one.


It's name on GMane is gmane.comp.python.general

--
Robert Kern

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

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


Re: Human word reader

2010-05-16 Thread CM
> > I need help with getting the useful information how do I get the place
> > if I don't now how long the string is?
>
>         And is it supposed to handle
>
>         for london give the weather to me
>         for the london weather give me
>
> ...
>
>         Do a search on "natural language processing"... You are at the level
> of algorithms, and algorithms are not limited to Python...

Yes, this is a major field of research.  For basic purposes in Python,
maybe just try to trigger off the presence of the word "weather" and
the presence of a particular city's name.  It will not work if the
user tries to trick it ("Don't give me the weather in London"), but,
like a search engine, it will more or less give what people want for
common queries.  Like:

list_of_cities = ['london', 'moscow', 'new york', 'paris']
user_string = 'Give me the weather for London please.'
user_word_list = user_string.split()  #if they put a comma after city,
this will be a problem
for word in user_word_list:
period_free_word = word.rstrip('.') #strips trailing period for
final word, in case there
lowered_word = period_free_word.lower()  #makes it case
insensitive
if lowered_word in list_of_cities:
 print 'The city is: ' + lowered_word
 DoSomething(lowered_word)  #go and get the weather data for
that city I guess

Che




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


Re: Human word reader

2010-05-16 Thread CM
On May 16, 2:57 pm, CM  wrote:
> > > I need help with getting the useful information how do I get the place
> > > if I don't now how long the string is?
>
> >         And is it supposed to handle
>
> >         for london give the weather to me
> >         for the london weather give me
>
> > ...
>
> >         Do a search on "natural language processing"... You are at the level
> > of algorithms, and algorithms are not limited to Python...
>
> Yes, this is a major field of research.  For basic purposes in Python,
> maybe just try to trigger off the presence of the word "weather" and
> the presence of a particular city's name.  It will not work if the
> user tries to trick it ("Don't give me the weather in London"), but,
> like a search engine, it will more or less give what people want for
> common queries.  Like:
>
> list_of_cities = ['london', 'moscow', 'new york', 'paris']
> user_string = 'Give me the weather for London please.'
> user_word_list = user_string.split()  #if they put a comma after city,
> this will be a problem
> for word in user_word_list:
>     period_free_word = word.rstrip('.') #strips trailing period for
> final word, in case there
>     lowered_word = period_free_word.lower()  #makes it case
> insensitive
>     if lowered_word in list_of_cities:
>          print 'The city is: ' + lowered_word
>          DoSomething(lowered_word)  #go and get the weather data for
> that city I guess
>
> Che

I forgot to split on two delimiters (a space and a comma).  See here:
http://mail.python.org/pipermail/tutor/2008-August/063570.html

Anyway, you get the idea...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to comp.lang.python

2010-05-16 Thread Terry Reedy

On 5/16/2010 11:35 AM, Grant Edwards wrote:

On 2010-05-16, cjw  wrote:

On 16-May-10 01:31 AM, James Mills wrote:

On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:

It's also at least partly due to problems with mail<->news gateways and
the differing fields used to maintain threading.


Some blame goes on MUAs too :)


Thanks for the responses.

Is it possible to connect a newsreader to gmane?


nntp://news.gmane.org/


Thunderbird 2 and 3 work fine with it.



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


Re: Updating values in a dictionary

2010-05-16 Thread Terry Reedy

On 5/16/2010 1:36 PM, Thomas wrote:

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1


Dicts are fine for sparse matrixes, but when filled in, a list of lists 
is perhaps easier and more efficient. And you can iterate and be 
guaranteed to get the sublists in the expected order.


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


Re: Global variables for python applications

2010-05-16 Thread christian schulze
On 16 Mai, 20:20, James Mills  wrote:
> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
>
>  wrote:
> > On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> >>    How can I set up global variables for the entire python applications?
> >> Like I can call and set this variables in any .py files.
> >>    Think of it as a global variable in a single .py file but this is for 
> >> the
> >> entire application.
>
> > First: Do NOT use global variables, it is bad practice and will
> > eventually give you loads of s**t.
>
> > But if you want to create global variables in python I do believe it
> > is possible to specify them in a .py file and then simply import it as
> > a module in your application. If you change one value in a module the
> > change will be available in all places you imported that module in.
>
> The only place global variables are considered somewhat "acceptable"
> are as constants in a module shared as a static value.
>
> Anything else should be an object that you share. Don't get into the
> habit of using global variables!
>
> --james

Exactly! Python's OOP is awesome. Use it. Global vars used as anything
but constants is bad practice. It isn't that much work to implement
that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Picking a license

2010-05-16 Thread Patrick Maupin
On May 16, 9:19 am, Ed Keith  wrote:
> --- On Sat, 5/15/10, Lawrence D'Oliveiro  
> wrote:
> > >> But what about the “freedom” to take away
> > other
> > >> people’s freedom? Is that really “freedom”?
>
> > > Yes.
>
> > But that’s a “freedom” that non-GPL licences do not
> > give you, that the GPL
> > does. So which licence gives you more “freedoms”,
> > again?

[ stuff snipped]

> There is clearly some kind of communication problem here. Either were are 
> speaking different languages with some faulty transaction program 
> interviewing, or one of is is either stupid or senile (seems a bit early for 
> me, but it is possible); or you are being disingenuous.

Lawrence is certainly being overly clever.  He is somewhat technically
correct, but is playing a shell game where he moves around who the
potential "freedom" giver is and who the potential "freedom" receiver
is.

The problem is, you have to handle this sort of argument very
carefully, or someone will come along and then point out (again,
somewhat technically correctly) that copyright law restricts the
"freedoms", and the GPL license only gives them out, so where's the
problem?  It's easy to lose sight of where the pea is, particularly
when you were expecting straightforward communication rather than this
sort of sophistry.

When people in this thread previously said that permissive licenses
give you the "freedom" to take away others' "freedoms", but the GPL
does not, the "you" they are referring to is "a person who has
received the software from someone else".

When Lawrence is now saying that the GPL gives you the "freedom" to
take away others' "freedoms" but other licenses do not, the "you" he
is referring to is the "author of the software", who I think we all
agree retains more "freedom" to restrict others' "freedoms" if he uses
the GPL than if he uses a permissive license.

So in this instance, the thing that disappeared under the shell where
you thought it was and reappeared under a different shell was the very
definition of the word "you".  But don't feel bad; some of the
thimbleriggers around here are quite accomplished, and very hard to
catch out.

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


Re: Qt and progressBar - how to update

2010-05-16 Thread OMS
On 16 Maj, 20:52, Robert Kern  wrote:
> On 2010-05-16 13:28 , OMS wrote:
>
>
>
> > I am quite new to Python and Qt and need very urgently advice on how
> > to update Qt progressBar while executing a process. I have went thrugh
> > number of 'google' stuff and saw different solution, hence none worked
> > for me. The best idea I have seen is the usage of QThread and emiting
> > signal from thread to MainWindow. I do not know however why the code I
> > have written is not working. Most likely a stupid 'beginner related'
> > error but as far as I am beginner I can't get it. There is a code
> > below:
>
> > #!/opt/local/bin/python2.6
>
> > import os
> > import sys
> > import time
> > from PyQt4 import QtCore
> > from PyQt4 import QtGui
>
> > from uiTest import Ui_MainWindow
>
> > class MainWindow(QtGui.QMainWindow):
> >      def __init__(self):
> >          QtGui.QMainWindow.__init__(self)
> >          self.ui=Ui_MainWindow()
> >          self.ui.setupUi(self)
> >          self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
> > self.runWorker)
>
> >      def runWorker(self):
> >          self.worker = Worker()
> >          self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
> > self.updateWorkerProgress)
> >          self.worker.start()
>
> >      def updateWorkerProgress(self, min, max, progress):
> >          self.ui.progressBar.setMinimum = min
> >          self.ui.progressBar.setMaximum = max
> >          self.ui.progressBar.setValue = progress
>
> These should be
>
> self.ui.progressBar.setMinimum(min)
> self.ui.progressBar.setMaximum(max)
> self.ui.progressBar.setValue(progress)
>
> --
> Robert Kern

Thanks. You have saved the day. I knew it must be something only
greenhorn could do.

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


Re: Access to comp.lang.python

2010-05-16 Thread Vincent Davis
I have no problem with threads
Using gmail in a browser.
That said I like how google groups handles email.
I am also ways having to fix the reply on this list to send back to the list
and not to the list and the last author. If someone knows a way to fix that
I would be happy to hear it.

Vincent


On Sat, May 15, 2010 at 4:34 PM, cjw  wrote:

> This isn't about Python but I'm seeking suggestions as to the best way to
> access the newsgroup.
>
> It seems that messages are coming from a number of sources, such as gmane
> and google groups.
>
> The problem is that many messages seem to get unlinked from their threads.
>
> I use Thunderbird 3.0.5 and wonder whether the problem lies with the merge
> process, the server or my reader.
>
> Would it be better to go to gmane, google groups or some such provider.
>
> In the past, use of Ctrl K had neatly disposed of thread that are of no
> interest.
>
> I would welcome advice.
>
> Colin W.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

  *Vincent Davis
720-301-3003 *
[email protected]
 my blog  |
LinkedIn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: imports and exec

2010-05-16 Thread Patrick Maupin
On May 16, 1:51 pm, Paul Carter  wrote:
> We are using python for our build system. Each subproject dir has a
> python script that builds it. Parent dirs have python scripts that
> recurse into their children and use exec to invoke the python scripts.
> Recently we discovered that one of the python scripts works when
> invoked directly, but fails when invoked with exec. I've created a
> very simple pair of python scripts that demonstrates the problem.
> (We're using python 2.6)
>
> Can someone explain or point to a good explanation of why this problem
> occurs?
>
> I have two python files: prim.py and sec.py.
> prim.py:
> -
> #!/usr/bin/env python
>
> ##sec2 = open('sec.py')
> ##exec sec2
>
> def invoke():
>   sec = open('sec.py')
>   exec sec
>
> invoke()
> --
>
> and sec.py:
> --
> import sys
>
> def sec():
>   print('Inside sec(): ' +  str(sys.argv))
>
> print('Outside sec(): ' + str(sys.argv))
> sec()
> --
>
> When I run prim.py, I get an error:
> 
> Outside sec(): ['./prim.py']
> Traceback (most recent call last):
>   File "./prim.py", line 10, in 
>     invoke()
>   File "./prim.py", line 8, in invoke
>     exec sec
>   File "sec.py", line 7, in 
>     sec()
>   File "sec.py", line 4, in sec
>     print('Inside sec(): ' +  str(sys.argv))
> NameError: global name 'sys' is not defined
> --
>
> I don't understand why the sys import is not visible in the sec()
> function. I can fix this by adding a:
>   global sys
> or
>   import sys
> inside the sec() function. But I would like to understand why this is
> necessary, especially since sys is visible in sec.py outside of the
> sec() function. I found this page discussing exec
>
> http://docs.python.org/reference/executionmodel.html
>
> but I'm afraid I couldn't quite follow it. It makes me think that a
> free variable is involved, but I don't see how. It did made me try
> invoking exec in prim.py outside of the invoke() function (see the
> commented out code). Everything worked fine when I did that.
>
> Can someone set me straight? Suggestions on avoiding this problem are
> welcome as well!
>
> Thanks in advance.

Yes.  Since you did not pass any dictionaries to your exec of "sec",
sec inherited the globals and locals from the calling function.  So
the import of sys happened in that functions locals (bad practice in
any case) and the globals used by sec() are the globals of your main
module.

Especially if invoked from inside a function, you should always pass a
dict to exec.  Just "exec sec() in {}" will do the trick.  But if you
want to use your caller's dictionaries, you can do "exec sec() in
globals()"  But you should *not* use a functions locals directly if
you are going to modify them (as you are currently doing).

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


global variables in imported modules

2010-05-16 Thread vsoler
Taken from www.python.org, FAQ 2.3 How do I share global variables
across modules?

config.py:

x = 0   # Default value of the 'x' configuration setting


mod.py:

import config
config.x = 1


main.py:

import config   # try removing it
import mod
print config.x

The example, such as shown in the website, works perfectly well.
However, I don't fully understand why I have to import config in
main.py, since it has already been imported by mod.py.

As the website explains, there is only one module namespace for each
module, and mod.py has aleady created the config namespace by
importing it. Why should I import it again in main.py if that
namespace already exists?

If I remove ->   import config   # try removing it in main.py,
the application does not run

What am I missing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global variables in imported modules

2010-05-16 Thread Patrick Maupin
On May 16, 4:42 pm, vsoler  wrote:
> Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0   # Default value of the 'x' configuration setting
>
> mod.py:
>
> import config
> config.x = 1
>
> main.py:
>
> import config       # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.
>
> As the website explains, there is only one module namespace for each
> module, and mod.py has aleady created the config namespace by
> importing it. Why should I import it again in main.py if that
> namespace already exists?
>
> If I remove ->   import config       # try removing it     in main.py,
> the application does not run
>
> What am I missing?

What you are missing is that the interpreter has to look *inside* a
namespace in order to actually find the object associated with a
name.  As you found out, there is a namespace per module.  So
main.py's namespace is where the code in main.py will search for
variables.  If 'mod' imports config, then the 'mod' module's namespace
is updated with 'config' -> the config module.  But the act of 'mod'
importing 'config' will not alter the namespace of 'main' at all.  So
if you want to access variable 'x' inside 'config' from main you can
either import config directly into main and access it as config.x, or
you can import config into mod and import mod into main and access it
as mod.config.x.

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


Re: global variables in imported modules

2010-05-16 Thread Rhodri James

On Sun, 16 May 2010 22:42:40 +0100, vsoler  wrote:


Taken from www.python.org, FAQ 2.3 How do I share global variables
across modules?

config.py:

x = 0   # Default value of the 'x' configuration setting


mod.py:

import config
config.x = 1


main.py:

import config   # try removing it
import mod
print config.x

The example, such as shown in the website, works perfectly well.
However, I don't fully understand why I have to import config in
main.py, since it has already been imported by mod.py.


Globals are only global to a module.  As you can see above, they
don't magically appear in the namespace of the module you import
them into (not unless you do something careless like "from config
import *", at which point you deserve all the confusion you're
going to get).  In both mod.py and main.py you get at the global
x through its module: config.x

Now as you say, main.py imports mod.  In exactly the same way as
mod imports config.  *Exactly*.  We get at the contents of mod
(the things in its namespace) in the same way: mod.thing.  When
mod imports config it imports it into its own namespace only;
there is no magic that makes it appear in the namespace of anything
importing mod any more than happens for anything else.

If you want to access config in main.py without importing it
directly because you know that (in this case) mod has already
imported it, you have to access it through the module that did
the importing.  Instead of "config.x", in main it would be
"mod.config.x".

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: global variables in imported modules

2010-05-16 Thread vsoler
On 17 mayo, 00:05, Patrick Maupin  wrote:
> On May 16, 4:42 pm, vsoler  wrote:
>
>
>
> > Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> > across modules?
>
> > config.py:
>
> > x = 0   # Default value of the 'x' configuration setting
>
> > mod.py:
>
> > import config
> > config.x = 1
>
> > main.py:
>
> > import config       # try removing it
> > import mod
> > print config.x
>
> > The example, such as shown in the website, works perfectly well.
> > However, I don't fully understand why I have to import config in
> > main.py, since it has already been imported by mod.py.
>
> > As the website explains, there is only one module namespace for each
> > module, and mod.py has aleady created the config namespace by
> > importing it. Why should I import it again in main.py if that
> > namespace already exists?
>
> > If I remove ->   import config       # try removing it     in main.py,
> > the application does not run
>
> > What am I missing?
>
> What you are missing is that the interpreter has to look *inside* a
> namespace in order to actually find the object associated with a
> name.  As you found out, there is a namespace per module.  So
> main.py's namespace is where the code in main.py will search for
> variables.  If 'mod' imports config, then the 'mod' module's namespace
> is updated with 'config' -> the config module.  But the act of 'mod'
> importing 'config' will not alter the namespace of 'main' at all.  So
> if you want to access variable 'x' inside 'config' from main you can
> either import config directly into main and access it as config.x, or
> you can import config into mod and import mod into main and access it
> as mod.config.x.
>
> Regards,
> Pat

Thank you Pat, it's very clear.

However, can I be 100% sure that,no matter how I access variable
'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
that either reference of 'x' points to the same id(memory position)?

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


Re: global variables in imported modules

2010-05-16 Thread James Mills
On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> However, can I be 100% sure that,no matter how I access variable
> 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> that either reference of 'x' points to the same id(memory position)?

Yes it does unless you re-assign it.

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


Re: global variables in imported modules

2010-05-16 Thread vsoler
On 17 mayo, 00:38, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James

Understood, thank you very much

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


Re: global variables in imported modules

2010-05-16 Thread Patrick Maupin
On May 16, 5:38 pm, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James


To expand a bit on what James is saying:

If, for example, inside your main module, you got tired of typing
"mod.config.x" everywhere you were using it, and decided that you
could make a local reference to the same variable:

x = mod.config.x

Now, whenever you use just plain x inside the main module, you are
also referencing the exact same object, *until* some other function
decides to do:

mod.config.x = y

At this point in time, the 'x' inside main references the object that
mod.config.x originally referenced, but mod.config.x now references a
different object.

Unlike C, for example, where the assignment operator physically places
an item into a specific memory location (either fixed globally or
within a stack frame), the assignment operator in python simply stores
a key/value pair into a namespace dictionary.  So whenever you
retrieve a value from the dictionary using that key, you will get the
value that was last associated with that key.

So, 'mod.config.x' will first retrieve the object associated with the
key 'mod' from the main module's namespace dictionary, then will
retrieve the object associated with the key 'config' from that
module's namespace dictionary, then will retrieve the object
associated with the key 'x' from that module's namespace dictionary.
Unless you later modify any of those key/value pairs, subsequent
retrieval will always result in the same final value.

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


A couple questions about classes and inheritance

2010-05-16 Thread Paul LaFollette
Kind people,
Using Python 3.1

I have been poking around trying to get more insight into Python's
innards, and I have a couple of (marginally) related questions.

First, I've looked a fair bit and can't find how one can find the base
classes of a subclass?  isinstance and issubclass sort of do the
opposite of what I want.  Surely somewhere there is something like

MyThingee.something.orOther.baseClasses()

that returns a tuple of the parents?  If there is, can you point me to
the appropriate documentation?

Second,
I can subclass most builtin things like int and float and list and so
on, and then override operators to play Twilight Zone if I am so
inclined.

  But what happens if I try to subclass function?

First attempt:
>>>
>>> class MyFunction(function):
...   pass
...
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>>

OK.. so second attempt:


>>>
>>> def a():
...   pass
...
>>> a

>>> function
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>> function=type(a)
>>> function

>>>
>>> class MyFunction(function):
...   pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'function' is not an acceptable base type
>>>

So, it appears that function is perhaps the equivalent of a Java final
class? Or isn't really a class at all but something that "looks like"
a class?

Anyway, again can you point me to somewhere that I can learn more?  In
particular, is there a list somewhere of the builtin types that are
not subclassable?

I'm willing to root through the source code if that is what I need to
do, but even there (especially there) a hint as to where to start
looking would be helpful.

Thank you in advance,
Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A couple questions about classes and inheritance

2010-05-16 Thread Christian Heimes

First, I've looked a fair bit and can't find how one can find the base
classes of a subclass?  isinstance and issubclass sort of do the
opposite of what I want.  Surely somewhere there is something like

MyThingee.something.orOther.baseClasses()


You can get the direct parents of a class with the attribute __bases__. 
The class attribute __mro__ returns a tuple of for the method resolution 
order. But instead of poking around yourself I suggest you use the 
inspect module. It provides a high level interface.



class Example:

... pass
...

Example.__bases__

(,)

Example.__mro__

(, )



   But what happens if I try to subclass function?

First attempt:


class MyFunction(function):

   pass

Traceback (most recent call last):
   File "", line 1, in
NameError: name 'function' is not defined


There is no object called function in the list of builtins. You can't 
subclass from function anyway so there is no point in accessing the 
function object. If you want to create some callable class you have to 
provide a method call "__call__". It's called when you call the 
instances of your class like a function.



def a():

... pass
...

type(a)



function = type(a)
class MyFunc(function):

... pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'function' is not an acceptable base type


Anyway, again can you point me to somewhere that I can learn more?  In
particular, is there a list somewhere of the builtin types that are
not subclassable?


I don't think it's documented anyway. You have to try yourself. In 
general you don't have to subclass builtin types. Some classes are 
tricky to subclass like e.g. immutable classes (str, bytes) or dict.


Christian

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


Re: global variables in imported modules

2010-05-16 Thread vsoler
On 17 mayo, 00:52, Patrick Maupin  wrote:
> On May 16, 5:38 pm, James Mills  wrote:
>
> > On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > > However, can I be 100% sure that,no matter how I access variable
> > > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > > that either reference of 'x' points to the same id(memory position)?
>
> > Yes it does unless you re-assign it.
>
> > --James
>
> To expand a bit on what James is saying:
>
> If, for example, inside your main module, you got tired of typing
> "mod.config.x" everywhere you were using it, and decided that you
> could make a local reference to the same variable:
>
> x = mod.config.x
>
> Now, whenever you use just plain x inside the main module, you are
> also referencing the exact same object, *until* some other function
> decides to do:
>
> mod.config.x = y
>
> At this point in time, the 'x' inside main references the object that
> mod.config.x originally referenced, but mod.config.x now references a
> different object.
>
> Unlike C, for example, where the assignment operator physically places
> an item into a specific memory location (either fixed globally or
> within a stack frame), the assignment operator in python simply stores
> a key/value pair into a namespace dictionary.  So whenever you
> retrieve a value from the dictionary using that key, you will get the
> value that was last associated with that key.
>
> So, 'mod.config.x' will first retrieve the object associated with the
> key 'mod' from the main module's namespace dictionary, then will
> retrieve the object associated with the key 'config' from that
> module's namespace dictionary, then will retrieve the object
> associated with the key 'x' from that module's namespace dictionary.
> Unless you later modify any of those key/value pairs, subsequent
> retrieval will always result in the same final value.
>
> Regards,
> Pat

Really interesting, it helps a lot.

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


Re: A couple questions about classes and inheritance

2010-05-16 Thread Steven D'Aprano
On Sun, 16 May 2010 18:58:45 -0400, Paul LaFollette wrote:

> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass?

subclass.__base__
subclass.__bases__
subclass.__mro__

(The third one stands for "Method Resolution Order".)


See also the inspect module.



> So, it appears that function is perhaps the equivalent of a Java final
> class? Or isn't really a class at all but something that "looks like" a
> class?

No, it really is a class, at least as far as Python is concerned:

>>> type(lambda: None)

>>> type(type(lambda: None))


but as you've discovered, it's also special. Unfortunately I can't find 
any explanation of *why* (other than the obvious that subclassing doesn't 
work).



> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are not
> subclassable?


I don't believe so. Apart from intellectual curiosity, is there any 
reason you need to know?


This may be helpful:

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

You can also google for the error message, although in my few minutes of 
searching I've only found people demonstrating the failure and not 
explaining it.

Here's a rather long discussion about subclassing function:

http://mail.python.org/pipermail/python-list/2008-March/531661.html

but again, no explanation of why type(function) isn't subclassable.




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


Re: A couple questions about classes and inheritance

2010-05-16 Thread Carl Banks
On May 16, 4:17 pm, Christian Heimes  wrote:
> > First, I've looked a fair bit and can't find how one can find the base
> > classes of a subclass?  isinstance and issubclass sort of do the
> > opposite of what I want.  Surely somewhere there is something like
>
> > MyThingee.something.orOther.baseClasses()
>
> You can get the direct parents of a class with the attribute __bases__.
> The class attribute __mro__ returns a tuple of for the method resolution
> order. But instead of poking around yourself I suggest you use the
> inspect module. It provides a high level interface.
>
> >>> class Example:
>
> ...     pass
> ...>>> Example.__bases__
> (,)
> >>> Example.__mro__
>
> (, )
>
> >    But what happens if I try to subclass function?
>
> > First attempt:
>
>  class MyFunction(function):
> >        pass
> > 
> > Traceback (most recent call last):
> >    File "", line 1, in
> > NameError: name 'function' is not defined
>
> There is no object called function in the list of builtins. You can't
> subclass from function anyway so there is no point in accessing the
> function object. If you want to create some callable class you have to
> provide a method call "__call__". It's called when you call the
> instances of your class like a function.
>
> >>> def a():
>
> ...     pass
> ...>>> type(a)
> 
> >>> function = type(a)
> >>> class MyFunc(function):
>
> ...     pass
> ...
> Traceback (most recent call last):
>    File "", line 1, in 
> TypeError: type 'function' is not an acceptable base type
>
> > Anyway, again can you point me to somewhere that I can learn more?  In
> > particular, is there a list somewhere of the builtin types that are
> > not subclassable?
>
> I don't think it's documented anyway. You have to try yourself. In
> general you don't have to subclass builtin types. Some classes are
> tricky to subclass like e.g. immutable classes (str, bytes) or dict.


It's not a list, but you can tell if a given type is subclassable by
testing bit 10 of the __flags__ attribute:

type(lambda:0).__flags__ & 1024  ->  0
int.__flags__ & 1024  ->  1024


The reason some types are not subclassable is simply because there's
more involved to write a type at the C level that's subclassable.  For
a lot of types the work wasn't considered worth it.


If you think you want to subclass function, consider whether you can
do what you want with decorator syntax.


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


Re: A couple questions about classes and inheritance

2010-05-16 Thread Terry Reedy

On 5/16/2010 6:58 PM, Paul LaFollette wrote:


Anyway, again can you point me to somewhere that I can learn more?  In
particular, is there a list somewhere of the builtin types that are
not subclassable?


I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code.


Terry Jan Reedy

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


Re: Global variables for python applications

2010-05-16 Thread John Nagle

James Mills wrote:

The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.


   Python really ought to have named constants.

   For one thing, it's fine to share constants across threads, while
sharing globals is generally undesirable.  Also, more compile-time
arithmetic becomes possible.

   Python does have a few built-in named unassignable constants:
"True", "None", "__debug__", etc.  "Ellipsis" is supposed to be a
constant, too, but in fact you can assign to it, at least through Python 3.1.

   I think there's some religious objection to constants in Python, but
it predated threading.

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


tone generation for motherboard and sound card speakers?

2010-05-16 Thread Alex Hall
Hi all,
I am wondering if there is a way to generate a tone for the
motherboard speaker, like the call to Beep() in C++?

Also, is there a module to generate tones in Python using the sound
card? A module that can beep at a given frequency for a given time
using the usual sine wave is okay, but the fancier the better
(different waves, sweeping, and so on).

My final question will likely hinge upon the answer to the second
question, but is there a way to play a tone in a given position in the
stereo field? For example, I have a Battleship tactical board (my name
for where the little red and white pins go) which I am trying to
sonify using different tones for each status (not fired on, ship
sighted, ship hit, ship sunk). I want each row to play, from top to
bottom, but each square in each row should start at the left and
continue to the last square playing in the right speaker, giving the
user a better idea of where each square is. Oh, this is for blind
users, in case you were wondering why anyone would want to sonify a
battleship board.
Thanks for any information, and note that I am using Python2.6; unless
there is an easy way to use a module meant for 2.5 or before inside a
2.6 project, I would need a 2.6 module.

-- 
Have a great day,
Alex (msg sent from GMail website)
[email protected]; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A couple questions about classes and inheritance

2010-05-16 Thread Mark Young
You can't subclass Ellipsis.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables for python applications

2010-05-16 Thread James Mills
On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
>   For one thing, it's fine to share constants across threads, while
> sharing globals is generally undesirable.  Also, more compile-time
> arithmetic becomes possible.
>
>   Python does have a few built-in named unassignable constants:
> "True", "None", "__debug__", etc.  "Ellipsis" is supposed to be a
> constant, too, but in fact you can assign to it, at least through Python
> 3.1.
>
>   I think there's some religious objection to constants in Python, but
> it predated threading.

To be honest, classes work just fine for defining constants.
(Though in my own code I use ALL UPPER CASE variables as it the style).

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


Re: Global variables for python applications

2010-05-16 Thread Steven D'Aprano
On Mon, 17 May 2010 13:34:57 +1000, James Mills wrote:

> On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
>>   For one thing, it's fine to share constants across threads, while
>> sharing globals is generally undesirable.  Also, more compile-time
>> arithmetic becomes possible.
>>
>>   Python does have a few built-in named unassignable constants:
>> "True", "None", "__debug__", etc.  "Ellipsis" is supposed to be a
>> constant, too, but in fact you can assign to it, at least through
>> Python 3.1.
>>
>>   I think there's some religious objection to constants in Python, but
>> it predated threading.
> 
> To be honest, classes work just fine for defining constants. (Though in
> my own code I use ALL UPPER CASE variables as it the style).


In what way are they constant? Can you not modify them and rebind them?


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


Re: Picking a license

2010-05-16 Thread Aahz
In article <[email protected]>,
Ben Finney   wrote:
>[email protected] (Aahz) writes:
>>
>> You can't really sell Open Source software in any practical way;
>> someone will always undercut you once it's out in the wild. You can
>> only sell support for the software, which is entirely different.
>
>Not at all. I've been selling all the software I write for clients for
>the past ten years, and it's all free software. It's been very practical
>for me and those I've worked with.
>
>You can't sell free software like selling loaves of bread, but that's a
>much more limited case and a far cry from your claim. Selling free
>software is quite practical and a good way to fund development of
>software that otherwise wouldn't be written as free software.

>From my POV, if you're not selling COTS, you're really selling support
and consulting services, because that's what keeps your competitors from
just picking up your software and reselling it for cheaper.  BTDT.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables for python applications

2010-05-16 Thread Steven D'Aprano
On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:

> James Mills wrote:
>> The only place global variables are considered somewhat "acceptable"
>> are as constants in a module shared as a static value.
> 
> Python really ought to have named constants.

+1

Unfortunately, it will most likely require new syntax, and semantics. 
While the concept of a constant is pretty straightforward for immutable 
types like ints and strings, what about mutable types?

And then there's the moratorium, so even if we had agreement on semantics 
and syntax, and a patch, it couldn't be deployed for a few years.



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


Re: tone generation for motherboard and sound card speakers?

2010-05-16 Thread Jake b
For sound ( not internal beep ) you can check out:

   - pygame: http://www.pygame.org/project-PygSoundTestTest-1453-.html
   - python.org/sound : http://wiki.python.org/moin/PythonInMusic
   - pk http://trac2.assembla.com/pkaudio/
   - pureData http://puredata.info/Members/thomas/py



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


Re: Global variables for python applications

2010-05-16 Thread James Mills
On Mon, May 17, 2010 at 2:24 PM, Steven D'Aprano
 wrote:
> In what way are they constant? Can you not modify them and rebind them?

It's just style/convention :)
Much like _ to denote private variables and methods!

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


Re: an element from a set

2010-05-16 Thread Carl Banks
On May 14, 11:52 pm, Chris Rebert  wrote:
> On Fri, May 14, 2010 at 11:23 PM, Carl Banks  wrote:
> > On May 14, 9:39 am, Terry Reedy  wrote:
> >> On 5/14/2010 11:24 AM, gerardob wrote:
> >> > Hello, let S be a python set which is not empty
> >> > (http://docs.python.org/library/sets.html)
>
> >> > i would like to obtain one element (anyone, it doesn't matter which one) 
> >> > and
> >> > assign it to a variable.
>
> >> > How can i do this?
>
> >> Depends on whether or not you want the element removed from the set
>
> >> #3.1
> >>  >>> s=set(range(10))
> >>  >>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> >>  >>> x=next(iter(s))
> >>  >>> x
> >> 0
> >>  >>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> >>  >>> x = s.pop()
> >>  >>> x
> >> 0
> >>  >>> s
> >> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>
> >> The choice of 0 is an implementation artifact. It could have been any
> >> member.
>
> > Which brings up an interesting question: how do you get a random
> > element from a set?
>
> > random.choice(list(s))
>
> > is the most straightforward way and will work a lot of the time, but
> > how would you avoid creating the list?  I can't think of a way off
> > hand.
>
> def random_set_elem(s):
>     iterator = iter(s)
>     n = random.randint(0, len(s)-1)
>     for i in xrange(n):
>         next(iterator)
>     return next(iterator)
>
> Avoids creating the list, but it's still O(M). If you're gonna pick
> multiple times from the same set, you're better off just converting it
> to a list.

I've never had to do it (at least not in any situations where I had
any reluctance to call list on it), but it seems like a fairly bad
limitation.  Random element from a set is such a natural idea.

Even if we were to modify the set type at the C level to support it, I
can't think of an easy way to get a random element without selection
bias.  For instance, if you start from a random hash code, some
elements are more likely to be selected than others, depending on
distance between entries in the hash table.  You'd probably have to
choose an number in range(len(s)) and count off that many, but then
might as well have just converted it to a list or used an iterator.  A
little disappointing, actually.

Probably the "right" way is to use a binary-tree-based set.


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


Re: an element from a set

2010-05-16 Thread Steven D'Aprano
On Sun, 16 May 2010 21:53:21 -0700, Carl Banks wrote:

> I've never had to do it (at least not in any situations where I had any
> reluctance to call list on it), but it seems like a fairly bad
> limitation.  Random element from a set is such a natural idea.

There was a long discussion on the Python-Dev mailing list about that. As 
I recall, there was no consensus about this, and the moratorium hit, so 
as far as I can tell it went absolutely nowhere.

The thread started here:

http://mail.python.org/pipermail/python-dev/2009-October/093227.html

and there was a patch here:

http://mail.python.org/pipermail/python-dev/2009-October/093228.html




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