Help: retrieving e-mail from yahoo pop server. what's wrong?

2005-02-09 Thread Andre
  Hi guys, newbie question. I am having trouble with a script that is
supposed to login me to my account on yahoo pop server. When i do this:



import getpass, poplib, re
POPHOST = "pop.mail.yahoo.com"
POPUSER = "mylogin"
POPPASS = "mypass"
pop = poplib.POP3(POPHOST)
pop.user(POPUSER)


up to this point evertything proceeds fine, but when i do


if not POPPASS:
POPPASS = getpass.getpass("Password for [EMAIL PROTECTED]:" % (POPUSER, 
POPHOST))
pop.pass_(POPPASS)


I am being asked for password and after giving it getting
the following error:


POP3 Protocol Error: -ERR Error logging in. Please visit
http://mail.yahoo.com


Would appreciate any help or comments -- its my first day with Python :).
What am i doing wrong?


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


Re: Help: retrieving e-mail from yahoo pop server. what's wrong?

2005-02-09 Thread Andre
Thank, Kartic

I actually tried doing it with several other accounts, notably mail.com and
netscape.com
When i do it with netscape the dialog goes like the following:

>>> POPHOST = 'pop3.isp.netscape.com'
>>> pop = poplib.POP3(POPHOST)
>>> POPUSER = "myusername"
>>> pop.user(POPUSER)
'+OK'
>>> pop.pass_("mypassword")
Traceback (most recent call last):
  File "", line 1, in ?
pop.pass_("123456")
  File "D:\Python24\lib\poplib.py", line 202, in pass_
return self._shortcmd('PASS %s' % pswd)
  File "D:\Python24\lib\poplib.py", line 165, in _shortcmd
return self._getresp()
  File "D:\Python24\lib\poplib.py", line 141, in _getresp
raise error_proto(resp)
error_proto: -ERR invalid username or password

The username and password are naturally valid, but something else is wrong.
Do you know if Netscape also doesn't allow POP access? Is there a free
e-mail provider who does?
Thanks a mil,

Andre

"Kartic" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Andre,
>
> Do you have a premium Yahoo account? Only premium users can access
> Yahoo mail via POP3. If you are a premium account holder and it still
> is not working, print out your password to see if you typed the correct
> password.
>
> Have you tried accessing your Yahoo from an email client? Does that
> work?
>
> Thanks,
> -Kartic
>


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


Re: How to write python plug-ins for your own python program?

2005-03-03 Thread Andre
Mark Rowe <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> On Mar 3, 2005, at 9:33 PM, Simon Wittber wrote:
> 
> >> You mean like 'import'? :)
> >
> > That's how I would do it. It's the simplest thing, that works.
> >
> > exec("import %s as plugin" % pluginName)
> > plugin.someMethod()
> >
> > where pluginName is the name of the python file, minus the ".py" 
> > extension.
> 
> A better method would be something along the lines of:
> 
> plugin = __import__(pluginName)
> plugin.someMethod()
> 
> This avoids the potential security problem that `exec' poses as well as 
> the need to parse + interpret the string.
> 
What happens if you have:
.def someMethod():
.import os
.rm * # or whatever other evil thing you might thing of

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


Re: Embedding numpy works once, but not twice??

2014-06-04 Thread Andre
Any Solution?

-- 
AL Barbieri
http://scholar.google.com/citations?user=tylaKAMJ
-- 
https://mail.python.org/mailman/listinfo/python-list


Generic string import like in strptime?

2008-01-16 Thread Andre
Hi there

Is there a function like strptime, which takes a string and converts it 
into an array depending on a format string I provide. Like:
>>> a = '3456\tblub-blib.0.9'
>>> b = '%d\t%s-%s.%f'
>>> c = mysticalfunction(a,b) 
>>> print c
[3456,'blub','blib',0.9]


Many thanks

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


HTMLgen???

2009-10-15 Thread andre

Hi,
Does HTMLgen (Robin Friedrich's) still exsist?? And, if so, where can it
be found?

--
   Andre van der Vlies 
   Certifiable Linux/UNIX engineer (CLUE)
   Homepage: http://vandervlies.xs4all.nl/~andre
   Books: http://www.lulu.com/andre14
Key fingerprint = 397C 7479 67DB 9306 23DC B423 7B58 CD5A 6EFF 5CF8
--
"Programming isn't a craft, it's an art."
()  ascii ribbon campaign - against html e-mail
/\- against microsoft attachments
  ^[^#]
--

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


Zlib: correct checksum but error decompressing

2009-08-26 Thread Andre
I have been trying to solve this issue for a while now. I receive data
from a TCP connection which is compressed. I know the correct checksum
for the data and both the client and server generate the same
checksum. However, in Python when it comes to decompressing the data I
get the exception: "Error -5 while decompressing data"! I would assume
that if the string in python is equivalent to the correct checksum
than the decompress function should also work on the same string, but
that's clearly not the case.

# convert data to a byte array
data = array('b', raw_data)
# print checksum for visual inspection
print zlib.crc32(data.tostring())
# try to decompress, but fails!
str = zlib.decompress(data.tostring())

Does anyone know what's going on?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intermediate Python user needed help

2012-08-05 Thread Andre Ramaciotti

On 08/05/2012 06:12 PM, MRAB wrote:

On 05/08/2012 22:03, Tim Chase wrote:

On 08/05/12 15:52, John Mordecai Dildy wrote:

Current Problem at the moment

Traceback (most recent call last):
  File "ex26.py", line 66, in 
beans, jars, crates = secret_formula(start-point)
NameError: name 'start' is not defined

anyone know how to make start defined


"start-point" is not a valid identifier as the "-" isn't permitted
in a variable name.  This is the case for just about every language
out there.  HTML/XML & CSS are the only languages that come to my
mind in which the dash is considered a valid part of an identifier.


I believe that Cobol allows "-"  in names.


Lisp certainly does.
--
http://mail.python.org/mailman/listinfo/python-list


Function declarations ?

2011-06-08 Thread Andre Majorel
Is there a way to keep the definitions of the high-level
functions at the top of the source ? I don't see a way to
declare a function in Python.

Thanks in advance.

-- 
André Majorel http://www.teaser.fr/~amajorel/
J'ai des droits. Les autres ont des devoirs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function declarations ?

2011-06-12 Thread Andre Majorel
On 2011-06-10, Asen Bozhilov  wrote:
> Andre Majorel wrote:
>
>> Is there a way to keep the definitions of the high-level
>> functions at the top of the source ? I don't see a way to
>> declare a function in Python.
>
> Languages with variable and function declarations usually use
> hoisted environment.

Hoisted ? With a pulley and a cable ?

> JavaScript is the perfect example. Hoisted environment allows
> you to use call expression before the physical declaration of
> the function in the source text.

The issue here is not the ability to call a function before its
declaration. It's being able to do so before its definition.

> Hope this helps, why Python use definitions instead of
> declarations.

It's not either/or. Any language has to provide a way to define
functions whether or not it provides a way to declare them.

Anyway, it seems the Python way to declare a function is

  def f ():
pass

Thanks everyone.

-- 
André Majorel http://www.teaser.fr/~amajorel/
J'ai des droits. Les autres ont des devoirs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Language & lib reference in man format ?

2011-04-20 Thread Andre Majorel
If someone has ever written a script to convert the Python
Language Reference and Library Reference to man format, I'm
interested.

Thanks in advance.

-- 
André Majorel http://www.teaser.fr/~amajorel/
"The object of this year's expedition is to see if we can find
trace of last year's expedition."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no '|' operator for dict?

2018-02-05 Thread Andre Müller
You can use keyword-argument unpacking in a dict-constructor.
Values of duplicate keys are overwritten from left to right. The last wins.

>>> dict1 = {'foo': 13, 'bar': 42}
>>> dict2 = {'foo': 42, 'hello': 'world'}

>>> {**dict1, **dict2}
{'bar': 42, 'foo': 42, 'hello': 'world'}

{**dict2, **dict1}
{'bar': 42, 'foo': 13, 'hello': 'world'}

You can make a Class for this task, if you need it very often:

class UDict(dict):
def __or__(self, other):
if not isinstance(other, (self.__class__, dict)):
raise ValueError('Is not a dict!')
return {**self, **other}
__ror__ = __or__

>>> UDict({'foo': 1, 'bar': 1337}) | UDict({'bar': 43})
{'bar': 43, 'foo': 1}
>>> UDict({'foo': 1, 'bar': 1337}) | {'bar': 43}
{'bar': 43, 'foo': 1}
>>> {'foo':42} | UDict({'foo': 1, 'bar': 1337})
{'bar': 1337, 'foo': 42}


Greetings
Andre

Steven D'Aprano  schrieb am Mo., 5.
Feb. 2018 um 11:03 Uhr:

> On Mon, 05 Feb 2018 01:14:53 -0700, Ian Kelly wrote:
>
> > On Mon, Feb 5, 2018 at 12:35 AM, Frank Millman 
> > wrote:
> >> So I have 2 questions -
> >>
> >> 1. Is there any particular reason why '|' is not supported?
> >
> > '|' is the set union operation, roughly equivalent to the set.union
> > method. Dicts don't have a union operation. If they did, and the same
> > key were found in both sets, what would be the value of that key in the
> > union?
>
> Obviously it should be a quantum superposition of the two values, which
> remains uncertain until such time as you actually print the value and
> observe it.
>
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Old format with %

2018-02-15 Thread Andre Müller
It can be escaped: "test %d %%" % 7

Terry Reedy  schrieb am Mi., 14. Feb. 2018 um 20:53 Uhr:

> On 2/14/2018 7:54 AM, ast wrote:
> > Le 14/02/2018 à 13:46, ast a écrit :
> >> Hello
> >>
> >> It seems that caracter % can't be escaped
> >>
> >>  >>>"test %d %" % 7
> >> ValueError: incomplete format
> >>
> >>  >>>"test %d \%" % 7
> >> ValueError: incomplete format
> >>
> >>  >>>"test %d" % 7 + "%"
> >> 'test 7%'  # OK
> >>
> >> But is there a way to escape a % ?
> >>
> >> thx
> >
> > Found, double % to escape it
> >
> >  >>>"test %d%%" % 7
> > 'test 7%'
>
> Same with { and } in new format and f strings.
>  >>> a = 3
>  >>> f'{{x:{a}}}'
> '{x:3}'
>
> --
> Terry Jan Reedy
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regex on a Dictionary

2018-02-15 Thread Andre Müller
Hello,

this question also came up there:
https://python-forum.io/Thread-Working-with-Dict-Object

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


Re: "Programs" folder not found.

2018-02-15 Thread Andre Müller
Look in %localappdata%\Programs\Python

Enerel Amgalan via Python-list  schrieb am Do., 15.
Feb. 2018 um 14:05 Uhr:

>
> Hello! So I downloaded “Python” program in C:>Users>(my
> name)>AppData>Local>Programs>Python.And then in “Local” folder I can’t find
> “Programs” folder,but it says it downloaded in “Programs”.So can you help
> me.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Andre Müller
Hello,

it's a duplicate:
https://python-forum.io/Thread-Working-with-lists-homework-2

I have seen this more than one time. We don't like it. You keep people busy
with one question at different places.

You need two lists and one empty list. One outer loop iterating over the
first list and one inner loop iterating over the second list. In the inner
loop you concatenate the two elements from the outer-loop and inner-loop.
Then you append them to the empty list. This text is 10 times longer as the
source code...

Complicated solution:

from string import ascii_lowercase as letter
list1 = [str(i) + c for i in range(1,4) for c in letter[:3]]
list2 = [c[::-1] for c in list1]

But this won't help you. Before you understand the code above, you have to
understand for-loops and nested for-loops. Then you can proceed with list
comprehensions. But I don't see that your intention is to learn and
understand Python. You just want to finish your homework, which bother you.

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


TemplateError

2016-11-20 Thread iivri . andre
THIS error is constantly showing up when I run my python script 
 eloiim:build iivri.andre$ python run.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2016-11-21 01:15:26,561] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1988, in 
wsgi_app
response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1641, in 
full_dispatch_request
rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1544, in 
handle_user_exception
reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1639, in 
full_dispatch_request
rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1625, in 
dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
  File "run.py", line 10, in IsSelf
return render_template('index.html', author=author, name=name)
  File "/usr/local/lib/python2.7/site-packages/flask/templating.py", line 133, 
in render_template
return 
_render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
  File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 
851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
  File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 
812, in get_template
return self._load_template(name, self.make_globals(globals))
  File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 
774, in _load_template
cache_key = self.loader.get_source(self, name)[1]
  File "/usr/local/lib/python2.7/site-packages/flask/templating.py", line 57, 
in get_source
return self._get_source_fast(environment, template)
  File "/usr/local/lib/python2.7/site-packages/flask/templating.py", line 85, 
in _get_source_fast
raise TemplateNotFound(template)
TemplateNotFound: index.html

THIS is the code 

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
# THE @ is a decorator that is used to 'augment' function definitions
# Flask uses 'route()' to indicate that if the browser requests the address '/' 
(the default | home address), then our app shoud 'route' that request to this 
'IsSelf' function
def IsSelf() :
author = "raphael James "
name = "Jaden iivii"
return render_template('index.html', author=author, name=name)

if __name__ == "__main__" :
app.run()


How do I fix this? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: recommends of redesign OO feature of python !!!

2018-10-25 Thread Andre Müller
Troll detected!

If you don't like Python, don't use it. Very simple.
The concept of Python is good as it is.
-- 
https://mail.python.org/mailman/listinfo/python-list


start python web programming

2005-04-05 Thread Andre Nobre
I should implement a simple http/database page, based on python. I read some texts and it´s strange how python deal with html output. It´s something like Servlet... is there any diferent way to do that? Something like just bussiness code, applied in an MVC framework, or just like it. Thanks and sorry about my english.-- André Nobre[EMAIL PROTECTED]-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Send commands to USB device in Python

2014-05-26 Thread andre . miras
Hi,

I saw your thread on SourceFourge 
(http://sourceforge.net/p/pyusb/mailman/message/31969943/), but I don't have an 
account.
I also have MTI RU-824 reader. I sniffed the USB communication in the Windows 
demo program and I saw that the header should be written backward.
So rather than:
HEADER = bytearray("MTIC")
try:
HEADER = bytearray("MTIC"[::-1])
I tested it and it works.



On Tuesday, 11 February 2014 06:55:03 UTC+1, Setia Budi  wrote:
> Hi fellows,
> 
> I am facing difficulties in order to send USB commands to an RFID reader.
> 
> This is the command reference of the device: 
> https://github.com/mti-rfid/RFID_Explorer
> 
> 
> 
> I am working with the MTI RU-824 model.
> 
> 
> 
> The manufacturer of the device only provide a driver for Windows (using 
> .Net), but we need to run the device on Linux. That's why I need to write few 
> lines of code in Python as a new "driver".
> 
> 
> 
> I am using PyUSB for accessing the device, and this is few lines of my code:
> 
> 
> 
> 
> 
> 
> 
> import usb.core
> 
> import usb.util
> 
> import sys
> 
> 
> 
> VENDOR_ID = 0x24e9
> 
> PRODUCT_ID = 0x0824
> 
> 
> 
> device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
> 
> 
> 
> if device is None:
> 
> sys.exit("Could not find Id System Barcode Reader.")
> 
> else:
> 
> print 'Device detected'
> 
> 
> 
> device.set_configuration()
> 
> 
> 
> cfg = device.get_active_configuration()
> 
> interface_number = cfg[(0, 0)].bInterfaceNumber
> 
> alternate_setting = usb.control.get_interface(device, interface_number)
> 
> usb_interface = usb.util.find_descriptor(
> 
> cfg, bInterfaceNumber=interface_number,
> 
> bAlternateSetting=alternate_setting
> 
> )
> 
> 
> 
> endpoint_out = usb.util.find_descriptor(
> 
> usb_interface,
> 
> # match the first OUT endpoint
> 
> custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == 
> usb.util.ENDPOINT_OUT
> 
> )
> 
> 
> 
> endpoint_in = usb.util.find_descriptor(
> 
> usb_interface,
> 
> # match the first IN endpoint
> 
> custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == 
> usb.util.ENDPOINT_IN
> 
> )
> 
> 
> 
> endpoint_out.write('0x01')
> 
> print endpoint_in.read(len('0x01'), 1000)
> 
> 
> 
> =
> 
> My question is on the last 2 lines.
> 
> I am using endpoint_out to send a command and endpoint_in to read data from 
> the reader. Am I correct?
> 
> 
> 
> The problem is, when I run the code, there is an error message like this: 
> 
> usb.core.USBError: [Errno 110] Operation timed out
> 
> 
> 
> Anyone can give a clue?
> 
> Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create python web framework for ERP

2014-09-09 Thread Andre Duarte
Vimal,

Django is a more generic framework(was built initialy for content management). 
Odoo is a valid sugestion but take some time to see Frappe.io. ERPNext was 
built on top of this framework and is a great application for small bussiness.

[]'s
André
-- 
https://mail.python.org/mailman/listinfo/python-list


Stack trace in C

2006-07-25 Thread Andre Poenitz


Bear with me - I am new to Python. (And redirect me to a more suitable
newsgroup in case this one is not appropriate.)

I am trying to embed Python into a C++ application and want to get back
a backtrace in case of errors in the python code.

This works well with e.g.

  import sys

  def u3():
xx() # raise an error

  def u2():
u3()

  def u1():
u2()

  def f():
try:
  u1()
except NameError:
  type, value, tb = sys.exc_info()
  #f = tb.tb_frame
  #while f:
  #   print f.f_lineno, f.f_code.co_name
  #   f = f.f_back
  #print "==="
  while tb:
  f = tb.tb_frame
  print f.f_lineno, f.f_code.co_name
  tb = tb.tb_next

  def d1():
f()

  def d2():
d1()

  d2()


on the python side.

However, I want to do that on the C side.


So far I have code similar to


  std::ostringstream msg;

  [...]
#if 1
// Branch 1
PyObject * exc_type = 0;
PyObject * exc_value = 0;
PyObject * exc_traceback = 0;
PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
PyObject * tb_frame = PyObject_GetAttrString(exc_traceback, "tb_frame");
#else
// Branch 2
PyObject * pName = PyString_FromString("sys");
PyObject * pModule = PyImport_Import(pName);
PyObject * pFunc = PyObject_GetAttrString(pModule, "exc_info");
PyObject * pResult = PyObject_CallObject(pFunc, NULL);
PyObject * tb_frame = PySequence_GetItem(pResult, 2);
#endif
while (tb_frame != Py_None) {
  PyObject * f_code = PyObject_GetAttrString(tb_frame, "f_code");
  PyObject * f_lineno = PyObject_GetAttrString(tb_frame, "f_lineno");
  int lineno = PyInt_AsLong(f_lineno);
  msg << " in line " << lineno << "\n";
  PyObject * tmp1 = PyObject_GetAttrString(tb_frame, "f_back");
  PyObject * tmp2 = PyObject_GetAttrString(tb_frame, "tb_next");
  // Now, neither tmp1 nor tmp2 is usable
  // tb_frame = tmpX;
}
  }


[Plus some reference counting/error checking code I left out] 

The 'Branch 1' version works for a sinmgle frame, but then tmp1 will be
None and tmp2 0 at the end of the iteration and so no further frames
are found.

The 'Branch 2' version creates immediatly tb_frame as None and
does not even enter the loop body once.

So what am I doing wrong? How do I get the equivalent of the python
code in C?
 
Andre'


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


class variables

2006-07-27 Thread Andre Meyer
Hi allI am trying to understand the magic of Python's class variables and tried the following code (see below).Just out of curiosity, I tried to define a property that provides access to a seemingly instancae variable which is in fact a class variable. All seems to work fine (case 4), but when a custom object is assigned, an instance variable is created instead of using theproerty (case 5).
What goes wrong here? What is the difference between cases 4 and 5? How can case 5 be fixed?thanks a lot for your helpAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

class variables

2006-07-27 Thread Andre Meyer
Hi allI am trying to understand the magic of Python's class variables and tried the following code (see below).Just
out of curiosity, I tried to define a property that provides access to
a seemingly instancae variable which is in fact a class variable. All
seems to work fine (case 4), but when a custom object is assigned, an
instance variable is created instead of using theproerty (case 5).
What goes wrong here? What is the difference between cases 4 and 5? How can case 5 be fixed?thanks a lot for your helpAndreCode Listing=print; print "*** Case 1 ***"; print
class C1(object):        v = None        def __init__(self, value):    print '-', self.v    self.v = value        def value(self):    return self.v    a1 = C1(1)
b1 = C1(2)print a1.value()print; print "*** Case 2 ***"; printclass C2(object):        v = None        def __init__(self, value):    print '-', self.v    self.__class__.v = value
        def value(self):    return self.__class__.v    a2 = C2(1)b2 = C2(2)print a2.value()print; print "*** Case 3 ***"; printclass C3(object):        v = 5
        def __init__(self, value):    print '-', self.v    self.v = self.v + value        def value(self):    return self.v    a3 = C3(1)b3 = C3(2)print a3.value()
print a3.vprint a3.__class__.vprint; print "*** Case 4 ***"; printclass V4(list):    def work(self):    return 'done'    class C4(object):        def __set_v(self, v): self.__class__.__v = v    
    def __get_v(self): return self.__class__.__v    def __del_v(self): del self.__class__.__v    v = property(__get_v, __set_v, __del_v, 'make class variable')    v = V4()        def __init__(self, value):
    print '-', self.v    self.v.append(value)    print '+', self.v        @classmethod    def value(self):    print self.v.work()    return self.v    a4 = C4(1)
b4 = C4(2)print a4.value()print a4.vprint a4.__class__.vprint a4.v.work()print; print "*** Case 5 ***"; printclass V5(object):    def __init__(self, i):    self.i
 = i        def work(self):    return 'done', self.i    class C5(object):        def __set_v(self, v): self.__class__.__v = v        def __get_v(self): return self.__class__.__v
    def __del_v(self): del self.__class__.__v    v = property(__get_v, __set_v, __del_v, 'make class variable')    v = None        def __init__(self, value):    print '-', self.v    self.v
 = V5(value)    print '+', self.v#    print self.__class__.__dict__#    print self.__dict__        @classmethod    def value(self):    print self.v.work()    return self.v
    a5 = C5(1)b5 = C5(2)print a5.value()print a5.vprint a5.__class__.vprint a5.v.work()Output=*** Case 1 ***- None- None1*** Case 2 ***
- None- 12*** Case 3 ***- 5- 5665*** Case 4 ***- []+ [1]- [1]+ [1, 2]done[1, 2][1, 2][1, 2]done*** Case 5 ***
- None+ <__main__.V5 object at 0x00AFE0D0>- None+ <__main__.V5 object at 0x00AFE110>Traceback (most recent call last):  File "classvariables.py", line 121, in ?    print a5.value
()  File "classvariables.py", line 115, in value    print self.v.work()AttributeError: 'NoneType' object has no attribute 'work'
-- 
http://mail.python.org/mailman/listinfo/python-list

singleton decorator

2006-08-07 Thread Andre Meyer
While looking for an elegant implementation of the singleton design pattern I came across the decorator as described in PEP318.Unfortunately, the following does not work, because decorators only work on functions or methods, but not on classes.
def singleton(cls):instances = {}def getinstance():if cls not in instances:instances[cls] = cls()
return instances[cls]return getinstance@singletonclass MyClass:...Am I missing something here? What is the preferred pythonic way of implementing singleton elegantly?Thanks for your help
André
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: class variables

2006-08-08 Thread Andre Meyer
On 7/31/06, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Colin J. Williams wrote:
> > Andre Meyer wrote:
> >> Hi all
> >>
> >> I am trying to understand the magic of Python's class variables and
> >> tried the following code (see below).
> >>
> >> Just out of curiosity, I tried to define a property that provides
> >> access to a seemingly instance variable which is in fact a class
> >> variable.
>
> [...]
>
> I'm afraid there are too much problems with indentation in the posted
> code to give any serious answer.


So, here we go again (plain formatting).

The following code shows two versions of using class variables. The
first one uses the __class__ attribute directly and works. The second
one tries to hide the __class__ attibute with the help of a property,
which does not work, because an assignment in the instance replaces
the property with the assigned value.

Any idea how the second version could be fixed with either a property
and/or a decorator?

thanks for your help
André



class Value(object):
def __init__(self, i):
self.i = i

def work(self):
return 'done', self.i


print; print "*** Case A ***"; print

class ClassA(object):
v = None

def __init__(self, value):

print '-', self.v
self.__class__.v = Value(value)
print '+', self.__class__.v

@classmethod
def value1(self):
print self.v.work()
return self.v

def value2(self):
print self.__class__.v.work()
return self.__class__.v


va1 = ClassA(1)
va2 = ClassA(2)
print va1.value1()
print va1.value2()
print va1.v
print va1.__class__.v
print va1.v.work()


print "*** Case B ***"; print

class ClassB(object):

def __set_v(self, v): self.__class__.__v = v
def __get_v(self): return self.__class__.__v
def __del_v(self): del self.__class__.__v
#v = property(__get_v, __set_v, __del_v, 'make class variable')
v = None

def __init__(self, value):
self.v = property(self.__get_v, self.__set_v, self.__del_v,
'make class variable')

print '-', self.v
self.v = Value(value)
print '+', self.v

@classmethod
def value1(self):
print self.v.work()
return self.v

def value2(self):
print self.v.work()
return self.v

vb1 = ClassB(1)
vb2 = ClassB(2)
print vb1.value2()
print vb1.v
print vb1.__class__.v
print vb1.v.work()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Easy to use distributed system?

2006-08-14 Thread Andre Meyer
Hi allWe are using Pyro, too, for our Multi-Agent System framework Spyse (http://spyse.sf.net). We support mobile agents, distributed environments, various threading models and a lot more.
Just ask if you are interested, but use the svn version, mot the 0.1 download. Our 1.0 release should be coming with a month.kind regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Best IDE for Python

2006-08-15 Thread Andre Meyer
PyDev is really nice. I use it a lot and it works great.It's just a bit heavy and why should one need a Java IDE for Python development ;-)Another "issue" is the lack of integration with a UML tool (code generation and reverse engineering), though an ArgoUML plugin is in the making (not for eclipse).
btw What Web/XML plugins are you using with eclipse?regardsAndreOn 15 Aug 2006 09:03:44 -0700, 
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
I've had a similar experience and tried about everything.  Personally -eclipse with PyDev has been the winner for me.  I also still do a bunchof Java coding - so there is an added benefit of one tool acrosslanguages.  The final thing I really like with eclipse is the svn
plugins - making life very easy.  Also, if your doing web/xml and otherstuff - there is a plugin for eclipse for it ;)  Not all the pluginswork as seemlessly together (i abandon eclipse for the majority of
plone/zope stuff - most of it isn't python - and setting up eclipse tobe happy with the output of archgen has not been worth the bother - I'msure it's possible)PyLint can kind of be a pain if your on a low powered box, but tweaking
the settings (and I had to do a bit of tweaking) can alleviate theproblems, but still let you reap the benefits.AnandYu-Xi Lim wrote:> Michiel Sikma wrote:> > By FOS, do you mean FOSS (Free and Open Source Software)? I've never
> > seen the acronym FOS used.>> Maybe he was trying for "Free Open Source IDE" without the> semi-redundant "Software">> > I personally use Eclipse with PyDev.
> > http://www.eclipse.org/> > http://pydev.sourceforge.net/>> Eclipse+PyDev has the advantage over emacs when it comes to big
> projects, IMO. It has features like refactoring, better project> management, code coverage. emacs has the advantage of being faster and> smaller, and if all you need is a syntax-aware (smart indentation,
> syntax highlighting) editor and integrated debugger, emacs is more than> enough.>> I've tried the other free IDEs like IDLE, SPE, eric3, TruStudio (for> Eclipse), Boa, Komodo, WingIDE. I have various issues with them,
> including instability, poor automatic indentation, bad GUI (too many> subwindows or uncustomizable), costly, no refactoring, and no project> management.>> It's strangely ironic. I consider Eclipse to be a lousy Java IDE
> especially compared to commercial offerings and yet that's what the> project started out as.--http://mail.python.org/mailman/listinfo/python-list
-- Dr. Andre P. Meyerhttp://python.openspace.nl/meyerTNO Defence, Security and Safety  
http://www.tno.nl/Delft Cooperation on Intelligent Systems  http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: state of SOAP and python?

2006-08-16 Thread Andre Meyer
I had success with ZSI: http://pywebsvcs.sourceforge.net/It worked very nicely for publishing a SOAP we service and accessing it from a client writtenusing the same library. What I didn't manage to achieve was to write the client in AJAX (tried 
http://www-128.ibm.com/developerworks/webservices/library/ws-wsajax/).regardsAndreOn 8/16/06, 
Mark Harrison <[EMAIL PROTECTED]> wrote:
Gabriel Genellina <[EMAIL PROTECTED]> wrote:> At Thursday 10/8/2006 03:38, Mark Harrison wrote:>> >So I'm investigating doing some SOAP work... Any concensus on
> >what the best python libraries are for doing this?> >> >Too bad, xmlrpc is choking on our long longs. :-(>> Just thinking, if you have control over the two ends, and dont need
> real interoperability, maybe just extending  to support long> integers could be easier...> I remember extending  once to support NaN's, moving to SOAP> was too much effort for that application.
Good thinking!  It turns out all you have to do is commentout the range check:def dump_int(self, value, write):# in case ints are > 32 bits##if value > MAXINT or value < MININT:
##raise OverflowError, "int exceeds XML-RPC limits"write("")write(str(value))write("\n")
Thanks,Mark--Mark HarrisonPixar Animation Studios--http://mail.python.org/mailman/listinfo/python-list
-- Dr. Andre P. Meyerhttp://python.openspace.nl/meyerTNO Defence, Security and Safety  
http://www.tno.nl/Delft Cooperation on Intelligent Systems  http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Loading module via full path

2006-08-21 Thread Andre Poenitz
Hi all.

Is there a way to load a module given a full path to the module
without extending sys.path first?

Andre'

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


Re: Stack trace in C

2006-08-21 Thread Andre Poenitz
Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz <[EMAIL PROTECTED]> wrote:
>>
>>
>>Bear with me - I am new to Python. (And redirect me to a more suitable
>>newsgroup in case this one is not appropriate.)
>>
>>I am trying to embed Python into a C++ application and want to get back
>>a backtrace in case of errors in the python code.
> 
> I think you'd have more luck with the traceback module, which has such
> methods as format_exception and print_tb.

That's where I got my 'inspiration' from.

Unfortunately my attempt to translate this into C failed, and I can't
see the reason.

Thanks for the hint nevertheless

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


Re: Stack trace in C

2006-08-21 Thread Andre Poenitz
Just <[EMAIL PROTECTED]> wrote:
> 
>> On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz  wrote:
>> >
>> >
>> >Bear with me - I am new to Python. (And redirect me to a more suitable
>> >newsgroup in case this one is not appropriate.)
>> >
>> >I am trying to embed Python into a C++ application and want to get back
>> >a backtrace in case of errors in the python code.
>> 
>> I think you'd have more luck with the traceback module, which has such
>> methods as format_exception and print_tb.
> 
> From C, PyErr_Print() is often handy (if only for debugging).

I'd like to display the backtrace i a fancy gui widget, and PyErr_Print
sends everything to stderr...

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


Re: Loading module via full path

2006-08-21 Thread Andre Poenitz
Andre Poenitz <[EMAIL PROTECTED]> wrote:
> Hi all.
> 
> Is there a way to load a module given a full path to the module
> without extending sys.path first?

Ok. imp.find_module() and imp.load_module() seem to do what I need.

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


Re: Loading module via full path

2006-08-22 Thread Andre Poenitz
Gary Herron <[EMAIL PROTECTED]> wrote:
> Andre Poenitz wrote:
>> Hi all.
>>
>> Is there a way to load a module given a full path to the module
>> without extending sys.path first?
>
> The standard module named "imp" can help you with this.

Thank you. I got stuck on http://docs.python.org/api/importing.html
(as I need it to be called from C(++)) and found no way to specify a path there
[and there aren't too many cross references in the python docs *sigh*]

I have now something similar to

class CPyObject
{
public:
  explicit CPyObject(PyObject * pObject) : m_pObject(pObject) { /*Check();*/ }
  ~CPyObject() { Py_XDECREF(m_pObject); }
  operator PyObject *() { return m_pObject; }
private:
  CPyObject(const CPyObject &);  // intentionally not implemented
  void operator=(const CPyObject &); // intentionally not implemented
  PyObject * m_pObject;
};

static PyObject * LoadModule(const char * mod, const char * path)
{
  CPyObject pyImpModule ( PyImport_Import(PyString_FromString("imp")) ); 

  CPyObject pyImpFindModuleFunc ( PyObject_GetAttrString(pyImpModule, 
"find_module") ); 
  CPyObject pyImpFindModuleArgs ( Py_BuildValue("s[s]", mod, path) );
  CPyObject pyImpFindModuleRes  ( PyObject_CallObject(pyImpFindModuleFunc, 
pyImpFindModuleArgs) ); 

  CPyObject pyImpLoadModuleFunc ( PyObject_GetAttrString(pyImpModule, 
"load_module") ); 
  CPyObject pyImpLoadModuleArgs ( Py_BuildValue("sOOO",
mod,
PyTuple_GetItem(pyImpFindModuleRes, 0),
PyTuple_GetItem(pyImpFindModuleRes, 1),
PyTuple_GetItem(pyImpFindModuleRes, 2)
  )); 
  return PyObject_CallObject(pyImpLoadModuleFunc, pyImpLoadModuleArgs);
}

which seems to do what I want even if it looks a bit too verbose for my taste 
and I
don't know whether I go the reference counting right.

Thanks for the hint,
Andre'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxWindow GetPosition() bug???

2006-08-22 Thread Andre Poenitz
mardif <[EMAIL PROTECTED]> wrote:
> Hi,
> I've found a strange behavior in method GetPosition() of wxWindow class
> 
> ( and derived ).
> On windows, if you create a window object
> 
> frame = wx.Frame(None, -1, "TESTING")
> 
> and you set the position to:
> frame.SetPosition( (300, 45000) )
> 
> If you call method GetPosition, the result will be:
> frame.GetPosition()
> >>> (300, 32767)
> 
> 32767 is the integer limit. Why GetPosition() returns this value??? and
> 
> why on Unix Platform this problem was not found??
> 
> thx very much!

Traditionally, there was a 16(15?) bit limit for coordinates on X Window
systems.

Maybe the wx implementations tries to be smarter than X itself and
restricts the positions artificially. Maybe Windows has sch a limit 
itself...

I don't really know, other than 'never try to access coordinates
that are 'much' bigger than what is actually visible'...

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


Re: How to download a web page just like a web browser do ?

2006-08-23 Thread Andre Meyer
You get websucker.py in the standard Python installation. On Win look at C:\Python24\Tools\webchecker or similar.regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Dumping the state of a deadlocked process

2006-10-06 Thread andre . naess
Hi all

I'm currently having some issues with a process getting deadlocked. The
problem is that the only way I can seem to find information about where
it deadlocks is by making a wild guess, insert a pdb.set_trace() before
this point, and then step until it locks up, hoping that I've guessed
right.

The frustrating part is that most of the time my guesses are wrong.

It would be really nice if I could send the python process some signal
which would cause it to print the current stacktrace and exit
immediately. That way I would quickly be able to pinpoint where in the
code the deadlock happens. Java has a somewhat similar feature where
you can send a running VM process a SIGQUIT, to which it will respond
by dumping all current threads and lots of other information on stdout.

Is this possible somehow?

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


Re: Dumping the state of a deadlocked process

2006-10-07 Thread andre . naess

MrJean1 wrote:
> Did you try using the signal module?  If not, a basic example is here
>  which may need to be
> extended.

I looks useful. I gave it a try, and the only weakness it has is that
when my process locks, it locks so badly that it doesn't respond to
CTRL-C, or any other signal. But by sending it a SIGQUIT which causes
it to dump the current state, and then kill it, I get the dump I need.

This is actually not a multi-threaded app. It's an application which
uses a SQL DB. The problem I was having was that I had a cursor which
started a transaction, and then never finished. Then some other cursor
came along and tried to perform a delete table, and they both locked
up. The cursor isn't ending it's transaction, and the transaction
prevents the delete table from being executed. Luckily Postgresql
allows me to list current activity, otherwise I would have been
scratching my head still.

Using logging or print statements to debug this sort of things is
highly unsatisfactory. I think the way Java uses SIGQUIT is pretty
neat, are there any reasons why Python can't adopt something similar?

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


Re: Feature Request: Py_NewInterpreter to create separate GIL (branch)

2006-11-03 Thread Andre Meyer
Hi allStrange enough, there does not even seem to be interest in removing the GIL in Python 3000.For some interesting answers on this topic you may read through the thread "Kill GIL" on the py3k mailing list archives:
<http://mail.python.org/pipermail/python-3000/2006-September/thread.html>.kind regardsAndré
On 11/3/06, robert <[EMAIL PROTECTED]> wrote:
Feature Request: Py_NewInterpreter to create separate GIL (branch)Daniel Dittmar wrote:> robert wrote:>> I'd like to use multiple CPU cores for selected time consuming Python>> computations (incl. numpy/scipy) in a frictionless manner.
>>>> Interprocess communication is tedious and out of question, so I>> thought about simply using a more Python interpreter instances>> (Py_NewInterpreter) with extra GIL in the same process.
>> If I understand Python/ceval.c, the GIL is really global, not specific> to an interpreter instance:> static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */>Thats the show stopper as of now.
There are only a handfull funcs in ceval.c to use that very global lock. The rest uses that funcs around thread states.Would it be a possibilty in next Python to have the lock separate for each Interpreter instance.
Thus: have *interpreter_lock separate in each PyThreadState instance and only threads of same Interpreter have same GIL?Separation between Interpreters seems to be enough. The Interpreter runs mainly on the stack. Possibly only very few global C-level resources would require individual extra locks.
Sooner or later Python will have to answer the multi-processor question.A per-interpreter GIL and a nice module for tunneling Python-Objects directly between Interpreters inside one process might be the answer at the right border-line ? Existing extension code base would remain compatible, as far as there is already decent locking on module globals, which is the the usual case.
Robert--http://mail.python.org/mailman/listinfo/python-list-- Dr. Andre P. Meyer
http://python.openspace.nl/meyerTNO Defence, Security and Safety  http://www.tno.nl/Delft Cooperation on Intelligent Systems  
http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

dictionaries vs. objects

2006-08-24 Thread Andre Meyer
Hi allI have the following question: I need a representation of a physically inspired environment. The environment contains a large number of objects with varying attributes. There may be classes of objects, but there is not necessarily a strictly defined hierarchy among them. Object access should be fast, because there a many objects that change often (
e.g., moving objects).My approach is to use a dictionary for the environment model and store each object as a slot, which contains either a dictionary or an object. Now, which is better? What is the performance of Python to look up attributes as either slots of a dictionary or attributes of an object? What feels more logical? What is more pythonic and performs better? Which is constructed and modified easier and quicker? Are there effects that I am not yet aware of?
thanks for your thoughtsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

performance of dictionary lookup vs. object attributes

2006-08-25 Thread Andre Meyer

Hi all

I was wondering about the performance comparison of either using a
dictionary or an object for a large collection of "things". Therefore
I have run the attached test. I create a dictionary and an object.
Both get the same number of items/attributes, respectively. Then, for
both the values are read often (iterations).

Here are the results:

attributes 100
iterations 100
dic 25.515999794
obj 138.57172

Is the test meaningful and are you surprised by the results? I am,
actually, because I would have assumed that attribute access with an
object should be faster because lookup can be precompiled.

kind regards
Andre
import time
import random

ITERATIONS = 100
ATTRIBUTES = 100

class O(object):
pass

class Test(object):
def __init__(self):
self.attributes = []
self.dic = {}
self.obj = O()

for i in range(ATTRIBUTES):
value = ""
for s in range(12):
value = value + chr(random.randint(ord('a'), ord('z')))
#print value

attr = ""
for s in range(6):
attr = attr + chr(random.randint(ord('a'), ord('z')))
#print attr

self.attributes.append(attr)
self.dic[attr] = value
self.obj.__setattr__(attr, value)

print "attributes", len(self.attributes)

def run_dic(self):
t0 = time.time()
for i in range(ITERATIONS):
for a in self.attributes:
v = self.dic[a]
#print i, v
t1 = time.time()
return t1 - t0

def run_obj(self):
t0 = time.time()
for i in range(ITERATIONS):
for a in self.attributes:
v = self.obj.__getattribute__(a)
#print i, v
t1 = time.time()
return t1 - t0

print "iterations", ITERATIONS

t = Test()
td = t.run_dic()
to = t.run_obj()

print "dic", td
print "obj", to
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: performance of dictionary lookup vs. object attributes

2006-08-25 Thread Andre Meyer
Good points! It's always good to learn from the pros!

So, what it means is that the test is not meaningful, because of the
different way that object attributes are accessed (not as o.x, which
could be compiled).

Nevertheless, the general impression remains that dicts *are* faster
than objects, because attribute lookup uses dicts itself. Is that
correct?

thanks
Andre


On 8/25/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Andre Meyer wrote:
>
> > Is the test meaningful and are you surprised by the results?
>
> surprised by the amount of code you needed to test this, at least.  and you
> might wish to use the proper spelling for
>
> v = self.obj.__getattribute__(a)
>
> which is
>
> v = getattr(obj, a)
>
> and is quite a bit faster, at least in CPython.
>
> (you should also use setattr() instead of __setattr__; in general, if you 
> find your-
> self *calling* a method named __method__, there's most likely a better way to
> do it).
>
> > I am, actually, because I would have assumed that attribute access with an
> > object should be faster because lookup can be precompiled.
>
> huh?  you're using a reflection API; there's no way the compiler can figure 
> out
> in advance what you're going to pass to getattr().
>
> 
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I
wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-08-26 Thread Andre Meyer
http://www.python.org/download/releases/2.4/bugs/IDLE now executes code in a separate process.  To communicate
between the main process and executing processes, IDLE opens a
socket to 127.0.0.1 (the local machine).  Some firewalls running on
Windows machines interfere with this and can cause either silent
failures or erroneous popup windows from the firewall.  This problem
only occurs if you run a firewall on the same machine as IDLE.
hthAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Persistent Session in CGI

2006-08-27 Thread Andre Meyer
Karrigell is a very easy-to-use pure-Python web framework. It has examples of session management.http://karrigell.sourceforge.net/regardsAndre
On 27 Aug 2006 14:48:05 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:Hi,I have started a new small web project, and was wondering if there are
any good guides on how to do Persistent Sessions and Authenticationusing python and CGI. I don't really want too use Zope, because It'sprobably overkill for my tiny project.--
http://mail.python.org/mailman/listinfo/python-list-- Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/Delft Cooperation on Intelligent Systems  http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pros/Cons of Turbogears/Rails?

2006-08-28 Thread Andre Meyer
Hi allIt might be interesting to watch the videos about Django and Rails (http://www.djangoproject.com/snakesandrubies/). Django makes a good impression, although I would not agree with all of their arguments (eg. templating language, ajax). Most striking, though, is the difference in attitude! While Django grew out of a production environment and solves real problems very elegantly, Rails comes "out of beauty", whatever that means. Is Ruby code more beautiful than Python - don't think so.
Nevertheless, I agree with original statement that we Python guys need to look very closely at Ruby and why they are able to catch so much attention. There are good things in the language and Python marketing could certainly be improved. The new web site and logo are good steps in the right direction. Now for free t-shirts to create pervasive awareness? ;-)
regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: dictionaries vs. objects

2006-08-31 Thread Andre Meyer
On 8/28/06, Steve Holden <[EMAIL PROTECTED]> wrote:
Andre Meyer wrote:> Hi all>> I have the following question: I need a representation of a physically> inspired environment. The environment contains a large number of objects> with varying attributes. There may be classes of objects, but there is
> not necessarily a strictly defined hierarchy among them. Object access> should be fast, because there a many objects that change often ( e.g.,> moving objects).>> My approach is to use a dictionary for the environment model and store
> each object as a slot, which contains either a dictionary or an object.> Now, which is better? What is the performance of Python to look up> attributes as either slots of a dictionary or attributes of an object?
> What feels more logical? What is more pythonic and performs better?> Which is constructed and modified easier and quicker? Are there effects> that I am not yet aware of?>I'd suggest using objects: quite apart from the fact that name lookup in
a namespace is pretty much equivalent to a dictionary lookup (namespacesuse an internal optimised dictionary-style object) remember that objectscan have methods, and that the names are given as attributes rather than
as strings.From another thread I learned that lookup in dictionaries is way faster than accessing object attributes (which makes use of an internal dictionary). However, the syntax is cleaner with objects and having methods and properties is a plus. So, it seems like it is about speed vs. elegance...
regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: threading support in python

2006-09-05 Thread Andre Meyer
This seems to be an important issue and fit for discussion in the context of Py3k. What is Guido's opinion?As a developer of a multi-threaded system I would like to know more about these issues, so it's no time wasted for me... ;-)
regardsAndreOn 9/5/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
Steve> Given the effort that GIL-removal would take, I'm beginning toSteve> wonder if PyPy doesn't offer a better way forward than CPython,
Steve> in terms of execution speed improvements returned perSteve> developer-hour.How about execution speed improvements per hour of discussion about removingthe GIL? ;-)

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

Re: IDE

2006-09-06 Thread Andre Meyer
http://pydev.sourceforge.net/http://wiki.python.org/moin/PythonEditors
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: python vs java

2006-09-06 Thread Andre Meyer
http://www.ferg.org/projects/python_java_side-by-side.html
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: the first arg to super() must be a type, not a class obj?

2006-09-08 Thread Andre Meyer
Another thing: how does super() work wrt. multiple inheritance? It seems like it returns only the first superclass.regardsAndreOn 9/8/06, 
Georg Brandl <[EMAIL PROTECTED]> wrote:
metaperl wrote:> On p.282 of "Python Cookbook" and in the Python docs on calling super:> http://www.python.org/download/releases/2.2.3/descrintro/#cooperation
>> it is clear that the first argument to super is a class and not a type.> However, for the code below, I am getting an error when attempting to> provide a class as my first argument and don't understand why. Also,
> since this is my first attempt at writing anything of any seriousness> in Python, any other feedback is welcome."super" only works for new-style classes.You could make "ftputilx" new-style by inheriting from object and FTPHost,
but FTPHost is still old-style, and I don't know if that's okay with super.So in your case it would be advisable to useFTPHost.__init__(self)instead ofsuper(ftputilx, self).__init__()
Georg--http://mail.python.org/mailman/listinfo/python-list-- Dr. Andre P. Meyer
http://python.openspace.nl/meyerTNO Defence, Security and Safety  http://www.tno.nl/Delft Cooperation on Intelligent Systems  
http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Building Python Based Web Application

2006-09-09 Thread Andre Meyer
Karrigell can really be recommended. Simple, but powerful. No need for SQL (though it can), just use the pure Python buzhug, Karrigell services and (Cheetah) templates. Works great.regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: best small database?

2006-09-11 Thread Andre Meyer
buzhug is a nice one: http://buzhug.sourceforge.net/ (not sure about binaries, though).greetingsAndreOn 9/11/06, 
km <[EMAIL PROTECTED]> wrote:
checkout gadfly database.regards,KMOn 9/11/06, David Isaac
 <[EMAIL PROTECTED]> wrote:

I have no experience with database applications.This database will likely hold only a few hundred items,including both textfiles and binary files.I would like a pure Python solution to the extent reasonable.
Suggestions?Thank you,Alan Isaac--http://mail.python.org/mailman/listinfo/python-list


--http://mail.python.org/mailman/listinfo/python-list
-- Dr. Andre P. Meyerhttp://python.openspace.nl/meyerTNO Defence, Security and Safety  
http://www.tno.nl/Delft Cooperation on Intelligent Systems  http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Help me use my Dual Core CPU!

2006-09-17 Thread Andre Meyer
You may, of course, also have a look at JavaSpaces or TSpaces (both in Java).JavaSpaceshttp://java.sun.com/docs/books/jini/javaspaces/
http://java.sun.com/developer/technicalArticles/tools/JavaSpaces/index.htmlhttp://www.javaworld.com/jw-11-1999/jw-11-jiniology.htmlTSpaces
http://www.almaden.ibm.com/cs/TSpaces/http://www.alphaworks.ibm.com/tech/tspacesOr read the original tuple space articles by David Gelernter:
http://en.wikipedia.org/wiki/David_Gelernterhttp://portal.acm.org/citation.cfm?id=2433
http://citeseer.ist.psu.edu/14383.htmlTuple spaces are cool ;-)On 9/17/06, Ramon Diaz-Uriarte <
[EMAIL PROTECTED]> wrote:On 17 Sep 2006 00:55:09 -0700, Paul Rubin<"
http://phr.cx"@nospam.invalid> wrote:> "Ramon Diaz-Uriarte" <[EMAIL PROTECTED]> writes:> > You might also want to check
> > http://www.lindaspaces.com/products/NWS_overview.html52> > by the guys who "invented" Linda.>> Cool, I guess.
I've only played a little bit with it, but it does certainly looknice. Nick Carriero (from network spaces) also developed a similarthing for R, the GNU S statistical programming language (also from the
above url), and the demonstration I saw of it was _really_ impressive.> I looked at these.  Oz/Mozart is a whole nother language, worth> examining for its ideas, but the implementation is quite slow.
Yes, that is true. On the plus side, though, the "Concepts,techniques, and models of computer programming" book, by Van Roy andHaridi, uses Oz/Mozart, so you get a thorough, pedagogical, andextended ---900 pages--- "tutorial" of it. But the speed and, so far,
limited ways of being friendly to other languages, can be showstoppers.> Kamaelia doesn't attempt concurrency at all.  Its main idea is to use> generators to simulate microthreads.  Candygram is a module that lets
> you write code in Python that's sort of like Erlang code, but it uses> OS threads for the equivalent of Erlang processes.  That misses the> point of Erlang pretty badly, which is that processes are extremely
> lightweight (i.e. normally they are microthreads) so you can have> millions of them active simultaneously (e.g. one for each active> telephone connected to a big phone switch).Thanks for the clarification (I had only cursorily looked at them).
>> Right now I want to check out GHCI (the Glasgow Haskell compiler),> which may be the closest thing to a "winner":>>   - very advanced language, even higher level than Python, once described
> by somebody as "what Python should have become">   - native code compilation>   - lock-free concurrency using software transactional memory (STM)Thanks for this. I'll check it out!!
Best,R.--http://mail.python.org/mailman/listinfo/python-list-- Dr. Andre P. Meyer
http://python.openspace.nl/meyerTNO Defence, Security and Safety  http://www.tno.nl/Delft Cooperation on Intelligent Systems  
http://www.decis.nl/Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Porting Tkinter application to JYthon

2006-11-23 Thread Andre Burgaud

Hi Sandip,

JPype could be a solution to implement the second option mentioned by Tim:
http://jpype.sourceforge.net/

Thanks,

Andre
http://www.burgaud.com/




On 23 Nov 2006 05:36:46 -0800, Tim N. van der Leeuw <[EMAIL PROTECTED]>
wrote:


Hi,

sandip desale wrote:
> Dear All,
>
> We have a Tcl/Tk application written using Python 2.2. Using this
application we want to call some customizable Java APIs. I tried porting
Tcl/Tk application to Jython but not able to do the same as TKinter library
is not available with JYthon.
>
> Can you please help me in porting Tkinter application to Jython? Also
kindly let me know how to do the same.

Not having Tkinter in Jython, you can either rewrite your app to be a
Java Swing app, or you can embed the Java JVM into the Python
interpreter as an importable library. I believe some projects exist to
enable the latter, although I don't know of a URL.

Cheers,

--Tim
>
>
> Thanks & Regards,
> Sandip Desale
>
>
> --
>
> Search for products and services at:
> http://search.mail.com

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

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

synching with os.walk()

2006-11-24 Thread Andre Meyer

Hi all

os.walk() is a nice generator for performing actions on all files in a
directory and subdirectories. However, how can one use os.walk() for walking
through two hierarchies at once? I want to synchronise two directories (just
backup for now), but cannot see how I can traverse a second one. I do this
now with os.listdir() recursively, which works fine, but I am afraid that
recursion can become inefficient for large hierarchies.

thanks for your help
André
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: synching with os.walk()

2006-11-24 Thread Andre Meyer

That sounds like a good approach.

On 24 Nov 2006 08:27:09 -0800, Paddy <[EMAIL PROTECTED]> wrote:



Andre Meyer wrote:

> Hi all
>
> os.walk() is a nice generator for performing actions on all files in a
> directory and subdirectories. However, how can one use os.walk() for
walking
> through two hierarchies at once? I want to synchronise two directories
(just
> backup for now), but cannot see how I can traverse a second one. I do
this
> now with os.listdir() recursively, which works fine, but I am afraid
that
> recursion can become inefficient for large hierarchies.
>
> thanks for your help
> André

Walk each tree individually gathering file names relative to the head
of the tree and modification data.

compare the two sets of data to generate:
1. A list of what needs to be copied from the original to the copy.
2. A list of what needs to be copied from the copy to the original

Do the copying.

|You might want to show the user what needs to be done and give them
the option of aborting after generating the copy lists.

- Paddy.

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

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

Re: synching with os.walk()

2006-11-24 Thread Andre Meyer

What I forgot to mention is that I want this to run unmodified from both
Windows and Linux (and Mac). Otherwise, there are enough options to choose
from, besides developing it myself, I guess.

On 24 Nov 2006 08:37:13 -0800, Paddy <[EMAIL PROTECTED]> wrote:



Paddy wrote:

> Andre Meyer wrote:
>
> > Hi all
> >
> > os.walk() is a nice generator for performing actions on all files in a
> > directory and subdirectories. However, how can one use os.walk() for
walking
> > through two hierarchies at once? I want to synchronise two directories
(just
> > backup for now), but cannot see how I can traverse a second one. I do
this
> > now with os.listdir() recursively, which works fine, but I am afraid
that
> > recursion can become inefficient for large hierarchies.
> >
> > thanks for your help
> > André
>
> Walk each tree individually gathering file names relative to the head
> of the tree and modification data.
>
> compare the two sets of data to generate:
>  1. A list of what needs to be copied from the original to the copy.
>  2. A list of what needs to be copied from the copy to the original
>
> Do the copying.
>
> |You might want to show the user what needs to be done and give them
> the option of aborting after generating the copy lists.
>
> - Paddy.
P.S. If you are on a Unix type system you can use tar to do the copying
as you can easily compress the data if it needs to go over a sow link,
and tar will take care of creating any needed directories in the
destination if you create new directories as well as new files.
- Paddy.

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





--
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I wasn't
previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: synching with os.walk()

2006-11-24 Thread Andre Meyer

Cool, this seems to work.

thanks!


On 24 Nov 2006 08:12:08 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


> os.walk() is a nice generator for performing actions on all files in a
> directory and subdirectories. However, how can one use os.walk() for
walking
> through two hierarchies at once? I want to synchronise two directories
(just
> backup for now), but cannot see how I can traverse a second one. I do
this
> now with os.listdir() recursively, which works fine, but I am afraid
that
> recursion can become inefficient for large hierarchies.

I've run into wanting to work with parallel directory structures
before, and what I generally do is something like:

for root, dirs, files in os.walk( dir1 ):
  dir2_root = dir2 + root[len(dir1):]
  for f in files:
dir1_path = os.path.join( root, f )
dir2_path = os.path.join( dir2_root, f )

Does this work for your needs?
-- Nils

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





--
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I wasn't
previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

route planning

2006-12-01 Thread Andre Meyer

Hi all

Just a very simple question: where can I find a module for route planning?

I have looked around and found some implementations of graph theory, e.g.
http://sourceforge.net/projects/pynetwork/. But, what I need is not an
abstract graph, but one where nodes/vertices have locations (2D), are
connected (to follow a path, respecting distance among nodes) and where I
can easily find the closest edge and vertex from any point in space.

your links are much appreciated
thanks
André
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Plugin for Web Browser

2006-12-06 Thread Andre Meyer

Hi

I was looking for something similar in the past and could not find it. It
would be very useful to have Python applets in web pages. What would you use
them for?

kind regards
André



On 5 Dec 2006 23:59:29 -0800, Sébastien Ramage <[EMAIL PROTECTED]>
wrote:


des exemples de plugins pour IE oui mais qui ne sont pas embarqué dans
une page Web
je souhaiterai créer qqchose qui ressemble vraiment à Java VM ou
Flash
J'ai trouvé un début de réponse pour Firefox en télécharger le
GeckoSDK
mais je n'arrive pas à compiler les exemples pour le moment...

merci


MC a écrit :

> Bonjour !
>
> Pour IE, il y a des exemples de plugins, fournis avec PyWin32.
> Pour FF (comme pour Opera), je ne sais pas.
>
> --
> @-salutations
>
> Michel Claveau



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





--
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I wasn't
previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Plugin for Web Browser

2006-12-06 Thread Andre Meyer

Hi Sebastien

Yes, I am a developer, but not C/C++. I have done Java (and many other
languages) in the past, but use Python nowadays.

So, I am no help for developing the plugin, sorry. I would want to use it
though for developing richer Web sites in Python, rather than in
JavaScript/Ajax. Having said that: maybe you are also interested in pyjamas
(http://pyjamas.pyworks.org/).

kind regards
André



On 12/6/06, Sebastien Ramage <[EMAIL PROTECTED]> wrote:


Hi

Thank you for your reply.
Yes ! It would be very useful and easy to develop (the applet not the
plugin) !

I don't have real project at this time but, I like Python and use it every
day. Many time I want to make an applet for game, or webcam remote control
but I don't understand and I don't want to learn Java when I know the
powerful python.
Are you a developper? C++ ?

Seb




2006/12/6, Andre Meyer <[EMAIL PROTECTED]>:
>
> Hi
>
> I was looking for something similar in the past and could not find it.
> It would be very useful to have Python applets in web pages. What would you
> use them for?
>
> kind regards
> André
>
>
>
> On 5 Dec 2006 23:59:29 -0800, Sébastien Ramage <[EMAIL PROTECTED]
> > wrote:
> >
> > des exemples de plugins pour IE oui mais qui ne sont pas embarqué dans
> > une page Web
> > je souhaiterai créer qqchose qui ressemble vraiment à Java VM ou
> > Flash
> > J'ai trouvé un début de réponse pour Firefox en télécharger le
> > GeckoSDK
> > mais je n'arrive pas à compiler les exemples pour le moment...
> >
> > merci
> >
> >
> > MC a écrit :
> >
> > > Bonjour !
> > >
> > > Pour IE, il y a des exemples de plugins, fournis avec PyWin32.
> > > Pour FF (comme pour Opera), je ne sais pas.
> > >
> > > --
> > > @-salutations
> > >
> > > Michel Claveau
> >
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
>
>
> --
> Dr. Andre P. Meyer    http://python.openspace.nl/meyer
>
> TNO Defence, Security and Safety   http://www.tno.nl/
> Delft Cooperation on Intelligent Systems  http://www.decis.nl/
>
> Ah, this is obviously some strange usage of the word 'safe' that I
> wasn't previously aware of. - Douglas Adams






--
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I wasn't
previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: funcs without () like print

2006-12-07 Thread Andre Meyer

print is supposed to become a function in Py3k, though.


On 12/7/06, Georg Brandl <[EMAIL PROTECTED]> wrote:


iwl wrote:
> Hello can I make funktions callable without () like print
> at time the interpreter seems to printout the adres when I type the
> function without ()

print is not a function, it's a statement, and as such equivalent to
raise or assert.



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

Re: Is anyone using Python for embedded applications?

2006-12-13 Thread Andre Meyer

Not sure what your target embedded platform is, but there is a Python
version for the Nokia S60 mobile phone platform (Symbian).

http://s60.com/

Python for 
S60<http://www.forum.nokia.com/info/sw.nokia.com/id/ee447e84-2851-471a-8387-3434345f2eb0/Python_for_S60.html>
Python for S60 allows developers to execute Python commands and run Python
scripts and applications in devices based on S60 Platform. In addition,
developers can execute Python commands and scripts in the emulators of S60
Developer Platform SDKs. Development starts with an interactive console in a
S60 compatible device where Python commands can be executed.

hth
Andre

On 12/12/06, Carl J. Van Arsdall <[EMAIL PROTECTED]> wrote:


I'm aware of a couple python projects for embedded systems.  I am
currently considering using Python on an embedded platform to develop a
simple application as a personal project, mostly to see if it will
work.  I was wondering if anyone here was using python for anything of
that nature?  For those that are involved in these types of projects,
how does development in python differ for embedded projects versus a
non-embedded project?  Is there a community standard technique or style
for this type of development (i.e. heavy in OO design? commonly used
patterns?)  Are there any good tools to assist for this type of
development environment?

Oh, and if anyone has opinions/facts on why python should not be used in
an embedded platform, I'd like to know that too.  I'm somewhat familiar
with pythons needs on a system, but there are a number of things I am
not aware of.

Thanks to everyone for their input!

-carl

--

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release


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





--
Dr. Andre P. Meyerhttp://python.openspace.nl/meyer
TNO Defence, Security and Safety  http://www.tno.nl/
Delft Cooperation on Intelligent Systems  http://www.decis.nl/

Ah, this is obviously some strange usage of the word 'safe' that I wasn't
previously aware of. - Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [Edu-sig] automatically grading small programming assignments

2006-12-14 Thread Andre Roberge

Hello Brian,

I do not teach (much to my regrets) but I have been thinking about what you
describe.
See below.

On 12/14/06, Brian Blais < [EMAIL PROTECTED]> wrote:


Hello,

I have a couple of classes where I teach introductory programming using
Python.  What
I would love to have is for the students to go through a lot of very small
programs,
to learn the basic programming structure.  Things like, return the maximum
in a list,
making lists with certain patterns, very simple string parsing,
etc.  Unfortunately,
it takes a lot of time to grade such things by hand, so I would like to
automate it
as much as possible.



I envision a number of possible solutions.  In one solution, I provide a

function
template with a docstring, and they have to fill it in to past a
doctest.  Is there a
good (and safe) way to do that online?  Something like having a student
post code,
and the doctest returns.  I'd love to allow them to submit until they get
it, logging
each attempt.



I may have a partial solution.  I (co-)wrote a program called Crunchy
(crunchy.sf.net)
which, among other features, allow automated correction of code that has to
satisfy a given docstring. As it stands, it only allows self-evaluation i.e.
there's no login required nor is the solution forwarded to someone else.
(This has been requested by others and may, eventually, be incorporated in
Crunchy.)  So, as a tool for learning, it's working; the grading component
is simply not there.  However, the code is open-source and you could adopt
it to your needs ;-)

André


Or perhaps there is a better way to do this sort of thing.  How do others

who teach
Python handle this?


thanks,


Brian Blais

--
-

  [EMAIL PROTECTED]
  http://web.bryant.edu/~bblais
___
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

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

Re: Python equivilant to msgbox()

2006-02-12 Thread Andre Burgaud
Hi,
 
If you target Windows, you may try ctypes http://starship.python.net/crew/theller/ctypes/:
 
>>> from ctypes import *>>> windll.user32.MessageBoxA(None, "MessageBox Text", "MessageBox Caption", 0)1>>>
 
 
or win32api http://starship.python.net/crew/mhammond/win32/:
>>> import win32api>>> win32api.MessageBox(0, "Text", "Title")1>>>
 
Regards,
 
Andre
http://www.burgaud.com/
 
On 2/12/06, LittlePython <[EMAIL PROTECTED]> wrote:

Is there an equivalent to a msgbox() or wscript.echo (via wcsript) . I would like to call this instead of print (to the screen) . I would like to write a simple script that is not an event drive gui but calls input boxes, message boxes, or maybe even a file open browser box as well? 
--http://mail.python.org/mailman/listinfo/python-list

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

Re: Python equivilant to msgbox()

2006-02-13 Thread Andre Roberge
On 2/13/06, Peter Decker <[EMAIL PROTECTED]> wrote:
> On 12 Feb 2006 17:27:56 -0800, André <[EMAIL PROTECTED]> wrote:
>
> > It's also possible to something like that with wxPython.  Try:
> > import wx
> > app = wx.PySimpleApp()
> > dlg = wx.TextEntryDialog(None, 'Enter value', 'Title', '')
> > if dlg.ShowModal() == wx.ID_OK:
> > val = dlg.GetValue()  # this line should be indented
> > dlg.Destroy()
> > print "you have entered %s" % val
>
> That's the sort of butt-ugly code that got me convinced that Dabo is
> the way to go. To get a simple message box, you have to create it,
> show it, check a return value against an ugly constant (make sure you
> don't forget an use wx.OK instead!), and then remember to destroy it
> or your app will hang.
>
> The same code in Dabo is:
>
> val = dabo.ui.getString("Enter value", "Some Title")
> if val in None:
>print "You canceled"
> else:
>print "You entered %s" % val
>
> Look at both examples, and tell me which looks more Pythonic to you.

While I agree that dabo's version is more Pythonic than wxPython, my
understanding is that dabo is built on top of wxPython.  There are
other framework (wax, anygui) that also aim to make the coding "more
pythonic", hiding "ugly" wxPython details.  Personnally, I am hesitant
to start using an extra layer on top of wxPython, with no guarantee
that it will be always updated.  Ideally, something like dabo+wxPython
would become part of the standard Python distribution.

The original post was asking if it was possible to have such message
dialogs using Python, without having a full gui app.  I'd say that the
answer is yes... and that one has a lot of options, depending on how
many packages one is ready to download.

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


Re: c[:]()

2007-06-01 Thread Andre Engels
2007/6/1, Warren Stringer <[EMAIL PROTECTED]>:

> I am not insisting on anything. I use ``c[:]()`` as shorthand way of saying
> "c() for c in d where d is a container"
>
> Having c() support containers seems obvious to me. It jibes with duck
> typing. Perhaps the title of this thread should have been: "Why don't
> containers quack?"
>
> A change is surprising only if it breaks something. I still haven't seen any
> code that breaks by making such a change. Seeing such code would teach a
> great deal.

I think it very much bites duck typing. Currently, if I try to execute
a string or a list or whatever, I get:

TypeError: 'str' object is not callable

But under your proposed semantics, suppose a is a list with some
executable and some non-executable elements. What should

a()

now give? It cannot be a TypeError, because a list (in your semantics)
is callable. Whatever error it gives, and whether or not the preceding
executables are executed first, it will not be an existing error
acting the way it normally does - there is no Python error for "you
cannot do this with this object, but you can do it with other objects
of the same type". And that does not seem to be a case of "We have
never needed it yet" - the join method seems to have been specifically
tailored so that no such error is needed.


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error when calling method of class

2007-06-08 Thread Andre Engels
2007/6/8, Sean Farrow <[EMAIL PROTECTED]>:
> Hi:
> I have defined a class in that class is a method defined as follows:
> def splitTime(n):
> seconds =float(n)
> I call the method in another procedure as follows:
> sefl.splitTime(200)
> the traceback states that splitTime takes one argument two given. why is
> this occuring?
> if I try calling it like:
> splitTime(200)
> I get a name resultion error saying that the global name splitTime is
> not defined.
> Any help apreciated.

In self.splitTime(200), self is considered an argument as well, thus
the definition should be done with:

def splitTime(self,n):

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


Ang roskilde billet

2007-06-09 Thread andre lerche

Hej

Jeg er interesseret i at købe din billet, jeg bor selv på amager, så vi kan
gøre en hurtig handel.

Mvh

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

Re: skip next item in list

2007-06-11 Thread Andre Engels
2007/6/11, ahlongxp <[EMAIL PROTECTED]>:
> list=('a','d','c','d')
> for a in list:
> if a=='a' :
> #skip the letter affer 'a'
>
> what am I supposed to do?

There might be better ways to do it, but I would do:

flag_last_a = False
for a in list:
   if flag_last_a:
   flag_last_a = False
   continue
   if a=='a':
   flag_last_a = True
   # Whatever is done when you don't skip

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question about unicode in python

2007-06-13 Thread Andre Engels
2007/6/12, WolfgangZ <[EMAIL PROTECTED]>:
> hzqij schrieb:
> > i have a python source code test.py
> >
> > # -*- coding: UTF-8 -*-
> >
> > # s is a unicode string, include chinese
> > s = u'张三'
> >
> > then i run
> >
> > $ python test.py
> > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1:
> > invalid data
> >
> > by in python interactive, it is right
> >
> >>>> s = u'张三'
> >
> > why?
> >
> >
>
> just an idea: is your text editor really supporting utf-8? In the mail
> it is only displayed as '??' which looks for me as the mail editor did
> not send the mail as utf. Try to attach a correct text file.

That must be your mail client, not his text editor or mail client. I
do see two Chinese characters in the message.

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: web page text extractor

2007-07-12 Thread Andre Engels
2007/7/12, kublai <[EMAIL PROTECTED]>:

> For a project, I need to develop a corpus of online news stories.  I'm
> looking for an application that, given the url of a web page, "copies"
> the rendered text of the web page (not the source HTNL text), opens a
> text editor (Notepad), and displays the copied text for the user to
> examine and save into a text file. Graphics and sidebars to be
> ignored. The examples I have come across are much too complex for me
> to customize for this simple job. Can anyone lead me to the right
> direction?

def textonly(url):
   # Get the HTML source on url and give only the main text
   f = urllib2.urlopen(url)
   text = f.read()
   r = re.compile('\<[^\<\>]*\>')
   newtext = r.sub('',text)
   while newtext != text:
  text = newtext
  newtext = r.sub('',text)
   return text



-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web page text extractor

2007-07-12 Thread Andre Engels
2007/7/12, Andre Engels <[EMAIL PROTECTED]>:

I forgot to include

import urllib2, re

here

> def textonly(url):
># Get the HTML source on url and give only the main text
>f = urllib2.urlopen(url)
>text = f.read()
>r = re.compile('\<[^\<\>]*\>')
>newtext = r.sub('',text)
>while newtext != text:
>   text = newtext
>   newtext = r.sub('',text)
>return text


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coming from delphi - looking for an IDE - willing to spend money

2006-04-24 Thread Andre Burgaud
Hi James,There are many different IDE available for Python, but if you are coming from Delphi, you may find interesting to try PyScripter available at http://mmm-experts.com/Products.aspx?ProductID=4
. For a list of availale Python IDE and editors, you cmay also check this page: http://wiki.python.org/moin/PythonEditors.HTHAndre
http://www.burgaud.comOn 24 Apr 2006 17:34:12 -0700, Just call me James <[EMAIL PROTECTED]> wrote:
Hi,Coming away from the luxury of the delphi IDE has been something of ashock.
As a consequence I've become aware that maybe I need to spend somemoney on a python IDE.As a beginner I reckon integrated debugging would be helpful.Does anyone have any advice or suggestions? So far I've glanced at
Komodo, but as a beginner I'm not in a positon to evaluate it.thanks for exprienced advice,Greg--http://mail.python.org/mailman/listinfo/python-list

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

Re: Generic string import like in strptime?

2008-01-16 Thread Andre' John
Nice. Thanks a lot.

Andre


On Wed, 16 Jan 2008, Paul Hankin wrote:

> On Jan 16, 8:34 am, Andre <[EMAIL PROTECTED]> wrote:
> > Hi there
> >
> > Is there a function like strptime, which takes a string and converts it
> > into an array depending on a format string I provide. Like:>>> a = 
> > '3456\tblub-blib.0.9'
> > >>> b = '%d\t%s-%s.%f'
> > >>> c = mysticalfunction(a,b)
> > >>> print c
> >
> > [3456,'blub','blib',0.9]
> 
> Use regular expressions: see http://docs.python.org/lib/node49.html
> 
> --
> Paul Hankin
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


psycopg2

2008-01-31 Thread Andre' John
Hi

I am trying to do this for a Postgresql database:

conn = psycopg2.connect('host=localhost')
cur = conn.cursor()
cur.execute("SELECT * FROM names WHERE name=%s", ['S'])

, which doesn't work, and neither does

cur.execute("SELECT * FROM names WHERE name='%s'", ['S'])

or

cur.execute("SELECT * FROM names WHERE name='S'")

work. It always returns:

Traceback (most recent call last):

  File "", line 1, in 

psycopg2.ProgrammingError:  array value must start with ?{½ or 
dimension information


Though, when doing

cur.execute("SELECT * FROM names")

it works.
I am totally helpless here. Does anyone have an idea?

Cheers

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

Re: psycopg2

2008-02-01 Thread Andre' John
Thanks very much, this was indeed the problem. That column was an array. 
I created it via GUI and was wondering why it did append a '[]' to the 
variable type, but didn't bother, because there was no other varchar 
available.

Cheers

Andre

PS: Weird though how few results turn up when running that through 
Google.


On Thu, 31 Jan 2008, Steve Holden wrote:

> Andre' John wrote:
> > Hi
> > 
> > I am trying to do this for a Postgresql database:
> > 
> > conn = psycopg2.connect('host=localhost')
> > cur = conn.cursor()
> > cur.execute("SELECT * FROM names WHERE name=%s", ['S'])
> > 
> > , which doesn't work, and neither does
> > 
> > cur.execute("SELECT * FROM names WHERE name='%s'", ['S'])
> > 
> > or
> > 
> > cur.execute("SELECT * FROM names WHERE name='S'")
> > 
> > work.
> 
> I'm more inclined to believe the first two than the third, but I suppose if
> you are telling the truth (House: "Patients always lie") then I am guessing
> you have defined your table's "names" columns to be an array type.
> 
> I haven't worked with those (since they don't confirm to the strict relational
> model I prefer to work with), but I am guessing you might try
> 
> 
> cur.execute("SELECT * FROM names WHERE name='%s'", (['S'], ))
> 
> as this provides the necessary tuple as the second argument to execute, and
> the on;y element of the tuple is a list of a single element.
> 
> > It always returns:
> > 
> > Traceback (most recent call last):
> > 
> >   File "", line 1, in 
> > 
> > psycopg2.ProgrammingError:  array value must start with ?{½ or dimension
> > information
> > 
> > 
> > Though, when doing
> > 
> > cur.execute("SELECT * FROM names")
> > 
> > it works.
> > I am totally helpless here. Does anyone have an idea?
> > 
> If my suggestion doesn't work, you should probably let us know more about the
> structure of your table.
> 
> regards
>  Steve
> -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python surpasses Perl in popularity?

2008-12-01 Thread Andre Majorel
On 2008-11-30, Stephane Chazelas <[EMAIL PROTECTED]> wrote:
> 2008-11-30, 06:11(+00), Tam Ha:
>> Stephane CHAZELAS wrote:
>>> There's a common confusion in this in the nature of /bin/sh.
>>> There's no standard (neither POSIX nor Unix) that specifies that
>>> /bin/sh should be any variant of the Bourne shell.
>>
>> Sure there is, POSIX.
> [...]
>
> And on this. First, POSIX has no juridiction on defining the
> Bourne shell, let alone its location as the Bourne shell is
> completely outside POSIX, it's a legacy shell and as been for
> years. Then, POSIX makes it clear that the location of its sh
> utility (again, which the Bourne shell is not) is unspecified,
> only that the lookup of "sh" via $PATH in a conformant
> environment should resolve to a conformant "sh".
>
> And if you need some examples to be convinced, see the different
> choices of those 4 different POSIX conformant Unices:
>
> Solaris (7, 8, 9 at least):
>   /bin/sh: legacy Bourne/SVr4 shell
>   /usr/xpg4/bin/sh: a POSIX compliant shell (actually ksh88)
>   Solaris choice was to keep /bin/sh as the Bourne shell for
>   backward compatibility (as changing it for a POSIX shell
>   introduces a slight chance of breaking some existing scripts
>   as there are a few corner-case areas where the POSIX shells
>   are not backward compatible with the Bourne shell), and make
>   /bin a non standard place. How to get a conformant environment
>   (typically one where /usr/xpg4/bin/sh is before /bin) is
>   described in standards(5). The default one is not, which makes
>   Solaris a pain when porting scripts.
>
> HPUX (10.10 and newer at least):
>   /usr/bin/sh (and /bin/sh if there's a symlink /bin ->
>   usr/bin): a POSIX compliant shell (based on ksh88)
>
>   /usr/old/bin/sh: the Bourne shell (though I think nowadays,
>   it's part of an optional package).
>
> Tru64:
>   /bin/sh can behave either as a Bourne shell or a POSIX shell
>   (ksh88) depending on the environment

How does it decide ? argv[0] ? isatty (STDIN_FILENO) ?

> most Linux based systems and most other Unices:
>   /bin/sh is a POSIX compliant shell (bash generally for Linux)
>   and there's no Bourne shell (either there has never been or it
>   has been removed/replaced by a POSIX shell).

Two other Unixen I know of that have a non-POSIX sh are SCO Open
Server and UnixWare. I'm not sure they even provide a
POSIX-compliant alternative like Solaris does.

On the other hand, their utilities (awk, grep, sed et al.) seem
to be POSIX-compliant, at least to the extent that I've always
managed. Unlike Solaris where I've often had to use the ones in
/usr/xpg4/bin.

Many people assume "standard" equates "portable". As far as
shell programming is concerned, the safest way to get portability
is to ignore the standard and code for the Bourne shell.

-- 
André Majorel http://www.teaser.fr/~amajorel/>
"After 15 minutes, I wanted to marry her. After a half hour, I completely
gave up the idea of snatching her purse." -- _Take the Money and Run_
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to find all completely connected sub-graphs?

2009-03-03 Thread Andre Engels
On Tue, Mar 3, 2009 at 7:35 AM, Hyunchul Kim  wrote:

> How can I find all "completely connected subgraphs" in a graph when node and
> edge data are available?
>
> "completely connected subgraph" is a group, all members of which are
> connected to each other.

Here is an algorithm I came up with in a few minutes of thinking,
complexity O(N*SN) with N being the number of nodes in the graph and
SN the sum of the nodes in each connected subgraph (there may well be
faster algorithms, but then you'd probably have to ask someone who
either already knows it, or spends significantly more time on it than
I did) - in pseudocode, but translating pseudocode into Python is an
easy thing to do:

Let N be the nodes in the graph.
A = {emptyset}  # that is, a set containing only the empty set in
the beginning
foreach node k in N:
foreach set a in A:
if k is connected to each node in a:
add k+{a} to A   # in such a way that it's not included in
the loop for the current node k

The completely connected subgraphs are the subgraphs for which the set
of nodes in the subgraph is in A.


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


Re: Inverse of dict(zip(x,y))

2009-03-04 Thread Andre Engels
On Wed, Mar 4, 2009 at 11:02 AM, lone_eagle  wrote:

> Can someone suggest a easy method to do the inverse of dict(zip(x,y))
> to get two lists x and y?
>
> So, if x and y are two lists, it is easier to make a dictionary using
> d = dict(zip(x,y)), but if I have d of the form, d = {x1:y1,
> x2:y2, ...}, what is there any trick to get lists x = [x1, x2, ...]
> and y = [y1, y2, ...]

x = d.keys()
y = [d[e] for d in x]

y = d.values() might also work, but I am not sure whether d.keys() and
d.values() are guaranteed to use the same order.


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


Re: Inverse of dict(zip(x,y))

2009-03-05 Thread Andre Engels
On Thu, Mar 5, 2009 at 6:01 PM, Tino Wildenhain  wrote:

> Still I'd like to see an application where this really matters (that
> keys() and values() match in order)

I think there are many such applications, but also that in each of
those cases it's a mis-programming of something that would be done
better and more pythonic using items()...


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


Re: Inverse of dict(zip(x,y))

2009-03-05 Thread Andre Engels
On Thu, Mar 5, 2009 at 7:07 PM, psykeedelik  wrote:

> I usually get properties that I compute, in a dictionary like property
> = [key1: val1, key2:val2, ...] and then I usually want to plot them in
> pylab, which AFAIK requires x and y as lists for the plot argument.
> Then I need to get the lists [key1, key2, ...] and [val1, val2, ...].
> And now I wonder if there a more efficient way doing what I described
> above!! ;)

If the dict = {key1: val1, key2: val2, ...}, you can do:

for key in dict:
plot(key,dictionary[key])



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


Re: Inverse of dict(zip(x,y))

2009-03-05 Thread Andre Engels
On Thu, Mar 5, 2009 at 7:46 PM, Andre Engels  wrote:

> If the dict = {key1: val1, key2: val2, ...}, you can do:
>
> for key in dict:
>    plot(key,dictionary[key])

Of course I meant:

for key in dict:
   plot(key,dict[key])



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


Re: While loop

2009-03-05 Thread Andre Engels
On Thu, Mar 5, 2009 at 6:49 PM, Fab86  wrote:
> On Mar 5, 5:23 pm, Marco Mariani  wrote:
>> Fab86 wrote:
>> > Is it possible to get the program to catch the exception, wait 10
>> > seconds, then carry of from where it was rather than starting again?
>>
>> something like this? probably works in PASCAL as well :)
>>
>> > i=0
>> > while i < len(stuff):
>> >    try:
>> >       do_with(stuff[i])
>> >    except SomeError:
>> >       sleep(10)
>> >       continue
>> >    i+=1
>>
>>
>
> using sleep and then continue just makes the search start from the
> first search term like before.. Would it be easier to understand if I
> posted sections of my code?
>
> i = 0
> k = open('blah', 'w')
> domains = ["au", "ca", "nl", "be", "...]
> srch = WebSearch(app_id=YahooKey)
>
> while i<200:
>    try:
>        for domain in domains:
>            srch.query = "test site:.%s" % domain
>            res = srch.parse_results()
>            print >> k, res.total_results_available
>            i = i + 1
>
>    except SearchError:
>
> (I currently close then reopen document here then restart i to 0)
>
> Any ideas?

What you did not tell us was the inside loop. Just put code like
Tino's inside this inner loop:


while i<200:
   for domain in domains:
   srch.query = "test site:.%s" % domain
   while true:
   try:
res = srch.parse_results()
break
   except SearchError:
time.sleep(10)
   print >> k, res.total_results_available
   i = i + 1


Or, if you want to to retry a maximum number of times:


max_retries = 50
while i<200:
   for domain in domains:
   srch.query = "test site:.%s" % domain
   retries = 0
   while true:
   try:
res = srch.parse_results()
break
   except SearchError:
if retries < max_retries:
time.sleep(10)
retries += 1
else:
raise TooManyRetriesError
   print >> k, res.total_results_available
   i = i + 1


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


Re: create boolean

2009-03-07 Thread Andre Engels
On Sat, Mar 7, 2009 at 6:03 AM, Grant Edwards  wrote:

> Putting in the second comparison in makes the code match the
> stated requirement.  Otherwise you have to start making
> assumptions about what n might be besides None or the empty
> list.

But the stated requirement already assumes that n is either None or a
list. The outcome is simply undefined when used on something that is
not None or a list. And it feels more in line with Python philosophy,
in particular with duck typing, to have 'list-like objects' (like sets
or tuples) behave like lists.

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


Re: create boolean

2009-03-09 Thread Andre Engels
On Mon, Mar 9, 2009 at 12:48 AM, Grant Edwards  wrote:

> I didn't say that he hadn't authorized that assumption.  I just
> said that the code does rely on such an assumption.  In my
> experience, assumptions like that result broken code down the
> road.

And assumptions like "when assumptions fail, it is save to go by the
letter of the requirement" don't?

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


Re: a problem in datetime.interval()

2009-03-09 Thread Andre Engels
On Mon, Mar 9, 2009 at 10:57 AM, lameck kassana  wrote:
> hi ,
> I am writing a scriot which will move old files from one directory to backup
> The files are in mode *20090307* mean *mmmdd* to new files.
> The script is below is like this
>
> import os
> import datetime
> import time
> from datetime import date
> today=date.today()
> for x in range(5,10):
>     interval=datetime.timedelta(x)
>     print interval
>     today=today-interval
>     today=today.strftime("%Y%m%d")
>     print today
>     src=r"f:\Sql_Loader\SMR\file_log_backup\smr"+today+"*"
>     dest=r" f:\Sql_Loader\SMR\file_log_backup2"
>     print src
>     print dest
> os.system(r"move " +src+" "+ dest)
>
>
>
> but the error is like that
> Traceback (most recent call last):
>   File "remove_old_files.py", line 10, in 
>     today=today-interval
> TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
>
> It seems datetime.timedelta()does not respond with my loop
> Any help??

The first time you go through the loop, all goes well, but during that
loop there is the command

today=today.strftime("%Y%m%d")

After this, today is not a date any more, but a string - and you
cannot substract a timedelta from a string.


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


Re: How to add months to a date (datetime object)?

2009-03-15 Thread Andre Engels
On Sun, Mar 15, 2009 at 7:00 PM,   wrote:
> Roy Smith  wrote:
>> In article <49bd3ab8$0$510$bed64...@news.gradwell.net>, tinn...@isbd.co.uk
>> wrote:
>>
>> > I have a date in the form of a datetime object and I want to add (for
>> > example) three months to it.  At the moment I can't see any very
>> > obvious way of doing this.  I need something like:-
>> >
>> >     myDate = datetime.date.today()
>> >     inc = datetime.timedelta(months=3)
>> >     myDate += inc
>> >
>> > but, of course, timedelta doesn't know about months. I had a look at
>> > the calendar object but that didn't seem to help much.
>>
>> Well, before you can "add three months" to something, you need to explain
>> what that means.
>>
>> What is Nov 29th plus 3 months?
>>
>> What is Jan 31st plus 3 months?
>>
>> Months are different lengths.  Asking to "add 3 months" is kind of like
>> asking, "If I'm somewhere in the continental US (east of the Mississippi
>> River) and move three states to the west, how many miles have I moved?"
>
> No, it's perfectly possible applying simple logic.  My reminder
> program manages it perfectly well.  I have, for example, two sets of
> three monthly reminders.
>
>    One starts on Jan 19th and repeats three monthly, that means Jan
>    19th, April 19th, July 19th and October 19th.  Very simple.
>
>    The other is a little more difficult, it starts on December 31st
>    and repeats three monthly.  So that one is on December 31st, March
>    31st, June 30th and September 30th.
>
> The calendar program manages it perfectly well using what seems to me
> fairly obvious logic, what I want is to be able to do the same in
> Python.
>
> I.e. in simple terms I want the "same day N months hence" and, if it
> doesn't exist then the nearest possible.

Well, that's one way of defining it, but it does have some
consequences you have to watch out for. In particular, it means that
the following equalities do not necessarily hold:

Date + 2 months = Date + 1 month + 1 month
Date = Date + 1 month - 1 month

not to mention anything where you use days or weeks in combination
with months...

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


Re: array next pointer

2009-03-17 Thread Andre Engels
On Tue, Mar 17, 2009 at 12:12 PM, Anjanesh Lekshminarayanan
 wrote:
 a = ['cat','dog','elephant']
 a.next()
> Traceback (most recent call last):
>  File "", line 1, in 
> AttributeError: 'list' object has no attribute 'next'

> Is there something that imtates PHP's next() ? (http://php.net/next)

>>> b = a.__iter__()
>>> b.next()
1
>>> b.next()
2

However, in many cases the more Pythonic way of working will be to use
a for-loop (which is like a foreach-loop in PHP and other languages).


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


Re: array next pointer

2009-03-17 Thread Andre Engels
On Tue, Mar 17, 2009 at 12:24 PM, Andre Engels  wrote:
> On Tue, Mar 17, 2009 at 12:12 PM, Anjanesh Lekshminarayanan
>  wrote:
>>>>> a = ['cat','dog','elephant']
>>>>> a.next()
>> Traceback (most recent call last):
>>  File "", line 1, in 
>> AttributeError: 'list' object has no attribute 'next'
>>>>>
>> Is there something that imtates PHP's next() ? (http://php.net/next)
>
>>>> b = a.__iter__()
>>>> b.next()
> 1
>>>> b.next()
> 2

That should of course be:

>>> b = a.__iter__()
>>> b.next()
'cat'
>>> b.next()
'dog'

I had copied a bit too literal from my own attempt...

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


Re: Python to Perl transalators

2009-03-18 Thread Andre Engels
On Wed, Mar 18, 2009 at 6:27 AM,   wrote:
>
> -Original Message-
> From: ch...@rebertia.com [mailto:ch...@rebertia.com] On Behalf Of Chris Rebert
> Sent: Wednesday, March 18, 2009 10:53 AM
> To: Raju, Abhinayaraj
> Cc: python-list@python.org
> Subject: Re: Python to Perl transalators
>
> 2009/3/17  :
>> Could anyone suggest whether there is any Python to Perl code convertors?
>> I found one on the net viz. Perthon. But it wasn’t really helping out.
>
> 
> Why on earth would you want to? That'd be like translating Shakespeare
> into a bad rap song!
> 
>
> Cheers,
> Chris
>
> --
> I have a blog:
> http://blog.rebertia.com
>
> :-)
>
> I am just a beginner learning both the languages. Wondered if I can have some 
> comparative understanding of both.

I think automatic translation would be a very bad way of getting
understanding of both. Translating from another language to Python
usually leads to very un-Pythonic code - syntactically correct and
working Python, but not 'real' Python. I assume that translating from
Python to Perl will lead to something similarly un-Perlish.



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


Re: Crunchy [Was: Preparing teaching materials]

2009-03-21 Thread Andre Roberge
On Sat, Mar 21, 2009 at 5:06 PM, andrew cooke  wrote:

> André wrote:
> > If I may suggest a very different alternative than the ones already
> > suggested: use Crunchy.  (http://code.google.com/p/crunchy)
> >
> > You can have you handouts (html or reStructuredText documents) live on
> > the web with all your code samples executable from within Firefox.
> >
> > If you don't want to install Crunchy, but want to see it in action,
> > you can check these older videos:
> > http://showmedo.com/videos/video?name=143;fromSeriesID=143
> > http://showmedo.com/videos/video?name=1430020;fromSeriesID=143
>
> this is very cool, but i can't find (quickly) an explanation of the
> implementation.  since there only seem to be videos and not an actual demo
> page, i assume you need to install it locally?  is there a technical
> introduction?
>


Yes, you have to install it locally. The best method is to get it from the
svn trunk, and run it from the base directory.  You first need to create an
account (python account_manager.py), and you are ready to start it (python
crunchy.py).  Crunchy comes with a rather complete tutorial intended both
for end user AND with some more advanced sections for tutorial writers.

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


Re: What way is the best to check an empty list?

2009-03-25 Thread Andre Engels
On Wed, Mar 25, 2009 at 3:38 PM, srinivasan srinivas
 wrote:
>
> For ex: to check list 'A' is empty or not..
> if A == []:
> if A.count == 0:
> if len(A) == 0:
> if not A:

I would go for the last one, because it has the highest likelihood of
doing what is intended when fed with something that is 'list-like'
rather than a list. The second one is incorrect, by the way. A.count
is something completely different.

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


Re: What way is the best to check an empty list?

2009-03-25 Thread Andre Engels
On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke  wrote:
>
> i will go against the grain slightly and say that "len" is probably the
> best compromise in most situations (although i admit i don't know what
> count is) because i think it will work when you expect it to and break
> when you have a bug in your program.
>
> using a simple boolean is more robust (and what i typically do in my own
> code because i am often too lazy to think carefully), but if it is given
> something that is not "list-like" you won't get an error until later in
> your code (and typically the sooner an error is found, the better).
>
> but i may be wrong - are there any containers (apart from pathological
> hand-crafted examples) that would not define __len__()?

When writing my answer, I thought of generators, but I now find that
those will have boolean value 'true' whether or not they have
something to generate, so they will go wrong under either method. The
same holds for iterators. So for now I can't find any good example.


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


Re: absolute newbie: divide a list into sublists (nested lists?) of fixed length

2009-04-11 Thread Andre Engels
On Sun, Apr 12, 2009 at 12:05 AM,   wrote:

> Thanks very much - works fine! Now for a follow-up question:)
>
> Actually my original list called "mylist" contains 81217 elements - I
> shape those into
>
 len(mylist)
> 81217
 s = N.array(mylist)
 s.shape = (241,337)
>
> which works because the "total size of new array must be
> unchanged" (241x337=81217)
>
> Now this "matrix" actually is a 2D colorcoded map - I want to plot
> this using the imshow splot routine in mayavi2..
>
> However, there might be a problem: I believe that sometimes my
> original array will not exactly contain 81217 elements, but maybe only
> 81216 or so. Nevertheless, I know that time x times y - structure will
> always be the same (that is, 241 columns). What is of interest to me
> is the first 241 x 241 part of the matrix anyway. Is there an easy way
> to reshape my original array into a symmetric 241x241 matrix?

Provided that the array always has at least 58081 elements:

[mylist[i:i+241] for i in range(0,58081,241)]




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


Re: [False,True] and [True,True] --> [True, True]?????

2009-04-20 Thread Andre Engels
On Mon, Apr 20, 2009 at 9:03 AM, bdb112  wrote:
> Is there any obvious reason why
> [False,True] and [True,True]
> gives [True, True]

Well, whether the reason is obvious, I do not know, but the way and
seems to be implemented is:

X and Y =
* X if the boolean value of X is false
* Y if the boolean value of X is true

In this case, bool([False,True]) = true, so the second element is taken.


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


Re:

2009-04-21 Thread Andre Engels
On Tue, Apr 21, 2009 at 3:00 PM, karlos barlos  wrote:
> hello to everybody...
>
> having problem withe this code :
>
> dom = raw_input("The Domain name..:")
>   ad_user.Put('userPrincipalName',user['login']+'@(['dom'])
>
> but it wont change whay ?

Well, you don't tell what ad_user is, and its Put method, but what I
do see is that there are 7 single quotes in this line - given that
each single quote seems to be starting or ending a string, there
should be an even number of them.



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


Re: sorted() erraticly fails to sort string numbers

2009-04-28 Thread Andre Engels
On Tue, Apr 28, 2009 at 9:47 AM, uuid  wrote:
> I would be very interested in a logical explanation why this happens on
> python 2.5.1:
>
> In order to sort an etree by the .text value of one child, I adapted this
> snippet from effbot.org:
>
>> import xml.etree.ElementTree as ET
>>
>> tree = ET.parse("data.xml")
>>
>> def getkey(elem):
>>    return elem.findtext("number")
>>
>> container = tree.find("entries")
>>
>> container[:] = sorted(container, key=getkey)
>>
>> tree.write("new-data.xml")
>
> While working with a moderately sized xml file (2500 entries to sort by), I
> found that a few elements were not in order. It seems that numbers with
> seven digits were sorted correctly, while those with six digits were just
> added at the end.
>
> I fixed the problem by converting the numbers to int in the callback:
>
>> def getkey(elem):
>>    return int(elem.findtext("number"))
>
> So to my naive mind, it seems as if there was some error with the sorted()
> function. Would anyone be as kind as to explain why it could be happening?
> Thanks in advance!

When sorting strings, including strings that represent numbers,
sorting is done alphabetically. In this alphabetical order the numbers
are all ordered the normal way, so two numbers with the same number of
digits will be sorted the same way, but any number starting with "1"
will come before any number starting with "2", whether they denote
units, tens, hundreds or millions. Thus:

"1" < "15999" < "16" < "2"




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


Re: Why bool( object )?

2009-04-28 Thread Andre Engels
On Tue, Apr 28, 2009 at 2:22 PM, Colin J. Williams  wrote:
> Lie Ryan wrote:
>>
>> Aaron Brady wrote:
>>>
>>> What is the rationale for considering all instances true of a user-
>>> defined type?
>>
>> User-defined objects (or type) can override .__len__() [usually container
>> types] or .__nonzero__() to make bool() returns False.
>>
>>> Is it strictly a practical stipulation, or is there
>>> something conceptually true about objects?
>>
>> Objects are true unless they define themself as false. The practical
>> implication is we can do this:
>>
>> def foo(args = None):
>>    if args:
>>        ...
>>
>> In python all objects are true except: None, False, 0/0L/0.0/0j, empty
>> sequence or container, and on objects that defines .__len__() or
>> ..__nonzero__() that returns 0 or False.
>>
>>> '''
>>> object.__bool__(self)
>>> If a class defines neither __len__() nor __bool__(), all its instances
>>> are considered true.
>>> '''
>>>
>>> This makes it so all objects except False, None, 0, and empty
>>> containers are true by default.  I am not convinced that 'if >> generic object>' should have any meaning; it should probably throw an
>>> exception.  Is it part of Python's look and feel or its mentality?  Is
>>> it part of the Zen?  Certainly other ideal types can't be cast from
>>> generic objects, so why booleans?  Is it an ineffable component of the
>>> author's vision for the language?  I think that giving arbitrary
>>> syntactic constructs meaning is just space-filler.  It's worse than
>>> syntactic sugar, it's semantic sugar.  Why not assign meanings willy-
>>> nilly to other random juxtapositions of tokens?
>>
>> It's part of the design decision. In almost all cases (in any language), a
>> so-called "Design Decision" is rather random and prone to subjective
>> judgment, just as the decision to make bool(int) returns False only on 0,
>> -1, or for all negative values; whether to make bool(100) and exception or
>> True; or round() rounds down or up or even-odd; or the use of brackets vs.
>> indentation; or whether to treat empty list as True or False.
>
> I'm puzzled by the last sentence:
>
> *** Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] on win32. ***

 bool(0)
>
> False

 bool(-1)
>
> True

 bool(-100)
>
> True

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

bool has been defined thus in Python:

False are:
* False
* None
* empty containers, lists etc.
* The number zero

Everything else is true.

-100 is not equal to zero, so its boolean value is True.



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


Re: Generator oddity

2009-05-01 Thread Andre Engels
On Fri, May 1, 2009 at 4:25 PM, Dave Angel  wrote:

> The problem is in it2, which is initialized only once.  Thus the second time
> you're going through the c2 loop, it doesn't have any more values.
>
> If you need the indirection provided by those it1 and it2, you need to
> postpone the function evaluation, at least for it2.
>
> I'd do
> it1 = gen
> it2 = gen
>
> list(c1 + c2 for c1 in it1() for c2 in it2())
> or more simply:
> [c1 + c2 for c1 in it1() for c2 in it2()]

Another possibility would be to use the outcome of looping through the
generator rather than the generator itself:

it1 = list(gen())
it2 = list(gen())
[c1 + c2 for c1 in it1() for c2 in it2()]


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


  1   2   3   >