Avoiding defunct processes

2012-11-01 Thread Richard
Hello,

I create child processes with subprocess.Popen().
Then I either wait for them to finish or kill them.
Either way these processes end up as defunct until the parent process
completes:
$ ps e
6851 pts/5Z+ 1:29 [python] 

This confuses another library as to whether the processes are
complete.
For now I detect which processes are defunct by parsing the output of
"ps".
What would you recommend? I am hoping there is a cleaner way.

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


Generate unique ID for URL

2012-11-13 Thread Richard
Hello,

I want to create a URL-safe unique ID for URL's.
Currently I use:
url_id = base64.urlsafe_b64encode(url)

>>> base64.urlsafe_b64encode('docs.python.org/library/uuid.html')
'ZG9jcy5weXRob24ub3JnL2xpYnJhcnkvdXVpZC5odG1s'

I would prefer more concise ID's. 
What do you recommend? - Compression?

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


Re: Generate unique ID for URL

2012-11-13 Thread Richard
Good point - one way encoding would be fine.

Also this is performed millions of times so ideally efficient.


On Wednesday, November 14, 2012 10:34:03 AM UTC+11, John Gordon wrote:
> In <0692e6a2-343c-4eb0-be57-fe5c815ef...@googlegroups.com> Richard 
>  writes:
> 
> 
> 
> > I want to create a URL-safe unique ID for URL's.
> 
> > Currently I use:
> 
> > url_id = base64.urlsafe_b64encode(url)
> 
> 
> 
> > >>> base64.urlsafe_b64encode('docs.python.org/library/uuid.html')
> 
> > 'ZG9jcy5weXRob24ub3JnL2xpYnJhcnkvdXVpZC5odG1s'
> 
> 
> 
> > I would prefer more concise ID's. 
> 
> > What do you recommend? - Compression?
> 
> 
> 
> Does the ID need to contain all the information necessary to recreate the
> 
> original URL?
> 
> 
> 
> -- 
> 
> John Gordon   A is for Amy, who fell down the stairs
> 
> gor...@panix.com  B is for Basil, assaulted by bears
> 
> -- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Generate unique ID for URL

2012-11-13 Thread Richard
These URL ID's would just be used internally for quick lookups, not exposed 
publicly in a web application.

Ideally I would want to avoid collisions altogether. But if that means 
significant extra CPU time then 1 collision in 10 million hashes would be 
tolerable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate unique ID for URL

2012-11-13 Thread Richard
I found md5 / sha 4-5 times slower than hash. And base64 a lot slower.

No database or else I would just use their ID.


On Wednesday, November 14, 2012 11:59:55 AM UTC+11, Christian Heimes wrote:
> Am 14.11.2012 01:41, schrieb Richard Baron Penman:
> 
> > I found the MD5 and SHA hashes slow to calculate.
> 
> > The builtin hash is fast but I was concerned about collisions. What
> 
> > rate of collisions could I expect?
> 
> 
> 
> Seriously? It takes about 1-5msec to sha1() one MB of data on a modern
> 
> CPU, 1.5 on my box. The openssl variants of Python's hash code release
> 
> the GIL so you use the power of all cores.

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


Re: Generate unique ID for URL

2012-11-13 Thread Richard
I am dealing with URL's rather than integers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate unique ID for URL

2012-11-13 Thread Richard
So the use case - I'm storing webpages on disk and want a quick retrieval 
system based on URL. 
I can't store the files in a single directory because of OS limitations so have 
been using a sub folder structure.
For example to store data at URL "abc": a/b/c/index.html
This data is also viewed locally through a web app.

If you can suggest a better approach I would welcome it. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate unique ID for URL

2012-11-13 Thread Richard
> The next step is to reduce the number of bits you are encoding.  You 
> 
> said in another post that "1 collision in 10 million hashes would be 
> 
> tolerable".  So you need:
> 
> 
> 
> >>> math.log(10*1000*1000, 2)
> 
> 23.25349666421154


I think a difficulty would be finding a hash algorithm that maps evenly across 
those bits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate unique ID for URL

2012-11-13 Thread Richard
thanks for pointer to Varnish. 

I found MongoDB had a lot of size overhead so that it ended up using 4x the 
data stored. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generate unique ID for URL

2012-11-13 Thread Richard
yeah good point - I have gone with md5 for now.


On Wednesday, November 14, 2012 3:06:18 PM UTC+11, Chris Angelico wrote:
> On Wed, Nov 14, 2012 at 2:25 PM, Richard  wrote:
> 
> > So the use case - I'm storing webpages on disk and want a quick retrieval 
> > system based on URL.
> 
> > I can't store the files in a single directory because of OS limitations so 
> > have been using a sub folder structure.
> 
> > For example to store data at URL "abc": a/b/c/index.html
> 
> > This data is also viewed locally through a web app.
> 
> >
> 
> > If you can suggest a better approach I would welcome it.
> 
> 
> 
> The cost of a crypto hash on the URL will be completely dwarfed by the
> 
> cost of storing/retrieving on disk. You could probably do some
> 
> arithmetic and figure out exactly how many URLs (at an average length
> 
> of, say, 100 bytes) you can hash in the time of one disk seek.
> 
> 
> 
> ChrisA

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


Re: Generate unique ID for URL

2012-11-14 Thread Richard
thanks for perspective!
-- 
http://mail.python.org/mailman/listinfo/python-list


Help needed with nested parsing of file into objects

2012-06-04 Thread richard
Hi guys i am having a bit of dificulty finding the best approach /
solution to parsing a file into a list of objects / nested objects any
help would be greatly appreciated.

#file format to parse .txt
[code]
An instance of TestArray
 a=a
 b=b
 c=c
 List of 2 A elements:
  Instance of A element
   a=1
   b=2
   c=3
  Instance of A element
   d=1
   e=2
   f=3
 List of 1 B elements
  Instance of B element
   a=1
   b=2
   c=3
   List of 2 C elements
Instance of C element
 a=1
 b=2
 c=3
Instance of C element
 a=1
 b=2
 c=3

An instance of TestArray
 a=1
 b=2
 c=3
[/code]

expected output
list of 2 TestArray objects been the parents the first one having an
attribute holding a list of the 2 instance of A objects the parents
children, another
attribute of the parent holding a list of just the 1 child instance of
B object with the child object then containing an attribute holding a
list of the 2 Instance of C objects
but the nesting could be more this is just an example. The instance of
TestArray may or may not have any nesting at all
this is illustrated in the second TestArray. Basically just want to
create a list of objects with the objects may or may not contain more
nested objects as attributes but
need a generic way to do it that would work for any amount of depth.

#end list of objects with objects printed as dicts

[code]
parsed = [
{
  "a":"a",
  "b":"b",
  "c":"c",
  "A_elements":[
  {
"a":1,
"b":2,
"c":3
  },
  {
 "a":1,
 "b":2,
 "c":3
  }
   ],
  "B_elements":[
  {
"a":1,
"b":2,
"c":3,
"C_elements":[
 {
 "a":1,
 "b":2,
 "c":3
  },
  {
  "a":1,
  "b":2,
  "c":3
  }
 ]
  }
   ]
},

{
  "a":"1",
  "b":"2",
  "c":"3",
}

]

[/code]

#this is what i have so far which works with the 2nd instance but cant
figure
out the best way to handle the multi nested objects.

[code]
import re
def test_parser(filename):
parent_stanza = None
stanzas = []

class parentStanza:
pass

fo = open(filename)

for line in fo:
line = line.strip()
if re.search("An instance of TestArray", line):
if parent_stanza:
stanzas.append(parent_stanza)
parent_stanza = parentStanza()
if parent_stanza and "=" in line:
attr, val = line.split("=")
setattr(parent_stanza, attr, val)
else:
stanzas.append(parent_stanza)
return stanzas

stanzas = test_parser("test.txt")

import pprint
for stanza in stanzas:
pprint.pprint(stanza.__dict__)
n=raw_input("paused")
[/code]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed with nested parsing of file into objects

2012-06-04 Thread richard
On Jun 4, 3:14 pm, Alain Ketterlin 
wrote:
> richard  writes:
> > Hi guys i am having a bit of dificulty finding the best approach /
> > solution to parsing a file into a list of objects / nested objects any
> > help would be greatly appreciated.
>
> > #file format to parse .txt
> > [code]
> > An instance of TestArray
> >  a=a
> >  b=b
> >  c=c
> >  List of 2 A elements:
> >   Instance of A element
>
> [...]
>
> Below is a piece of code that seems to work on your data. It builds a
> raw tree, i leave it to you to adapt and built the objects you want. The
> assumption is that the number of leading blanks faithfully denotes
> depth.
>
> As noted in another message, you're probably better off using an
> existing syntax (json, python literals, yaml, xml, ...)
>
> -- Alain.
>
> #!/usr/bin/env python
>
> import sys
> import re
>
> RE = re.compile("( *)(.*)")
> stack = [("-",[])] # tree nodes are: (head,[children])
> for line in sys.stdin:
>     matches = RE.match(line)
>     if len(matches.group(2)) > 0:
>         depth = 1 + len(matches.group(1))
>         while len(stack) > depth:
>             stack[-2][1].append(stack[-1])
>             del stack[-1]
>             pass
>         stack.append( (matches.group(2),[]) )
>         pass
>     pass
> while len(stack) > 1:
>     stack[-2][1].append(stack[-1])
>     del stack[-1]
>     pass
>
> print(stack)

thank you both for your replies. Unfortunately it is a pre-existing
file format imposed by an external system that I can't
change. Thank you for the code snippet.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 4, 3:20 pm, richard  wrote:
> On Jun 4, 3:14 pm, Alain Ketterlin 
> wrote:
>
>
>
>
>
>
>
>
>
> > richard  writes:
> > > Hi guys i am having a bit of dificulty finding the best approach /
> > > solution to parsing a file into a list of objects / nested objects any
> > > help would be greatly appreciated.
>
> > > #file format to parse .txt
> > > [code]
> > > An instance of TestArray
> > >  a=a
> > >  b=b
> > >  c=c
> > >  List of 2 A elements:
> > >   Instance of A element
>
> > [...]
>
> > Below is a piece of code that seems to work on your data. It builds a
> > raw tree, i leave it to you to adapt and built the objects you want. The
> > assumption is that the number of leading blanks faithfully denotes
> > depth.
>
> > As noted in another message, you're probably better off using an
> > existing syntax (json, python literals, yaml, xml, ...)
>
> > -- Alain.
>
> > #!/usr/bin/env python
>
> > import sys
> > import re
>
> > RE = re.compile("( *)(.*)")
> > stack = [("-",[])] # tree nodes are: (head,[children])
> > for line in sys.stdin:
> >     matches = RE.match(line)
> >     if len(matches.group(2)) > 0:
> >         depth = 1 + len(matches.group(1))
> >         while len(stack) > depth:
> >             stack[-2][1].append(stack[-1])
> >             del stack[-1]
> >             pass
> >         stack.append( (matches.group(2),[]) )
> >         pass
> >     pass
> > while len(stack) > 1:
> >     stack[-2][1].append(stack[-1])
> >     del stack[-1]
> >     pass
>
> > print(stack)
>
> thank you both for your replies. Unfortunately it is a pre-existing
> file format imposed by an external system that I can't
> change. Thank you for the code snippet.

Hi guys still struggling to get the code that was posted to me on this
forum to work in my favour and get the output in the format shown
above. This is what I have so far. Any help will be greatly
apprectiated.

output trying to achieve
parsed = [
{
  "a":"a",
  "b":"b",
  "c":"c",
  "A_elements":[
  {
"a":1,
"b":2,
"c":3
  },
  {
 "a":1,
 "b":2,
 "c":3
  }
   ],
  "B_elements":[
  {
"a":1,
"b":2,
"c":3,
"C_elements":[
 {
 "a":1,
 "b":2,
 "c":3
  },
  {
  "a":1,
  "b":2,
  "c":3
  }
 ]
  }
   ]
},

{
  "a":"1",
  "b":"2",
  "c":"3",
}

]

file format unchangeable

An instance of TestArray
 a=a
 b=b
 c=c
 List of 2 A elements:
  Instance of A element
   a=1
   b=2
   c=3
  Instance of A element
   d=1
   e=2
   f=3
 List of 1 B elements
  Instance of B element
   a=1
   b=2
   c=3
   List of 2 C elements
Instance of C element
 a=1
 b=2
 c=3
Instance of C element
 a=1
 b=2
 c=3

An instance of TestArray
 a=1
 b=2
 c=3

def test_parser(filename):
class Stanza:
def __init__(self, values):
for attr, val in values:
setattr(self, attr, val)

def build(couple):
if "=" in couple[0]:
attr, val = couple[0].split("=")
return attr,val
elif "Instance of" in couple[0]:
match = re.search("Instance of (.+) element", couple[0])
return ("attr_%s" % match.group(1),Stanza(couple[1]))
elif "List of" in couple[0]:
match = re.search("List of \d (.+) elements", couple[0])
return ("%s_elements" % match.group(1),couple[1])

fo = open(filename, "r")
RE = re.compile("( *)(.*)")
stack = [("-",[])]
for line in fo:
matches = RE.match(line)
if len(matches.group(2)) > 0:
depth = 1 + len(matches.group(1))
while len(stack) > depth:
stack[-2][1].append(build(stack[-1]))
del stack[-1]
stack.append( (matches.group(2),[]) )
while len(stack) > 1:
stack[-2][1].append(stack[-1])
del stack[-1]
return stack

stanzas = test_parser("test.txt")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 8:50 pm, Eelco  wrote:
> > thank you both for your replies. Unfortunately it is a pre-existing
> > file format imposed by an external system that I can't
> > change. Thank you for the code snippet.
>
> Hi Richard,
>
> Despite the fact that it is a preexisting format, it is very close
> indeed to valid YAML code.
>
> Writing your own whitespace-aware parser can be a bit of a pain, but
> since YAML does this for you, I would argue the cleanest solution
> would be to bootstrap that functionality, rather than roll your own
> solution, or to resort to hard to maintain regex voodoo.
>
> Here is my solution. As a bonus, it directly constructs a custom
> object hierarchy (obviously you would want to expand on this, but the
> essentials are there). One caveat: at the moment, the conversion to
> YAML relies on the appparent convention that instances never directly
> contain other instances, and lists never directly contain lists. This
> means all instances are list entries and get a '-' appended, and this
> just works. If this is not a general rule, youd have to keep track of
> an enclosing scope stack an emit dashes based on that. Anyway, the
> idea is there, and I believe it to be one worth looking at.
>
> 
> import yaml
>
> class A(yaml.YAMLObject):
>     yaml_tag = u'!A'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'A' + str(self.__dict__)
>
> class B(yaml.YAMLObject):
>     yaml_tag = u'!B'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'B' + str(self.__dict__)
>
> class C(yaml.YAMLObject):
>     yaml_tag = u'!C'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'C' + str(self.__dict__)
>
> class TestArray(yaml.YAMLObject):
>     yaml_tag = u'!TestArray'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'TestArray' + str(self.__dict__)
>
> class myList(yaml.YAMLObject):
>     yaml_tag = u'!myList'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'myList' + str(self.__dict__)
>
> data = \
> """
> An instance of TestArray
>  a=a
>  b=b
>  c=c
>  List of 2 A elements:
>   Instance of A element
>    a=1
>    b=2
>    c=3
>   Instance of A element
>    d=1
>    e=2
>    f=3
>  List of 1 B elements
>   Instance of B element
>    a=1
>    b=2
>    c=3
>    List of 2 C elements
>     Instance of C element
>      a=1
>      b=2
>      c=3
>     Instance of C element
>      a=1
>      b=2
>      c=3
> An instance of TestArray
>  a=1
>  b=2
>  c=3
> """.strip()
>
> #remove trailing whitespace and seemingly erronous colon in line 5
> lines = ['  '+line.rstrip().rstrip(':') for line in data.split('\n')]
>
> def transform(lines):
>     """transform text line by line"""
>     for line in lines:
>         #regular mapping lines
>         if line.find('=') > 0:
>             yield line.replace('=', ': ')
>         #instance lines
>         p = line.find('nstance of')
>         if p > 0:
>             s = p + 11
>             e = line[s:].find(' ')
>             if e == -1: e = len(line[s:])
>             tag = line[s:s+e]
>             whitespace= line.partition(line.lstrip())[0]
>             yield whitespace[:-2]+' -'+ ' !'+tag
>         #list lines
>         p = line.find('List of')
>         if p > 0:
>             whitespace= line.partition(line.lstrip())[0]
>             yield whitespace[:-2]+'  '+ 'myList:'
>
> ##transformed = (transform( lines))
> ##for i,t in enumerate(transformed):
> ##    print '{:>3}{}'.format(i,t)
>
> transformed = '\n'.join(transform( lines))
> print transformed
>
> res = yaml.load(transformed)
> print res
> print yaml.dump(res)
> 

Hi Eelco many thanks for the reply / solution it definitely looks like
a clean way to go about it. However installing 3rd party libs like
yaml on the server I dont think is on the cards at the moment.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 9:40 pm, Alain Ketterlin 
wrote:
> richard  writes:
>
> [I'm leaving the data in the message in case anybody has troubles going
> up-thread.]
>
>
>
>
>
>
>
>
>
> > Hi guys still struggling to get the code that was posted to me on this
> > forum to work in my favour and get the output in the format shown
> > above. This is what I have so far. Any help will be greatly
> > apprectiated.
>
> > output trying to achieve
> > parsed = [
> >     {
> >       "a":"a",
> >       "b":"b",
> >       "c":"c",
> >       "A_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3
> >           },
> >           {
> >              "a":1,
> >              "b":2,
> >              "c":3
> >           }
> >        ],
> >       "B_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3,
> >             "C_elements":[
> >                  {
> >                      "a":1,
> >                      "b":2,
> >                      "c":3
> >                   },
> >                   {
> >                       "a":1,
> >                       "b":2,
> >                       "c":3
> >                   }
> >              ]
> >           }
> >        ]
> >     },
>
> >     {
> >       "a":"1",
> >       "b":"2",
> >       "c":"3",
> >     }
>
> > ]
>
> > file format unchangeable
>
> > An instance of TestArray
> >  a=a
> >  b=b
> >  c=c
> >  List of 2 A elements:
> >   Instance of A element
> >    a=1
> >    b=2
> >    c=3
> >   Instance of A element
> >    d=1
> >    e=2
> >    f=3
> >  List of 1 B elements
> >   Instance of B element
> >    a=1
> >    b=2
> >    c=3
> >    List of 2 C elements
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
>
> > An instance of TestArray
> >  a=1
> >  b=2
> >  c=3
>
> > def test_parser(filename):
> >     class Stanza:
> >         def __init__(self, values):
> >             for attr, val in values:
> >                 setattr(self, attr, val)
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1])
>
> You forgot one case:
>
>     def build(couple):
>         if "=" in couple[0]:
>             attr, val = couple[0].split("=")
>             return attr,val
>         elif "Instance of" in couple[0]:
>             #match = re.search("Instance of (.+) element", couple[0])
>             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
>             return dict(couple[1])
>         elif "An instance of" in couple[0]: # you forgot that case
>             return dict(couple[1])
>         elif "List of" in couple[0]:
>             match = re.search("List of \d (.+) elements", couple[0])
>             return ("%s_elements" % match.group(1),couple[1])
>         else:
>             pass # put a test here
>
> >     fo = open(filename, "r")
> >     RE = re.compile("( *)(.*)")
> >     stack = [("-",[])]
> >     for line in fo:
> >         matches = RE.match(line)
> >         if len(matches.group(2)) > 0:
> >             depth = 1 + len(matches.group(1))
> >             while len(stack) > depth:
> >                 stack[-2][1].append(build(stack[-1]))
> >                 del stack[-1]
> >             stack.append( (matches.group(2),[]) )
> 

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 9:40 pm, Alain Ketterlin 
wrote:
> richard  writes:
>
> [I'm leaving the data in the message in case anybody has troubles going
> up-thread.]
>
>
>
>
>
>
>
>
>
> > Hi guys still struggling to get the code that was posted to me on this
> > forum to work in my favour and get the output in the format shown
> > above. This is what I have so far. Any help will be greatly
> > apprectiated.
>
> > output trying to achieve
> > parsed = [
> >     {
> >       "a":"a",
> >       "b":"b",
> >       "c":"c",
> >       "A_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3
> >           },
> >           {
> >              "a":1,
> >              "b":2,
> >              "c":3
> >           }
> >        ],
> >       "B_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3,
> >             "C_elements":[
> >                  {
> >                      "a":1,
> >                      "b":2,
> >                      "c":3
> >                   },
> >                   {
> >                       "a":1,
> >                       "b":2,
> >                       "c":3
> >                   }
> >              ]
> >           }
> >        ]
> >     },
>
> >     {
> >       "a":"1",
> >       "b":"2",
> >       "c":"3",
> >     }
>
> > ]
>
> > file format unchangeable
>
> > An instance of TestArray
> >  a=a
> >  b=b
> >  c=c
> >  List of 2 A elements:
> >   Instance of A element
> >    a=1
> >    b=2
> >    c=3
> >   Instance of A element
> >    d=1
> >    e=2
> >    f=3
> >  List of 1 B elements
> >   Instance of B element
> >    a=1
> >    b=2
> >    c=3
> >    List of 2 C elements
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
>
> > An instance of TestArray
> >  a=1
> >  b=2
> >  c=3
>
> > def test_parser(filename):
> >     class Stanza:
> >         def __init__(self, values):
> >             for attr, val in values:
> >                 setattr(self, attr, val)
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1])
>
> You forgot one case:
>
>     def build(couple):
>         if "=" in couple[0]:
>             attr, val = couple[0].split("=")
>             return attr,val
>         elif "Instance of" in couple[0]:
>             #match = re.search("Instance of (.+) element", couple[0])
>             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
>             return dict(couple[1])
>         elif "An instance of" in couple[0]: # you forgot that case
>             return dict(couple[1])
>         elif "List of" in couple[0]:
>             match = re.search("List of \d (.+) elements", couple[0])
>             return ("%s_elements" % match.group(1),couple[1])
>         else:
>             pass # put a test here
>
> >     fo = open(filename, "r")
> >     RE = re.compile("( *)(.*)")
> >     stack = [("-",[])]
> >     for line in fo:
> >         matches = RE.match(line)
> >         if len(matches.group(2)) > 0:
> >             depth = 1 + len(matches.group(1))
> >             while len(stack) > depth:
> >                 stack[-2][1].append(build(stack[-1]))
> >                 del stack[-1]
> >             stack.append( (matches.group(2),[

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 10:21 pm, richard  wrote:
> On Jun 5, 9:40 pm, Alain Ketterlin 
> wrote:
>
>
>
>
>
>
>
>
>
> > richard  writes:
>
> > [I'm leaving the data in the message in case anybody has troubles going
> > up-thread.]
>
> > > Hi guys still struggling to get the code that was posted to me on this
> > > forum to work in my favour and get the output in the format shown
> > > above. This is what I have so far. Any help will be greatly
> > > apprectiated.
>
> > > output trying to achieve
> > > parsed = [
> > >     {
> > >       "a":"a",
> > >       "b":"b",
> > >       "c":"c",
> > >       "A_elements":[
> > >           {
> > >             "a":1,
> > >             "b":2,
> > >             "c":3
> > >           },
> > >           {
> > >              "a":1,
> > >              "b":2,
> > >              "c":3
> > >           }
> > >        ],
> > >       "B_elements":[
> > >           {
> > >             "a":1,
> > >             "b":2,
> > >             "c":3,
> > >             "C_elements":[
> > >                  {
> > >                      "a":1,
> > >                      "b":2,
> > >                      "c":3
> > >                   },
> > >                   {
> > >                       "a":1,
> > >                       "b":2,
> > >                       "c":3
> > >                   }
> > >              ]
> > >           }
> > >        ]
> > >     },
>
> > >     {
> > >       "a":"1",
> > >       "b":"2",
> > >       "c":"3",
> > >     }
>
> > > ]
>
> > > file format unchangeable
>
> > > An instance of TestArray
> > >  a=a
> > >  b=b
> > >  c=c
> > >  List of 2 A elements:
> > >   Instance of A element
> > >    a=1
> > >    b=2
> > >    c=3
> > >   Instance of A element
> > >    d=1
> > >    e=2
> > >    f=3
> > >  List of 1 B elements
> > >   Instance of B element
> > >    a=1
> > >    b=2
> > >    c=3
> > >    List of 2 C elements
> > >     Instance of C element
> > >      a=1
> > >      b=2
> > >      c=3
> > >     Instance of C element
> > >      a=1
> > >      b=2
> > >      c=3
>
> > > An instance of TestArray
> > >  a=1
> > >  b=2
> > >  c=3
>
> > > def test_parser(filename):
> > >     class Stanza:
> > >         def __init__(self, values):
> > >             for attr, val in values:
> > >                 setattr(self, attr, val)
>
> > >     def build(couple):
> > >         if "=" in couple[0]:
> > >             attr, val = couple[0].split("=")
> > >             return attr,val
> > >         elif "Instance of" in couple[0]:
> > >             match = re.search("Instance of (.+) element", couple[0])
> > >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> > >         elif "List of" in couple[0]:
> > >             match = re.search("List of \d (.+) elements", couple[0])
> > >             return ("%s_elements" % match.group(1),couple[1])
>
> > You forgot one case:
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             #match = re.search("Instance of (.+) element", couple[0])
> >             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >             return dict(couple[1])
> >         elif "An instance of" in couple[0]: # you forgot that case
> >             return dict(couple[1])
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1]

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 10:33 pm, Alain Ketterlin 
wrote:
> richard  writes:
> >> > An instance of TestArray
> >> >  a=a
> >> >  b=b
> >> >  c=c
> >> >  List of 2 A elements:
> >> >   Instance of A element
> >> >    a=1
> >> >    b=2
> >> >    c=3
> >> >   Instance of A element
> >> >    d=1
> >> >    e=2
> >> >    f=3
> >> >  List of 1 B elements
> >> >   Instance of B element
> >> >    a=1
> >> >    b=2
> >> >    c=3
> >> >    List of 2 C elements
> >> >     Instance of C element
> >> >      a=1
> >> >      b=2
> >> >      c=3
> >> >     Instance of C element
> >> >      a=1
> >> >      b=2
> >> >      c=3
>
> [...]
>
> > Hi Alain thanks for the reply. With regards to the missing case "An
> > Instance of" im not sure where/ how that is working as the case i put
> > in originally "Instance of" is in the file and been handled in the
> > previous case.
>
> Both cases are different in your example above. Top level elements are
> labeled "An instance ...", whereas "inner" instances are labeled
> "Instance of ...".
>
> > Also when running the final solution im getting a list of [None, None]
> > as the final stack?
>
> There's only one way this can happen: by falling through to the last
> case of build(). Check the regexps etc. again.
>
> > just busy debugging it to see whats going wrong. But sorry should have
> > been clearer with regards to the format mentioned above. The objects
> > are been printed out as dicts so where you put in
>
> >         elif "An Instance of" in couple[0]:
> >             return dict(couple[1])
>
> >         should still be ?
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1])) #
> > instantiating new stanza object and setting attributes.
>
> Your last "Instance of..." case is correct, but "An instance..." is
> different, because there's no containing object, so it's probably more
> like: return Stanza(couple[1]).
>
> -- Alain.

A big thank you to everyone who has helped me tackle / shed light on
this problem it is working great. Much appreciated.

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


C++ object in PyObject*?

2011-03-15 Thread Richard
I am wondering, what is the best way to write a Python module as an
interface to a C++ class? I don't want the C++ object representing the
class to be declared as a global, because then if multiple instances
in Python would be created, they would be using the same C++ object
instance, correct?

So it seems to me that there has to be a way to create an object, and
stick it in PyObject *self, since that is passed as an argument to
each function making up the Python module.  Then, if multiple
instances of the Python object would be created, they would be
referencing different C++ objects on the back end.  Thoughts?

So something like this:
static PyObject* module_function(PyObject *self, PyObject *args) {
MyCrazyCPPObject myobj;
self.add(myobj);
return Py_Something;
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cheese shop registration error

2005-11-30 Thread richard
Todd Greenwood-Geer wrote:
> I'd like to publish to PyPI. I'm assuming that this is open to anyone.

Correct.


> REPRO:
> - - open cheeseshop reg form
> http://cheeseshop.python.org/pypi?%3Aaction=register_form
> 
> - - fill out registration form as follows:
> Username: tgreenwood
> Password: some password
> Confirm: some password (same as above)
> Email Address: [EMAIL PROTECTED]
> PGP Key ID: (see below)
> 
> - - i don't have a lot of experience with pgp, so i installed kpgp, a gui
> frontend to gnupg. i created a pgp key as follows:
> - -- install kpgp
> - -- create a new key pair for me : Todd Greenwood-Geer,
> [EMAIL PROTECTED], etc.
> - -- publish the key to hkp://subkeys.pgp.net
> - -- dblclick the new key in kpgp to get the properties dialog, copy down
> the key id, and paste that into the web field for PGP Key ID (above)
> - - submit form
> 
> Error...
> 
> There's been a problem with your request
> 
> smtplib.SMTPRecipientsRefused: {u'tgreenwoodgeer.yahoo.com': (550,
> ': Recipient address rejected: User unknown in
> local recipient table')}

The error displayed here is complaining about the email address you
supplied, 'tgreenwoodgeer.yahoo.com'. This is different from the session
details you have supplied. I can't reconcile these. I suggest you try
again, and be careful when typing your email address.


 Richard

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


Re: Zope newsgroups? Need help with POSKeyError

2004-12-31 Thread richard
Bob Horvath wrote:
> I have a Zope/Plone combination that I have been having POSKeyErrors
> with for a while now.  Are there any newsgroups that deal with Zope?

No, but there is a mailing list - see zope.org

Also, try google searching for POSKeyError.


Richard

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


Re: python without OO

2005-01-25 Thread richard
Davor wrote:

> M.E.Farmer wrote:
>> Wrap your head around Python, don't wrap the Python around your head!
>> This is NOT Java, or C++ or C , it IS Python.
> 
> that's interesting hypothesis that behavior will vary due to the use of
> different language - actually most python scripts that I have seen do
> not even use OO which is quite understandable (same with perl, php,..)
> and I'm not even sure why all these languages have incorporated OO at
> all...

Of course, *all* Python programs (whether you call them scripts or
otherwise) are using objects. Strings, numbers, files, lists,
dictionaries ... they're all objects. You *can't* write a Python program
without objects, but you can do so without a single "class" declaration.

The point that M.E.Farmer was trying to make is that you should not judge OO
by Java or C++. Those languages make OO a burden, with on the one hand
excessive requirements to subclass, and on the othe hand ... well, C++ is
just a burden all round really :)


 Richard

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


Re: move bugs from Zope BITS into Bugzilla?

2005-01-28 Thread richard
[EMAIL PROTECTED] wrote:
> I inherited a bug reporting system at work, and it's currently in Zope
> BITS (Bug Information Tracking System).  This version of BITS uses ZODB
> -- not the RDBMS version.  I would like to export all the incident
> reports from BITS to later import into Bugzilla, but as of yet I
> haven't quite figured it out.  As soon as I'm done with this, that's it
> for BITS and Zope, so I'd like to avoid writing a Zope app just for
> this.
> 
> Anyone solved this problem, or at least the part about exporting from
> BITS?  I'd hand-enter the open issues, but they also want the closed
> ones for tracking & posterity.

I'm not helping you with your problem, just plugging my own tracker ;)

Use Roundup! It's Pure Python :)

http://roundup.sf.net/



   Richard

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


Re: Marketing reST (was Re: What YAML engine do you use?)

2005-01-29 Thread richard
Aahz wrote:
> While I can see how you'd get that impression of reST, it's not true:
> like Python, reST is intended to be simpl*er* and readable, but not
> simple.  The joy of reST is that I can concentrate on writing instead of
> formatting, just as I do when writing Usenet posts.  ;-)  Even after
> using reST for a long time, I'm still constantly looking up features that
> I use rarely (such as correct formatting of URLs).
> But reST is great because it's relatively unobtrusive.  Those of us
> who've used reST to document code for a long time have gotten into the
> habit of using some reST-isms even when not writing reST: have you
> noticed the number of Pythonistas who use constructs like ``foo()``?
> Even if you didn't know it was from reST, the meaning is obvious.

And this is the core of it for me too (if you want simple, use Word).
Roundup's documentation__ (in particular the `Customisation Doc`__ which is
now huge) is entirely written in reST. It uses a fraction of the total pool
of reST constructs, but I believe the end result is perfectly legible. I
also tend to write in reST style when composing emails (a biggie for me is
starting examples with "::").

Anyway, some sample Roundup docs:

__ http://roundup.sourceforge.net/doc-0.8/index.html
__ http://roundup.sourceforge.net/doc-0.8/customizing.html


> As you say, reST can/does get messy when you're doing complicated things,
> but it stays more readable than XML/DocBook.

Indeed - I chose to use reST for Roundup's documentation for two very
important reasons:

1. lower the barrier for me to write the docs - and I am *really* happy with
how current the Roundup docs stay, because I don't feel like actually
writing them is a pain, as opposed to any sort of Markup Language format,
and
2. the first contributor of docs suggested it, and I've had several
contributors since. It's easier for contributors to write for Roundup's
documentation - even if they don't get the reST markup correct, it's
trivial to fix. This is less the case with a Markup Language.


Richard

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


Re: Ann: The first PyWeek Python Game Programming Competition

2005-07-08 Thread richard
Lee Harr wrote:
>> Clip Art
>> note:
>> more links welcome
> 
> How about:
> http://www.openclipart.org/

Thanks!


Richard (aka PyWeek organiser bunny)


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


Efficiently Split A List of Tuples

2005-07-13 Thread Richard

I have a large list of two element tuples.  I want two separate
lists: One list with the first element of every tuple, and the
second list with the second element of every tuple.

Each tuple contains a datetime object followed by an integer.

Here is a small sample of the original list:

 ((datetime.datetime(2005, 7, 13, 16, 0, 54), 315),
 (datetime.datetime(2005, 7, 13, 16, 6, 12), 313),
 (datetime.datetime(2005, 7, 13, 16, 16, 45), 312),
 (datetime.datetime(2005, 7, 13, 16, 22), 315),
 (datetime.datetime(2005, 7, 13, 16, 27, 18), 312),
 (datetime.datetime(2005, 7, 13, 16, 32, 35), 307),
 (datetime.datetime(2005, 7, 13, 16, 37, 51), 304),
 (datetime.datetime(2005, 7, 13, 16, 43, 8), 307))

I know I can use a 'for' loop and create two new lists
using 'newList1.append(x)', etc.  Is there an efficient way
to create these two new lists without using a slow for loop?

r




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


Re: Efficiently Split A List of Tuples

2005-07-14 Thread Richard
On Wed, 13 Jul 2005 20:53:58 -0400, Peter Hansen wrote:


> a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10))
> zip(*a)
> 

This seems to work.  Thanks.

Where do I find documentation on "*args"?



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


Re: Oreilly CodeZoo

2005-08-07 Thread richard
gene tani wrote:
> http://radar.oreilly.com/archives/2005/08/codezoo_program_1.html
> 
> http://python.codezoo.com/
> 
> Nice to see that python is in-demand, but what is the rationale for
> another ASPN cookbook/Parnassus / pypackage / dmoz type repository?

We (PyPI / Cheese Shop developers) are talking to the CodeZoo people about
the relationship between the two systems. Things PyPI has:

1. python setup.py register
2. python setup.py (sdist|bdist|bdist_egg|bdist_wininst|...) upload
3. http://cheeseshop.python.org/
4. better categorisation (IMO)
5. XML-RPC interface
6. 852 packages registered

The things that CodeZoo has:

1. reviews, user tips and ratings
2. a full-time editor to make sure that the reviews are reasonable
3. links to O'Reilly articles
4. a big DOWNLOAD button. hurm, that's a good idea, I should add one of
   those to the PyPI interface... I hope no-one has that patented
5. DOAP (being added to PyPI)
6. Ads in the top bar and a sidebar (hehe)

Getting links from PyPI over to the CodeZoo information would be pretty
easy. Getting links from the CodeZoo pages to PyPI information / packages
would be pretty easy.


 Richard

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


Re: Oreilly CodeZoo

2005-08-09 Thread richard
Jorge Godoy wrote:
> A subtree with version numbers could solve the problem of storing
> information for old versions when a new one is added.
> 
> With regards to 4, I'd like to see the "Topic" category in the beginning
> of the page -- this is what most people search, I guess -- and not at the
> bottom of it.

That's a good idea. Unfortunately, changing the sorting of the classifiers
will be fun. Could I ask you to submit an RFE "bug" via the link on the
pypi page?


> Also, there's a discrepancy on the amount of packages stored.  The
> categorization page says there are 679 packages.  The main page says there
> are 852.  I believe the categorization page does what I suggested and
> disregard different versions of the same software.  I think this (679) is
> the correct number.

Yep, this is related to your other comment regarding my 6th point. Also, I
don't believe packages are included in the browse if they have no
classifiers.


> Ah!  And an RSS feeder would be interesting, to know when there are new
> packages or when a package has been upgraded... ;-)

There's a top-level RSS feed, but not one per-package.


> I hope you see this as a constructive feedback from someone that has just
> screened the pages, getting to know it.

Thanks!


 Richard

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


Re: Oreilly CodeZoo

2005-08-10 Thread richard
Jorge Godoy wrote:
> richard wrote:
>> That's a good idea. Unfortunately, changing the sorting of the
>> classifiers will be fun. Could I ask you to submit an RFE "bug" via the
>> link on the pypi page?
> 
> I'll do that tomorrow morning.

Thanks!

 
>> Yep, this is related to your other comment regarding my 6th point. Also,
>> I don't believe packages are included in the browse if they have no
>> classifiers.
> 
> It means that some packages might be "lost" somewhere?  How about an
> "unclassified" classifier? :-)

No, it means that when you're browsing by classifier, the packages that
don't specify any classifiers won't match your browse specifications ;)


>> There's a top-level RSS feed, but not one per-package.
> 
> I was thinking about one per topic / classification, not per package.  It
> would be overkill to subscribe to 600+ feeds.

Hurm. Interesting idea. Could be done with a bit of work.


Richard

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


Update: Python Game Programming Challenge

2005-08-20 Thread richard
The Python Game Programming Challenge (otherwise known as PyWeek) is only a
week away from starting! Theme voting has started!

  http://www.mechanicalcat.net/tech/PyWeek/1


 Richard

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


Embedding threaded Python in C

2005-08-21 Thread Richard
I've tried embedding Python in a C app so that Threading is done in the
Python side.

In the simple example below, unless I uncomment the ALLOW_THREADS macros,
the Python thread does nothing until the C for-loop finishes. 

My real-world example is a large C/Motif application - apart from scattering
the ALLOW_THREADS macros everywhere (and what do you do while the Motif
event loop is idling?), is there a better way to get the Python threads to
run?

I'm using Python-2.4 on Linux.

--
/* app.c */

#include 
#include 

void run_worker(void)
{
  PyObject *pmod;
  PyObject *pfunc;
  PyObject *pargs;
  PyObject *pres;

  pmod = PyImport_ImportModule("Manager");
  pfunc = PyObject_GetAttrString(pmod, "run");
  pargs = Py_BuildValue("()");
  pres = PyEval_CallObject(pfunc, pargs);
  Py_DECREF(pres);
  Py_DECREF(pfunc);
  Py_DECREF(pargs);
  Py_DECREF(pmod);
} 


int main(int argc, char **argv) 
{
  int  i;

  Py_Initialize();
  PyEval_InitThreads(); 
  PySys_SetArgv(argc, argv);

  run_worker();
  
  for (i=0; i<8; i++)
  {
printf("%d main()\n", i); 

/*Py_BEGIN_ALLOW_THREADS*/
sleep(1);
/*Py_END_ALLOW_THREADS*/
  }
  
  Py_Finalize();
}

--
# Manager.py
import time
from threading import Thread, currentThread

class Worker(Thread):

def run(self):
for i in range(5):
print "Worker.run() %d [%s]" % (i, currentThread().getName())
time.sleep(1)

def run():
w = Worker()
w.start()

--


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


complex data types?

2005-09-17 Thread richard
I'd like to have an array in which the elements are various data types. 
How do I do this in Python?  

For example:

array[0].artist = 'genesis'
array[0].album = 'foxtrot'
array[0].songs = ['watcher', 'time table', 'friday']
array[1].artist = 'beatles'
array[1].album = 'abbey road'
array[1].songs = ['come', 'something', 'maxwell']

Everything I try generates errors or results in array[0].songs equaling 
array[1].songs. I feel I'm missing something obvious.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-18 Thread richard
Gustavo Picon <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> On Sat, 2005-09-17 at 23:34 -0500, Gustavo Picon wrote:
>> Maybe something like this?
>> 
>> class music(object):
>> def __init__(self):
>> self.lst = {}
>> def __setattr__(self, name, value):
>> self.__dict__[name] = value
>> 
>> array = []
>> array.append(music())
>> array.append(music())
>> 
>> # begin quoting your code
>> array[0].artist = 'genesis'
>> array[0].album = 'foxtrot'
>> array[0].songs = ['watcher', 'time table', 'friday']
>> array[1].artist = 'beatles'
>> array[1].album = 'abbey road'
>> array[1].songs = ['come', 'something', 'maxwell']
>> # end quoting your code
>> 
>> print array[0].artist
>> print array[1].artist
>> print array[0].songs
>> print array[1].songs
>> 
> 
> Actually, forget about that music class, all you need in that example
> is:
> 
> class music:
> pass

I like that.  I ended up doing:

array = []

title = 't1'
name = 'n1'
songs = ['s1', 's2']
array.append([title,name,songs])
title = 't2'
name = 'n2'
songs = ['s3', 's4']
array.append([title,name,songs])

Thank you and the other posters for the help.

Must learn not to think in c/c++. Python is much easier - no malloc's 
and pointers to fuss with :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-18 Thread richard
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> At the same time, if array[0].songs equals array[1] songs, you are
> probably initializing both array[0] and array[1] with the same object.
> Since array[0] and array[1] both refer to the same object, a change to
> one will be reflected in the other.
> 
> I hope this is what you're looking for.
> 
> Michael Loritsch

I believe that was one of the things I was doing.

thanks 

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


PyWeek 1 has completed, winners announced

2005-09-20 Thread richard
The first PyWeek Game Programming Challenge is now finished, and the results
are in: <http://www.mechanicalcat.net/tech/PyWeek/1>

I consider it a success, and I'll be running it again. I'll be making some
small changes to the challenge format (mostly to do with the theme
selection) and I'll definitely be providing more information to competitors
next time about how to compete (how to plan, etc).

Phew. And there's some cool games in there too :)

It was interesting to see that the individual entries tended to be more
innovative than the team entries.


Richard

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


Re: Testing web applications

2005-02-12 Thread richard
John J. Lee wrote:
>> > I'm looking for frameworks to make testing web applications -
> 
> Did you read the question?

To answer the original question, which I did not see when first posted:

http://www.mechanicalcat.net/tech/webunit/


Richard

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


Re: Unittesting for web applications

2005-02-12 Thread richard
Sandip Bhattacharya wrote:
> Can someone suggest me some good resources for learning how to use
> unittests for web applications? Do we always have to cook up our own
> webpage scrapers to test the code?

http://www.mechanicalcat.net/tech/webunit/


    Richard

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


Re: Python mascot proposal

2004-12-12 Thread richard
Dimitri Tcaciuc wrote:
> While I'm not absolutely positive, it looks like Python still doesn't
> have any official mascot or logo.

As already mentioned, there is a snake that gets used in a number of icons
around the place - the windows installer, for example.


> Hence, here's something I came up with 
> yesterday. Its by no means a final version, but rather just a draft to
> show an idea. Here's a link to png file.
> 
> http://www.sfu.ca/~dtcaciuc/art/pymascot.png

Very cute :)

Having said that, don't forget that Python's name has *nothing to do with
snakes*. Please consider sticking to the original roots of the language's
name: Monty Python's Flying Circus. IIRC, Guido has said a number of times
that he's not fond of using a snake for logos. Hence the MacPython stuff
uses a 16 ton weight in its icons.


Richard

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


Re: PEP 338: Executing modules inside packages with '-m'

2004-12-12 Thread richard
[EMAIL PROTECTED] wrote:
> A useful feature that is a logical extension of current '-m' behaviour.
> (I'm actually surprised it was left out in the first place)
> 
> This will definitely allow me and other python programmers to package
> our scripts better
> 
> Sounds Good to me. (-;

/me too :)


Richard

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


Re: why no python setup.py uninstall?

2004-12-12 Thread richard
Roger Binns wrote:
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> I think a little database (maybe in xml?) of installed files/modules
>> and their locations would be useful, perhaps even for a future
>> automatic download/installation/dependency-tracking thingmabob that
>> still regretably still doesn't exist as parth of the stdlib in
>> Pythonia.
> 
> Actually it does, indirectly

Sorry, missed the OP. See PEP 261 for the plans in this area:

  http://python.org/peps/pep-0262.html

combined with extensions to the setup.py metadata in:

  http://python.org/peps/pep-0314.html

Most of the design / planning has been done. All we need is some developer
time to make it happen. Go visit the Catalog SIG if you're interested.

  http://www.python.org/sigs/catalog-sig/


 Richard

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


Re: what module can do html encoder??

2004-12-12 Thread richard
Leon wrote:
> example:
> s = ' ' --->  

That's technically not HTML encoding, that's replacing a perfectly valid
space character with a *non-breaking* space character. If that's all you
want to do, then:

  s.replace(' ', ' ')

will do it. If, however, you wish to quote special HTML chars, like <, > and
&, then:

  cgi.escape(s)

will do that for you. From the library reference for "escape(
s[, quote])":

  Convert the characters "&", "<" and ">" in string s to HTML-safe
  sequences. Use this if you need to display text that might contain such
  characters in HTML. If the optional flag quote is true, the double-quote
  character (""") is also translated; this helps for inclusion in an HTML
  attribute value, as in .


 Richard

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


48-hour game programming competition only 14 days away

2005-03-31 Thread richard
The 48-Hour Game Programming Competition is a "mostly from scratch", timed,
solo coding challenge where all willing game developers spend their allowed
time making the best game they can under a common theme.

http://www.mechanicalcat.net/tech/ld48/

There have been numerous entries in the past using Python and PyGame or
PyOpenGL. Personally, I'll be using it again.

Come along, it's a hella lot of fun :)


Richard

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


pyside dynamic buttons

2011-12-13 Thread Richard
Hi,

We are making a screen with data driven buttons. I can add buttons but
can't redraw the buttons for new values. The buttuns are placed in a
frame.
I draw the buttons on the screen in a for loop:

def drawS1Butons(self):
n=0
for self.S1 in self.Org.getVpuChilds(self.Focus):
self.S1.button = QtGui.QPushButton(self.frame_2)# Add
method to the button class !?!?
self.S1.button.setGeometry(QtCore.QRect(80, n*30, 161,
23))
self.S1.button.setObjectName(self.S1.name)
 
self.S1.button.setText(QtGui.QApplication.translate("MainWindow",
self.S1.name, None, QtGui.QApplication.UnicodeUTF8))
n=n+1


How can I delete buttons?

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


Re: SVG rendering with Python

2005-12-14 Thread richard
Dennis Benzinger wrote:
> Does anybody know of a SVG rendering library for Python?

Google "python svg"


Richard

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


Re: SVG rendering with Python

2005-12-15 Thread richard
Andreas Lobinger wrote:
> richard wrote:
>> Dennis Benzinger wrote:
>>>Does anybody know of a SVG rendering library for Python?
>> Google "python svg"
> 
> ... to find what?

The answer to the OP's question.


Richard

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


Re: time.strftime() NOT producing RFC2822-compliant Date strings?

2006-01-12 Thread richard
Peter Hansen wrote:
> richard wrote:
>> I'm just dealing with a Roundup bug report in which it's pointed out that
>> time.strftime() doesn't produce RFC2822-compliant date strings when in a
>> locale other than "C".
> 
> While it doesn't fix strftime() (though a change to the docs might do
> that ), using email.Utils.formatdate() appears likely to fix your
> immediate problem, not to mention looking cleaner.

Yeah, of course I only thought of the email module *after* I hit the send
button :)

Roundup was started in the 2.0 days of Python, with 1.5.2-compatibility a
big requirement back then, so the email module hasn't really factored into
its development until "relatively recently" :)


 Richard

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


time.strftime() NOT producing RFC2822-compliant Date strings?

2006-01-12 Thread richard
I'm just dealing with a Roundup bug report in which it's pointed out that
time.strftime() doesn't produce RFC2822-compliant date strings when in a
locale other than "C".

My reading of the RFC says that indeed the only valid strings should be the
"C" locale strings:

day-name=   "Mon" / "Tue" / "Wed" / "Thu" /
"Fri" / "Sat" / "Sun"

month-name  =   "Jan" / "Feb" / "Mar" / "Apr" /
"May" / "Jun" / "Jul" / "Aug" /
"Sep" / "Oct" / "Nov" / "Dec"

and there's no mention in the RFC of locale issues. The python standard
library makes this bold claim:

  ... a format for dates compatible with that specified in the RFC 2822
  Internet email standard. 6.1 

  >>> from time import gmtime, strftime
  >>> strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
  'Thu, 28 Jun 2001 14:17:15 +'

which would appear to be true for the "C" locale but not for "pl_PL", for
example.


 Richard

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


Pygame.draw challenge

2006-06-13 Thread richard


THE CHALLENGE:

Create a game in 64kbytes of source code using only pygame. No additional 
libraries, no external files (even ones loaded from a network). That means no 
PyOpenGL, no PNGs, no OGGs.


THE DEADLINE:

Start as soon as you read this announcement.

Human-readable, Linux-compatible entries must be received by 
[EMAIL PROTECTED] before midnight on the 25th of June, 2006. That's 
Australian Eastern Standard Time, which is UTC +10.

Multiple entries are allowed. Teams are allowed. Monkeys are allowed! Ponies, 
sadly, are not allowed.


THE RESULTS:

All entries will be posted to a page on the http://www.pyweek.org/ website.

Entry gameplay instructions and license must be included in the source or in 
the game itself.

I will probably choose one of the entries as my favourite, and declare this in 
various obscure fora and private email messages. No other mention of rankings 
or favourites will be made.


THANKS:

Thanks to Phil Hassey for the challenge inspiration!

-- 
Visit the PyWeek website:
  http://www.pyweek.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


pygame.draw deadline extended to Sunday midnight UTC

2006-06-24 Thread richard
I'm not going to be awake at midnight, so that means that entrants in the 
pygame.draw challenge have a few extra hours to get their entries in.

   http://media.pyweek.org/static/pygame.draw-0606.html

Get entries to me by email before UTC (GMT) 23:59 Sunday 25th June.


Richard

-- 
Visit the PyWeek website:
  http://www.pyweek.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Pygame.draw challenge is over!

2006-06-25 Thread richard
It was quite successful too! Download the submissions from the pyweek.org 
site:

http://media.pyweek.org/static/pgd-200606.zip

Congratulations to all who participated!


Richard

-- 
Visit the PyWeek website:
  http://www.pyweek.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


PyWeek Python Game Programming Challenge, The Second!

2006-02-24 Thread richard
The date for the second PyWeek challenge has been set: Sunday 26th March
to Sunday 2nd April (00:00UTC to 00:00UTC). 

The PyWeek challenge invites entrants to write a game in one week from
scratch either as an individual or in a team. Entries must be developed
in Python, during the challenge, and must incorporate some theme chosen
at the start of the challenge.


REGISTRATION IS NOW OPEN --

To register for the challenge, visit:

   http://www.pyweek.org/

Some of the challenge website isn't finished yet. I hope to have it completed 
in the next week. This includes management of team entries.


PLANNING FOR THE CHALLENGE --

Make sure you have working versions of the libraries you're going to use.
The rules page has a list of libraries and other resources.

Make sure you can build packages to submit as your final submission (if
you're going to use py2exe, make sure you know how to use it and that it
works).

If you don't have access to Linux, Windows or a Mac to test on, contact
friends, family or other competitors to find someone who is able to test
for you.


-- 
Visit the PyWeek website:
  http://www.pyweek.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem uploading ZIP file tp PyPI

2005-05-15 Thread richard
John Machin wrote:
> Sorry in advance if this is not the correct forum ...

Quite. The support link for PyPI is in the sidebar of the site.


> I'm trying to upload what appears to be a perfectly OK zip file as a
> "source" file type to PyPI, and am getting this response:
> 
> Error...
> There's been a problem with your request
> exceptions.ValueError: invalid distribution file

The *only* valid (perfectly OK) source file to upload is a Source
Distribution as generated by the "sdist" setup.py command.


> I have managed to upload a Windows installer, and downloaded it again
> [but the download count is still stuck on zero].

The download counts are updated daily (IIRC).


Richard

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


Re: problem uploading ZIP file tp PyPI

2005-05-16 Thread richard
John Machin wrote:
> richard wrote:
>> John Machin wrote:
>> > Sorry in advance if this is not the correct forum ...
>>
>> Quite. The support link for PyPI is in the sidebar of the site.
>>
> 
> Tried that, when I was trying to register and getting strange error
> messages about the user name, like "John Machin" and "John_Machin" were
> not "ascii" [it finally permitted "sjmachin"]. The response volume
> could not be likened to that of a fire-hose.

You mean the request you put in two days ago? Sorry I've not got around to
responding yet. It was admittedly low on my priority list because you were
the only person reporting the issue (out of hundreds of successful
registrations). I will now fill in the details you've just provided (ie the
input you used which broke the interface) so that when I get around to
fixing it I'll know what I'm looking for.


> Which is precisely how the file in question was generated:
> 
> setup.py sdist --format=zip

Try without the --format arg. The code is being too paranoid.


Richard

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


Re: problem uploading ZIP file tp PyPI

2005-05-19 Thread richard
John Machin wrote:
> On Mon, 16 May 2005 22:11:49 +1000, richard
>>John Machin wrote:
>>> setup.py sdist --format=zip
>>
>>Try without the --format arg. The code is being too paranoid.
> 
> Result: (A) produces a zip file with only minor differences
> (presumably a timestamp):

Oh, so even without --format, a ZIP source dist file is produced anyway? If
this is the case, please file a bug against PyPI.


>> The code is being too paranoid
> 
> Which code (distutils or PyPI server) is being paranoid about what???

The PyPI server code, which attempts to make sure people aren't uploading
pr0n.


Richard

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


Re: problem uploading ZIP file tp PyPI

2005-05-22 Thread richard
John Machin wrote:
> I presume you mean a bug report. Done.

Thankyou.


> I wrote:
>> He wrote:
>>> I wrote:
>>>> The code is being too paranoid
>>> 
>>> Which code (distutils or PyPI server) is being paranoid about what???
>>
>> The PyPI server code, which attempts to make sure people aren't uploading
>> pr0n.
> So zip implies pr0n but exe doesn't ???

Not sure what your point is here. Are you implying that PyPI is doing
something wrong W.R.T. exe files? If you are, what are you basing that
statement on? And what would you do differently?


Richard

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


RE: problem uploading ZIP file tp PyPI

2005-05-22 Thread richard
Tony Meyer wrote:

>>>>> setup.py sdist --format=zip
>>>>
>>>> Try without the --format arg. The code is being too paranoid.
>>> 
>>> Result: (A) produces a zip file with only minor differences
>>> (presumably a timestamp):
>> 
>> Oh, so even without --format, a ZIP source dist file is
>> produced anyway? If this is the case, please file a bug against PyPI.
> 
> How is this a bug?  sdist is meant to produce a zip file on Windows if
> --format isn't used.  If "upload" overrides this for some reason, then the
> documentation should say so (and, IMO, it would be a mistake for that to
> be the case).

"bug against PyPI". Where did I say bug against distutils?


 Richard

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


Re: problem uploading ZIP file tp PyPI

2005-05-22 Thread richard
John Machin wrote:
> FYI, there are a few unreconstructed diehards out here who neither run
> on a *x platform nor run bleeding-edge Python straight out of last
> night's CVS.

I think you need to pull your head in, mate.

The bug you discovered in PyPI is plain and simple a bug in its attempts to
discover whether an uploaded ZIP file was generated by distutils.

It's a bug. It will get fixed.

Get over your damn platform paranoia.


Richard

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


RE: problem uploading ZIP file tp PyPI

2005-05-22 Thread richard
richard wrote:
> "bug against PyPI". Where did I say bug against distutils?

Apologies for the dupe response.

The bug has now been fixed.


Richard

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


Re: SMTP Test Rig ( SMTPRIG.PY v1.0 )

2005-06-11 Thread richard
Tim Williams wrote:
> After a few posts recently,  I have put together an SMTP test rig that
> will
> receive emails and either store them to a file,  write them to a console,
> or both.
> 
> Does anyone have any suggestions on where I can get it hosted  as a
> utility for general public use?

http://www.python.org/pypi


Richard

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


PyWeek 6 is coming!

2008-01-31 Thread richard
PyWeek 6 will run from 00:00 UTC on March 30th through to 00:00 UTC on April 
6th.

Registration is NOT OPEN YET. It will open on Friday 2008/02/29.

If you're new (or even coming back again) please have a look at the rules and 
help pages at http://www.pyweek.org/

The PyWeek challenge:

   1. Invites entrants to write a game in one week from scratch either as an
  individual or in a team,
   2. Is intended to be challenging and fun,
   3. Will hopefully increase the public body of game tools, code and
  expertise,
   4. Will let a lot of people actually finish a game, and
   5. May inspire new projects (with ready made teams!)

Entries must be developed in Python during the challenge, and must incorporate 
some theme decided at the start of the challenge.


-- 
Visit the PyWeek website:
  http://www.pyweek.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Python game programming challenge, NUMBER 7, in September!

2008-07-21 Thread richard
The date for the SEVENTH bi-annual PyWeek challenge has been set: Sunday 7th 
September to Sunday 14th September (00:00UTC to 00:00UTC).

  http://pyweek.org/

The PyWeek challenge invites entrants to write a game in one week from
scratch either as an individual or in a team. Entries must be developed
in Python, during the challenge, and must incorporate some theme chosen
at the start of the challenge.


REGISTRATION IS NOT YET OPEN --

In order to reduce the number of unnecessary registrations, we will open
the challenge for registration one month before the start date. See the
competition timetable and rules:

   http://www.pyweek.org/


PLANNING FOR THE CHALLENGE --

Make sure you have working versions of the libraries you're going to use.
The rules page has a list of libraries and other resources.

Make sure you know how to build an MD5 sum for your submission. See the
challenge help page for more information.

Make sure you can build packages to submit as your final submission (if
you're going to use py2exe, make sure you know how to use it and that it
works).

If you don't have access to Linux, Windows or a Mac to test on, contact
friends, family or other competitors to find someone who is able to test
for you.



-- 
Visit the PyWeek website:
  http://www.pyweek.org/
--
http://mail.python.org/mailman/listinfo/python-list


Cheese Shop: some history for the new-comers

2006-03-10 Thread richard
So I wrote PyPI back a couple of years ago. It was just a simple cgi script
and some distutils code. I needed to call it *something* and "Python
Package Index" seemed like a fairly obvious name. Unfortunately, it's also
quite a mouthful. A friend suggested "PyPI" as a good shorter name. He also
indicated that it should be pronounced "Pippy" but that never really caught
on (just a little too cutesy for most people, I suppose).

Fast-forward to PyCon 2005. PyPI sprinters in the same room as PyPy
sprinters. I think you may see where this is heading. Every now and then
someone would say "Pie Pie" too loudly in the room, and *all* heads (well,
except the Chandler folk and Brett Cannon). Something needed to be done. A
new name was needed.

For the 6 months or so following PyCon 2005 I called for new name
suggestions. Some of those are in my weblog. Some are in c.l.p archives.
There was *zero* consensus, or anything even closely resembling consensus.
So I did what people always do in this situation, I asked Barry Warsaw to
name. it. And he did, "Cheese Shop". I liked the name, so it was done. When
the new pydotorg machines went live last year, so too did the name
cheeseshop.python.org

Rejoice! No more confusing conversations with PyPy developers!


 Richard

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


PyWeek #2 one week before the fun starts!

2006-03-19 Thread richard
The PyWeek challenge invites entrants to write a game in one week from
scratch either as an individual or in a team. Entries must be developed
in Python, during the challenge, and must incorporate some theme chosen
at the start of the challenge.

PyWeek #2 runs from Sunday 26th March to Sunday 2nd April (00:00UTC to
00:00UTC).

THEME VOTING HAS STARTED  --

To register for the challenge, visit:

   http://www.pyweek.org/



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


Efficiently determine where documents differ

2010-01-04 Thread Richard
Hello,

I have been using the difflib library to find where 2 large HTML
documents differ. The Differ().compare() method does this, but it is
very slow - atleast 100x slower than the unix diff command.

How can I efficiently determine where 2 documents differ in Python?
(Ideally I am after the positions rather the actual text, which is
what SequenceMatcher().get_opcodes() returns.)

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


Re: Efficiently determine where documents differ

2010-01-05 Thread Richard
On Jan 5, 9:46 am, "Gabriel Genellina"  wrote:
> En Mon, 04 Jan 2010 19:04:12 -0300, Richard  escribió:
>
> > I have been using the difflib library to find where 2 large HTML
> > documents differ. The Differ().compare() method does this, but it is
> > very slow - atleast 100x slower than the unix diff command.
>
> Differ compares sequences of lines *and* lines as sequences of characters  
> to provide intra-line differences. The diff command only processes lines.
> If you aren't interested in intra-line differences, use a SequenceMatcher  
> instead. Or, invoke the diff command using   subprocess.Popen +  
> communicate.
>
> --
> Gabriel Genellina


thank you very much Gabriel! Passing a list of the document lines
makes the efficiency comparable to the diff command.
Richard
-- 
http://mail.python.org/mailman/listinfo/python-list


os.rename [Errno 31] Too many links

2010-03-10 Thread Richard
I want to atomically write to a file so have been using temporary
files and renaming:

temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write(data)
temp.file.close()
os.rename(temp.name, output_file)

This worked but after 39567 files os.rename raises an OSError: [Errno
31] Too many links

I can still create files in this directory so I doubt it is a platform
limitation.
Can you tell what is wrong? Am I not freeing the temporary file
resources properly?

thanks,
Richard


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


Re: os.rename [Errno 31] Too many links

2010-03-10 Thread Richard
On Mar 11, 3:08 am, Thomas Guettler  wrote:
> Richard wrote:
> > I want to atomically write to a file so have been using temporary
> > files and renaming:
>
> > temp = tempfile.NamedTemporaryFile(delete=False)
> > temp.file.write(data)
> > temp.file.close()
> > os.rename(temp.name, output_file)
>
> > This worked but after 39567 files os.rename raises an OSError: [Errno
> > 31] Too many links
>
> > I can still create files in this directory so I doubt it is a platform
> > limitation.
> > Can you tell what is wrong? Am I not freeing the temporary file
> > resources properly?
>
> If you are on linux you can have a look at the open file descriptors of
> a running process like this:
>
> ls -l /proc/PID/fd/
>
> But I guess it is a limitation of your filesystem. What do you use?
>
> I once had this problem with ext2. It has a low limit for
> subdirectories.
>
> With xfs the limits are much greater.
>
>   Thomas
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de


I am using Ubuntu 9.10 with ext3, which I believe has a limit for the
number of subdirectories but not files.

Thanks for the open file descriptor tip - I will check that out.

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


Re: "Strong typing vs. strong testing"

2010-09-28 Thread Richard
Malcolm McLean  writes:

> On Sep 27, 9:29 pm, p...@informatimago.com (Pascal J. Bourguignon)
> wrote:
>>
>> On the other hand, with the dynamic typing mindset, you might even wrap
>> your values (of whatever numerical type) in a symbolic expression
>> mentionning the unit and perhaps other meta data, so that when the other
>> module receives it, it may notice (dynamically) that two values are not
>> of the same unit, but if compatible, it could (dynamically) convert into
>> the expected unit.  Mission saved!
>>
> I'd like to design a language like this. If you add a quantity in
> inches to a quantity in centimetres you get a quantity in (say)
> metres. If you multiply them together you get an area, if you divide
> them you get a dimeionless scalar. If you divide a quantity in metres
> by a quantity in seconds you get a velocity, if you try to subtract
> them you get an error.
>

or simply use c++ etc and simply use overridden operators which pick the correct
algorithm

-- 
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c
-- 
http://mail.python.org/mailman/listinfo/python-list


library for Amazon MWS

2010-10-04 Thread Richard
Hello,

Is there a Python library for interacting with Amazon MWS (https://
sellercentral.amazon.com/gp/mws/index.html)?

I found Ruby, Perl, PHP, C#, and Java versions, but not Python:
http://github.com/dmichael/amazon-mws
http://github.com/frodwith/Amazon-MWS
https://sellercentral.amazon.com/gp/mws/doc/en_US/bde/feeds/v20090901/php.html
https://sellercentral.amazon.com/gp/mws/doc/en_US/bde/feeds/v20090901/cSharp.html
https://sellercentral.amazon.com/gp/mws/doc/en_US/bde/feeds/v20090901/java.html

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


tkMessageBox

2010-10-18 Thread richard
When I do   import tkMessageBox  the Python Shell tells me that this
does not exist.  Where do I find it?   You may reply to my academic
email: rdrie...@nps.edu
-- 
http://mail.python.org/mailman/listinfo/python-list


Useful Python books and Web sites for system administrators

2013-06-13 Thread Richard Zinar
Hi,

If anyone has some favorite books or Web sites which explore using
Python for various system administration tasks, I'd be interested in
hearing about them.  I'm primarily interested in resources which focus
on Linux, but since I work in a multi-platform environment, pointers
to sites which discuss Python scripting in the context of Windows
system administration would also be helpful.

Thanks,

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


[ANN] PyWeek 17 will run in the first week of September (1st to 8th) - write a game in Python in a week

2013-07-24 Thread Richard Jones
Hi all,

The Python Game Programming Challenge  will run
its 17th challenge during the first week of September, from the 1st to
the 8th.

The PyWeek challenge:

1. Invites entrants to write a game in one week from scratch either as
an individual or in a team,
2. Is intended to be challenging and fun,
3. Will increase the public body of game tools, code and expertise,
4. Will let a lot of people actually finish a game, and
5. May inspire new projects (with ready made teams!)

Check out the help page for how to compete (and prepare) and the
growing resources message board post:

   http://pyweek.org/s/help/
   http://pyweek.org/d/4008/
-- 
http://mail.python.org/mailman/listinfo/python-list


Incorrect detection of futimesns/futimes in 3.3.0b1

2012-07-19 Thread RICHARD MOSELEY
I have recently been compiling the source for 3.3.0 beta1 and have
discovered that even though the functions futimens, futimes and lutimes are
found by the configure script, since they exist as entry points in libc,
their actually only stub functions that simply return ENOSYS (Not
Implemented) when called.

This causes the installation stage to fail with a fatal error, 'Error:
Function Not Implemented', during the installation of the libraries into
the lib-dynload directory, leading me to initially think that there was a
problem with the distutils module (fairly unlikely I know).

The platform I am compiling on, is an ASUS Eee PC 1000 running the original
Xandros operating system.

I can make the installation complete, by modifying the pyconfig.h and
undefining the erroneous defines: HAVE_FUNC_FUTIMENS, HAVE_FUNC_FUTIMES and
HAVE_FUNC_LUTIMES.

I am now considering providing a general patch to the configure.ac file
which will more correctly detect all the various flavours of utimes
(futimens, futimes, lutimes, futimesat, utimensat and utimes) using a
different check other than AC_CHECK_FUNCS. Or would it be better simply to
keep it private and apply the fix each time I upgrade the source code to
the latest version?

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


Python Game Programming Challenge (PyWeek) #15 is coming!

2012-08-12 Thread Richard Jones
The 15th Python Game Programming Challenge (PyWeek) is coming. It'll
run from the 9th to the 16th of September:

  http://pyweek.org/

The PyWeek challenge:

1. Invites entrants to write a game in one week from scratch either as
an individual or in a team,
2. Is intended to be challenging and fun,
3. Will increase the public body of game tools, code and expertise,
4. Will let a lot of people actually finish a game, and
5. May inspire new projects (with ready made teams!)


Check out the help page for how to compete and the growing resources
message board post:

   http://pyweek.org/s/help/
   http://pyweek.org/d/4008/


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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Richard Thomas
class Foo(object):
def __new__(cls, arg):
if isinstance(arg, list):
cls = FooList
elif isinstance(arg, dict):
cls = FooDict
return object.__new__(cls, arg)

class FooList(Foo, list):
pass

class FooDict(Foo, dict):
pass

You could even have __new__ make these Foo* classes dynamically when it 
encounters a new type of argument.

Chard.

On Thursday, 16 August 2012 18:54:12 UTC+2, Thomas Bach  wrote:
> On Thu, Aug 16, 2012 at 05:10:43PM +0200, Hans Mulder wrote:
> 
> > On 16/08/12 14:52:30, Thomas Bach wrote:
> 
> > > 
> 
> > > So, my question (as far as I can see it, please correct me if I am
> 
> > > wrong) is less of the "How do I achieve this?"-kind, but more of the
> 
> > > "What is a clean design for this?"-kind. My intuitive thought was that
> 
> > > the `merge' function should be a part of the object returned from `F'.
> 
> > 
> 
> > The misunderstanding is that you feel F should return an object with
> 
> > a 'merge' method and a varying abse type, while Steven and others
> 
> > think that F should be a function.
> 
> 
> 
> OK, then my design wasn't so bad in the first place. :)
> 
> 
> 
> I made a class `Model' which wraps the actual type and realized
> 
> `merge' and `F' (with a better name, though) as classmethods of
> 
> `Model' in order to tie together the stuff that belongs together. By
> 
> the way, another need I saw for this design was that
> 
> 
> 
> setattr(Model(), 'foo', {'bar': int})
> 
> 
> 
> works, whereas 
> 
> 
> 
> setattr(dict(), 'foo', {'bar': int}) 
> 
> 
> 
> raises an AttributeError (on Python 3.2). Could someone give me the
> 
> buzz word (or even an explanation) on why that is so?
> 
> 
> 
>  Thomas Bach

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


Re: Dynamically determine base classes on instantiation

2012-08-16 Thread Richard Thomas
> a is a Foo
> b is a Foo
> therefore a and b are the same type

What you mean here is "a and b share a common base class".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically determine base classes on instantiation

2012-08-17 Thread Richard Thomas
On Thursday, 16 August 2012 19:49:43 UTC+2, Steven D'Aprano  wrote:
> On Thu, 16 Aug 2012 10:03:51 -0700, Richard Thomas wrote:
> 
> 
> 
> > class Foo(object):
> 
> > def __new__(cls, arg):
> 
> > if isinstance(arg, list):
> 
> > cls = FooList
> 
> > elif isinstance(arg, dict):
> 
> > cls = FooDict
> 
> > return object.__new__(cls, arg)
> 
> > 
> 
> > class FooList(Foo, list):
> 
> > pass
> 
> > 
> 
> > class FooDict(Foo, dict):
> 
> > pass
> 
> 
> 
> 
> 
> Did you actually try your code?
>  

I rarely test code. I'm confident in, however undeserved the confidence. :) In 
this case that's not an error I've ever seen before. Obvious easy fix:

return cls.__new__(cls, arg)

Incidentally when I reply to your posts through the groups.google.com interface 
it inserts a blank quoted line between each pair of lines. My first thought was 
that it was a line endings bug with Google's app but in retrospect that seems 
very likely to have been fixed years ago. Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: building a dictionary dynamically

2012-02-06 Thread Richard Thomas
On Feb 4, 6:13 pm, noydb  wrote:
> How do you build a dictionary dynamically?  Doesn't seem to be an
> insert object or anything.  So I need an empty dictionary that I then
> want to populate with values I get from looping through a list and
> grabbing some properties.  So simply, I have (fyi, arcpy = module for
> interacting with gis data)
>
> >>> inDict = {}
> >>> for inFC in inFClist:
> >>>     print inFC
> >>>     inCount =  int(arcpy.GetCount_management(inFC).getOutput(0))
>
> where I want to make a dictionary like {inFC: inCount, inFC:
> inCount, }
>
> How do I build this???
>
> And, is dictionaries the best route go about doing a comparison, such
> that in the end I will have two dictionaries, one for IN and one for
> OUT, as in I'm moving data files and want to verify that the count in
> each file matches between IN and OUT.
>
> Thanks for any help!

Dictionaries are mutable, you can modify them in place:

>>> myDict = {}
>>> for myKey in myList:
... myDict[myKey] = doSomething(myKey)

Dictionaries sound like a good way to go. You only need the one
dictionary though, the IN one. When processing the outCount values you
can just check them against the inDict at that point.

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


Python Game Programming Challenge (PyWeek) #14 is coming!

2012-02-20 Thread Richard Jones
The 14th Python Game Programming Challenge (PyWeek) is coming. It'll
run from the 22nd to the 29th of April.

  http://pyweek.org/14/

New user registration is NOT YET OPEN. It will open one month before
the challenge starts.

The PyWeek challenge:

- Invites entrants to write a game in one week from scratch either as
an individual or in a team,
- Is intended to be challenging and fun,
- Will hopefully increase the public body of game tools, code and expertise,
- Will let a lot of people actually finish a game, and
- May inspire new projects (with ready made teams!)

If you're in the US and can make it I'm co-presenting a 3 hour pygame
tutorial at PyCon in March.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Game Programming Challenge (PyWeek) #14 is coming! [corrected dates]

2012-02-22 Thread Richard Jones
Note: this email corrects the dates given in the previous announcement.

The 14th Python Game Programming Challenge (PyWeek) is coming. It'll
run from the 6th to the 13th of May. Not April as previously announced.

 http://pyweek.org/14/

New user registration is NOT YET OPEN. It will open one month before
the challenge starts.

The PyWeek challenge:

- Invites entrants to write a game in one week from scratch either as
an individual or in a team,
- Is intended to be challenging and fun,
- Will hopefully increase the public body of game tools, code and expertise,
- Will let a lot of people actually finish a game, and
- May inspire new projects (with ready made teams!)

If you're in the US and can make it I'm co-presenting a 3 hour pygame
tutorial at PyCon in March.
-- 
http://mail.python.org/mailman/listinfo/python-list


converting from tcl/tkl to python

2012-03-09 Thread Richard Boothroyd
Hi there,

First, I am not a developer so go easy on my ignorance ;-). Our
company designs and develops hearing aid audibility fitting equipment.
(www.audioscan.com). Our current software GUI is all based on TCL/TKL
and we are running into issues on developing a "prettier" GUI in an
effort to modernize some of our equipment.

My understanding is that Python is a much better GUI tool than TCL/TKL
so I'd appreciate any insight on this assumption. Also I'm wondering
what kind of effort and expertise it would take to convert from TCL/
TKL to Python. Let me know what further info you may require.

Also, if there is anyone out there that has specific expertise in
performing this conversion please contact me.

Thanks
Richard Boothroyd
General Manager
Audioscan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a reference of the 'owner' class to which a method belongs in Python 3.X?

2012-03-17 Thread Richard Thomas
On Saturday, 17 March 2012 05:30:34 UTC, Cosmia Luna  wrote:
> I'm porting my existing work to Python 3.X, but...
> 
> class Foo:
> def bar(self):
> pass
> 
> mthd = Foo.bar
> 
> assert mthd.im_class is Foo # this does not work in py3k

mthd.im_class is the class of mthd.im_self not the class that defined the 
method.

> 
> So, how can I get a reference to Foo? This is important when writing
> decorators, the only way I can think out is:

Not sure what sort of decorators you're writing. Examples?

You can achieve this with metaclasses but if you're using classes from someone 
else's code this doesn't necessarily work. Something in inspect module can 
probably do the trick, check the docs. Frankly though it sounds messy no matter 
what. It might be better to find an alternative to knowing the class.

> class Foo:
> def bar(self):
> 'Foo' # manually declare the owner class
> pass
> 
> mthd = Foo.bar
> 
> assert mthd.__globals__[mthd.__doc__] is Foo # this works
> 
> class Child(Foo):
> def bar(self):
> 'Child' # I have to override all method defined by bar but do nothing
> pass
> 
> child_mthd = Child.bar
> 
> assert child_mthd.__globals__[child_mthd.__doc__] is Child # this works
> 
> But the code above is quite ugly and abuses the __doc__. Is there any
> equivalent in py3k of im_class?
> 
> Thanks,
> Cosmia

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


Re: setup.py for an extension

2012-03-21 Thread Richard Thomas
Assuming you have:
lib/__init__.py
lib/foo.py
lib/foo.c

Then:
from distutils.core import setup, Extension
setup(name="lib", packages=["lib"], ext_modules=[Extension("lib._foo", 
["lib/foo.c"])])
-- 
http://mail.python.org/mailman/listinfo/python-list


Suggest design to accomodate non-unix platforms ?

2012-04-18 Thread Richard Shea
On a *nix box this is a reasonable bit of Python :

cmd = "ssh -o StrictHostKeyChecking=no -i %s %s@%s '%s' > %s" % (key,
user, dns, "echo CONNECTION READY", tmp_file)
result = os.system(cmd)

... on a Windows box it will fail because 'ssh' isn't part of Windows.

There *are* ways of achieving the equivalent functionality in Windows,
eg

putty.exe -ssh user@host

... and that's only one of them.

So I'm interested in suggestions/examples where a user can update a
config file to specify by which means they want (in this case) the ssh
functionality to be supplied.

I'm thinking of something in a config file like this ...

ssh_dropin = {exec: 'putty.exe -ssh %s@%s', args:['auser','somehost']}

... which I think would work and be sufficiently flexible to deal with
alternatives to putty.exe but is there a more established (...
better !) way of doing this stuff ?

Thanks

Richard.



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


Re: Suggest design to accomodate non-unix platforms ?

2012-04-18 Thread Richard Shea
On Apr 19, 1:56 am, Irmen de Jong  wrote:
> On 18-4-2012 15:35, Richard Shea wrote:
>
> > ... which I think would work and be sufficiently flexible to deal with
> > alternatives to putty.exe but is there a more established (...
> > better !) way of doing this stuff ?
>
> Perhaps install Cygwin and use its ssh.exe?
> Or use the paramiko library? (which, I believe, implements SSH directly)
>
> Irmen

OK I didn't know about Paramiko, that looks good - I will investigate.
I didn't want to go to as far as Cygwin because it's a bit much to
make that a requirement when installing a library.

More generally though I'd be interested to see patterns which would
allow a plugin alternative to be used for a system utility on which a
library is dependent.

I've realised that my example isn't much good because the values in
the args list would in fact have to equate to the variables already in
place within the relevant function - it's pretty late where I am so I
probably shouldn't be trying to think up new ideas but I'd be
interested to hear from others about how they might do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggest design to accomodate non-unix platforms ?

2012-04-18 Thread Richard Shea
On Apr 19, 2:28 am, tinn...@isbd.co.uk wrote:
> Richard Shea  wrote:
> > On a *nix box this is a reasonable bit of Python :
>
> > cmd = "ssh -o StrictHostKeyChecking=no -i %s %s@%s '%s' > %s" % (key,
> > user, dns, "echo CONNECTION READY", tmp_file)
> > result = os.system(cmd)
>
> > ... on a Windows box it will fail because 'ssh' isn't part of Windows.
>
> ssh isn't guaranteed to be part of Unix/Linux systems surely.
>
> --
> Chris Green

Ha ! Ok I didn't know that (or more to the point hadn't really thought
about it). But anyway my more general point was looking for a design
pattern which would accommodate the use of system utilities across
multiple platforms which has sufficiently similar functionality that
they were functionally identical but which would have to be invoked in
different ways
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Whither paramiko?

2012-04-19 Thread Richard Shea
On Apr 16, 1:42 am, Bryan  wrote:
> Paramiko is a Python library for SSH (Secure Shell). Over about the
> last year, I've grown dependent upon it. Its home page is still easy
> to search up, but the links to its mailing list and repository don't
> work.
>
> Paramiko depends on PyCrypto, and not so long ago that dependency was
> the stated reason why paramiko did not yet play with Python 3. Even
> more recently, PyCrypto has gone green on the Python 3 Wall of Shame.
>
> Anyone know recent news on the status of paramiko?
>
You may have already tried this but on the web page ( 
http://www.lag.net/jaramiko/
)for Jaramiko, the Java port of Paramiko, there's an email address for
the author - maybe you could try that ? The email address quoted is :
robey at lag.net .

What's a bit odd is that, as you mentioned, the repository is
mentioned as being at : http://github.com/robey/paramiko/ but comes up
404. However the user robey (robeypointer at gmail.com) is still on
GitHub (and has been there since 2008) but there's no mention of
anything related to Paramiko on his page.

If you do find anything maybe you could update this thread as I'm just
about to start using the library and I'd like to know a little more
about where it might be going in future.

regards

Richard.



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


Re: Whither paramiko?

2012-04-19 Thread Richard Shea
On Apr 19, 8:28 pm, Richard Shea  wrote:
> On Apr 16, 1:42 am, Bryan  wrote:> 
> Paramiko is a Python library for SSH (Secure Shell). Over about the
> > last year, I've grown dependent upon it. Its home page is still easy
> > to search up, but the links to its mailing list and repository don't
> > work.
>
> > Paramiko depends on PyCrypto, and not so long ago that dependency was
> > the stated reason why paramiko did not yet play with Python 3. Even
> > more recently, PyCrypto has gone green on the Python 3 Wall of Shame.
>
> > Anyone know recent news on the status of paramiko?
>
> You may have already tried this but on the web page 
> (http://www.lag.net/jaramiko/
> )for Jaramiko, the Java port of Paramiko, there's an email address for
> the author - maybe you could try that ? The email address quoted is :
> robey at lag.net .
>
> What's a bit odd is that, as you mentioned, the repository is
> mentioned as being at :http://github.com/robey/paramiko/but comes up
> 404. However the user robey (robeypointer at gmail.com) is still on
> GitHub (and has been there since 2008) but there's no mention of
> anything related to Paramiko on his page.
>
> If you do find anything maybe you could update this thread as I'm just
> about to start using the library and I'd like to know a little more
> about where it might be going in future.
>
> regards
>
> Richard.

Just another data point . I've just taken a look at the bundled
documention of the 1.7.7.1 release and in there the robeypointer @
gmail.com is cited as being the contact point for the developer .

regards

Richard.


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


Use of internal ctypes objects

2012-06-15 Thread RICHARD MOSELEY
I have a module which makes use of ctypes to interface to the IBM C-ISAM
library under linux. I have created a libpyisam.so library which combines
the two official libraries, libifisam.so and libifisamx.so and provides a
SONAME for the ctypes module (if that is still required).

My main object uses a dictionary in which the keys are the external
functions that can be called from the externl library, and the values are
initially tuples which define the arguments and return type for the
functions. The first time that a function is called, the __getattr__
function locates the function in the library then modifies the return type
and arguments according to the tuple stored in the value, this object is
then stored in place of the tuple so that subsequent calls simply use the
previous object.

To check whether the function has been previously converted, I make use of
internal objects within the ctypes module, namely, _SimpleCData and
_CFuncPtr. Is this a safe thing to do, bearing in mind that the objects are
documentated as internal?

In order to make the above paragraphs clear, I provide a cutdown version of
the object in question with a sample of the functions and the calling
convention used. Is there a better way to do this using ctypes:

from ctypes import *

class ISAMobject(dict):
  """
  The _func dictionary initially consists of:
(args,...)where the return type is c_int and arguments
are passed,
(None,) where the return type is c_int but no arguments
are passed,
(ret,(args,...))where the return type is not c_int and
arguments are passed,
(ret,None) where the return type is not c_int and no
arguments are passed,
None where there is no return type and no arguments
are passed
  """
  _func = {
'isbegin'  : (None,),
'iscluster' : (c_int, byref(keydesc)),
'islangchk' : None,
'islanginfo' : (c_char_p, (c_char_p,))
  }

  _const = {
'iserrno' : c_int,
'iscopyright' : c_char_p
  }

  _lib = cdll.LoadLibrary('./libpyisam.so')

  def __getattr__(self, name):
func_info = self._func.get(name, 'NONE')
if func_info == 'NONE':
   const_info = self._const.get(name, 'NONE')
   if const_info == 'NONE':
  raise AttributeError('Underlying ISAM library does not have %s
attribute' % name)
   if not isinstance(const_info, ctypes._SimpleCData):
  const_info = const_info.in_dll(self._lib, name)
  self._const[name] = const_info
   return const_info.value if hasattr(const_info, 'value') else
const_info
elif not instance(func_info, ctypes._CFuncPtr):
   real_func = getattr(self._lib, name)
   if real_func is None:
  raise AttributeError('Underlying ISAM library does not support %s
function' % name)
   if func_info is None:
  real_func.restype = real.argtypes = None
   elif isinstance(func_info, list):
  real_func.restype, real_func.argtypes = func_info
   elif len(func_info) > 1 and isinstance(func_info[1], tuple):
  real_func.restype, real_func.argtypes = func_info
   elif isinstance(func_info, tuple):
  real_func.argtypes = func_info
   else:
  real_func.restype = func_info
   self._func[name] = func_info = real_func
return func_info

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


Re: Determine attributes of calling method

2011-06-04 Thread Richard Thomas
On Jun 3, 9:35 pm, Joe  wrote:
> Hello,
>
> I'm trying to implement a way to restrict method usage based on the
> caller's attributes.  In the following example I'd like to execute the
> server method "bar" only if the caller's method has a "blue" value for
> it's color attribute.
>
> The current output is:
>
> blue
> red
> bar
> bar
>
> I'd like it to be:
>
> blue
> red
> bar
>
> I've worked my way through inspect but that doesn't seem to be the
> right approach.
>
> # Example
> class Client:
>
>     def __init__(self, server):
>         self.server=server
>
>     def foo(self):
>         self.server.bar()
>
>     def fu(self):
>         self.server.bar()
>
>     foo.__dict__['color']='blue'
>     fu.__dict__['color']='red'
>
> class BlueServer:
>
>     def bar(self):
>         """
>         Goal is to only accept calls from "blue" client methods.
>         Don't know how to do it :(
>         """
>         print "bar"
>
> s=BlueServer()
> c=Client(s)
> print c.foo.color
> print c.fu.color
> c.foo()
> c.fu()
>
> Thanks for your help!
>
> Joe

It is possible to get access to the code object of the parent
execution frame. Function objects are just wrappers for code objects
and are not part of the frame. You could do something with that
though...

_colors = {}
def color(c):
def decorator(f):
code = f.func_code
key = code.co_filename, code.co_firstlineno
_colors.setdefault(key, set()).add(c)
return f
return decorator

def require(c):
import sys
code = sys._getframe().f_back.f_back.f_code
key = code.co_filename, code.co_firstlineno
assert c in _colors.get(key, ())

def tryit():
require("blue")

@color("blue")
def bluefunc():
tryit()

@color("red")
def redfunc():
tryit()

Executing untrusted Python code is nigh impossible to make secure of
course. I'd suggest examining whether this is necessary. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Documenting Regex (and code)

2011-06-06 Thread Richard Parker
-
Dense and complex REs are quite powerful, but may also contain
and hide programming mistakes.  The ability to describe what is
intended -- which may differ from what is written -- is useful.
-
Once again, I feel compelled to stress the importance of well-written 
documentation embedded within the program's code. Many of you eschew this 
practice, stating that when the code is changed that often the documentation 
isn't. Shame on you! Documentation is at least, or more, important than the 
code, as it reflects the intentions of the creator. Failing to revise 
documentation along with it's accompanying code is an egregious sin and is one 
for which all programmers should repent.

After more than five decades of programming, documenting my code, writing books 
about programming and it's documentation, I shudder at the thought of even one 
of you thinking that removal of all the comments before modifying a program is 
appropriate, that the code itself properly expresses it's creator's intent.

I accept the flames that will ensue from this post and remain steadfast in my 
belief and extensive experience that commented (in the form of block comments) 
code is far more valuable than just the code itself.

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


Re: Function docstring as a local variable

2011-07-10 Thread Richard Thomas
> >>> def findself():
>
>         """Find myself. Ooh look, there I am!"""
>         import sys
>         try:
>                 1/0
>         except:
>                 traceback=sys.exc_info()[2]
>         # Now I'm not sure what to do with traceback.
>         # traceback.tb_frame.f_code.co_name is the function name ("findself").
>         # Is there a way to get the function object?

I'm pretty sure there isn't. I've tried a number of times before to
find it but failed. Fundamentally frame objects don't need to know
about functions. Functions are just one way of wrapping code objects
but sometimes code objects come in modules.

You can use sys._getframe() to get the current frame instead of the
traceback.

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


Python Game Programming Challenge 13 (September 2011) is coming!

2011-07-21 Thread Richard Jones
The 13th Python Game Programming Challenge (PyWeek) is coming. It'll
run from the 11th to the 18th of September.

The PyWeek challenge:

- Invites entrants to write a game in one week from scratch either as
an individual or in a team,
- Is intended to be challenging and fun,
- Will hopefully increase the public body of game tools, code and expertise,
- Will let a lot of people actually finish a game, and
- May inspire new projects (with ready made teams!)


   Richard
   http://pyweek.org/13/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Code Examples

2011-03-01 Thread Richard Dobson

On 01/03/2011 08:43, Erik de Castro Lopo wrote:

Fred Marshall wrote:


I'm interested in developing Python-based programs, including an
engineering app. ... re-writing from Fortran and C versions.  One of the
objectives would to be make reasonable use of the available structure
(objects, etc.).  So, I'd like to read a couple of good, simple
scientific-oriented programs that do that kind of thing.


Why Python? I really can't understand the rush of every man and
his dog to Python.

Its not that I'm a stick in the mud stuck with C and C++, rather
that I used Python for a number of years from 1998 to 2004 and
rejected it in favour of strict statically typed functional
langauges like Ocaml and Haskell.



My understanding is/was that Guido originally proposed Python as the 
replacement for BASIC; i.e. to be the new first language students at 
school would be exposed to. So rather than compare it to C and C++, I 
suppose one should, strategically speaking, compare it to Visual Basic 
and/or Java.


The other aspect is purely pragmatic - it has bindings for tk, MIDI and 
audio (and of course Csound as you know), which adds up to a fairly 
hefty scripting package complete with GUI design options - great for 
"knocking up stuff quickly". But - I am ~still~ caught out by the 
semantic significance of indenting. Looks OK enough on paper, but doing 
it interactively is another matter.



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


PyWeek 12 (April 2011) is registration is open!

2011-03-06 Thread Richard Jones
The 12th Python Game Programming Challenge (PyWeek) is almost upon us.
It'll run from the 3rd to the 10th of April. Registration for teams
and individuals is now open on the website:

   http://pyweek.org/

The PyWeek challenge:

- Invites entrants to write a game in one week from scratch either as
an individual or in a team,
- Is intended to be challenging and fun,
- Will hopefully increase the public body of game tools, code and expertise,
- Will let a lot of people actually finish a game, and
- May inspire new projects (with ready made teams!)

If you've never written a game before and would like to try things out
then perhaps you could try either:

The tutorial I presented at LCA 2010, Introduction to Game Programming:
  http://www.lca2010.org.nz/wiki/Tutorials/Introduction_to_game_programming

The book Invent Your Own Computer Games With Python:
  http://inventwithpython.com/


   Richard Jones
   http://pyweek.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Tk MouseWheel Support

2011-03-10 Thread Richard Holmes
I am trying to use the mouse wheel to scroll a list box, but I'm not
getting the event. When I bind "" to the listbox I get the
event and I'm able to scroll using yview_scroll. I've tried binding
"MouseWheel" and "", and I've also tried "" and
"" even though I'm using Windows (XP, if that makes a
difference). None of these works (I'm using print to see if I got to
an event handler, and there's no printout).

TIA for any help!

Dick

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


Next Melbourne PUG meeting 6pm Monday 4th of April @ RMIT

2011-03-30 Thread Richard Jones
Hi all,

Sorry for the late post this week. The next meeting is next Monday,
the 4th of April at RMIT.

The room has changed! After the double-booking last week we've been
moved to 12.07.02 (building 12, level 7, room 2).

Tennessee's going to talk to us about an approach to benchmarking that
he's been working on.

If you have some experience with benchmarking or profiling Python
code, perhaps you have something you can share?

I'm going to talk about PyWeek number 12, which starts this coming
Sunday morning :-)

Full meeting info at http://j.mp/mpug


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


Re: Namespaces in functions vs classes

2011-04-17 Thread Richard Thomas
On Apr 17, 8:56 pm, Chris Rebert  wrote:
> On Sun, Apr 17, 2011 at 12:30 PM, Gerald Britton
>
>
>
>
>
>
>
>
>
>  wrote:
> > I apologize if this has been answered before or if it is easy to find
> > in the docs. (I couldn't find it but might have missed it)
>
> > I'm trying to understand the differences between namespaces in class
> > definitions vs. function definitions.  Consider this function:
>
>  def a():
> > ...     foo = 'foo'
> > ...     def g(x):
> > ...         return foo
> > ...     print g(1)
> > ...
>  a()
> > foo
>
> > Now, I replace the first "def" with "class":
>
>  class a():
> > ...     foo = 'foo'
> > ...     def g(x):
> > ...         return foo
> > ...     print g(1)
> > ...
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "", line 5, in a
> >  File "", line 4, in g
> > NameError: global name 'foo' is not defined
>
> > So, the variable "foo" is not available inside the function inside
> > class as it is inside the (inner) function.  I figured this was just
> > because the class was still being defined, so I tried this:
>
>  class a():
> > ...     foo = 'foo'
> > ...     def g(x):
> > ...         return foo
> > ...
>  x = a()
>  x.g()
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "", line 4, in g
> > NameError: global name 'foo' is not defined
>
> > which still fails.  I had expected that "foo" would be available
> > within the namespace of the object instance.  I was wrong.  For my
> > final attempt, I add the prefix "a." to my use of "foo"
>
>  class a():
> > ...     foo = 'foo'
> > ...     def g(x):
> > ...         return a.foo
> > ...
>  x = a()
>  x.g()
> > 'foo'
>
> > So, this works and I can use it.  However,  I would like a deeper
> > understanding of why I cannot use "foo" as an unqualified variable
> > inside the method in the class.  If Python allowed such a thing, what
> > problems would that cause?
>
> Class-level scope is simply never consulted when looking up
> unqualified names in methods. When looking up such name from within a
> method, the following scopes are consulted, in order (ignoring some
> subtleties):
> 1. Local variables
> 2. Variables in nested functions
> 3. Global variables
> 4. Built-ins
>
> For "workarounds" for this, 
> see:http://mail.python.org/pipermail/python-list/2009-December/1228354.html
>
> As to why Python works this way, I'm not sure. However, one could
> cogently argue that this requires you to be more explicit about what
> the scope is of the name you're referring to; which set of semantics
> you desire in the face of inheritance, monkey-patching, and instance
> variable shadowing makes this trickier than you might otherwise think.

I don't know but I suspect that the reason is one of optimisation.
Functions know what the locally defined names are so when it is
compiled it uses the opcode that loads from the local variable
namespace. Functions also know what their closure is (that is, the
locally defined names of enclosing functions) and can do an
appropriate thing in that case. If a name does not fall into either of
those two categories it is loaded with the LOAD_GLOBAL opcode. The
result of all this is that functions find the correct namespace very
quickly.

If variables in class scope were to be accessible unqualified from
within a method either loading of global names (a VERY common
operation) would be made notably slower, or the class namespace would
have to be immutable (which I think we can agree would be
undesirable), or possibly other, more complicated tradeoffs I haven't
considered.

This is all just guesswork. As a suitable proxy for the class (i.e. an
instance thereof) is available within the local scope of all methods,
getting those class variables is quite straightforward really.
Personally I find qualifying the scope of variables that aren't
globals or builtins to be a restriction that leads to better, clearer
code. :-)

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

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


  1   2   3   4   5   6   7   8   9   10   >