Re: explode()

2009-07-14 Thread alex23
Fred Atkinson  wrote:
>         I wish the Python site was as well written as the PHP site. On
> the PHP site, I can look up a command and they show not only the docs
> on that command but a list of all other commands associated with it.  

Hey Fred,

My problem is the complete opposite, I wish I could as easily
interrogate objects in PHP about their behaviour as I can Python :)

In case you're not familiar with this, you can see what methods are
attached to an object using the intepreter via dir() and see the
associated docstring for them via help(). Try looking at 'dir(str)'
for a list of methods that strings recognise, then 'help(str.join)' to
see the help on join.

This is such a handy ability to have that I miss this casual
introspection in everything else in which I'm required to develop.

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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Ben Finney
Steven D'Aprano  writes:

> Isn't that risky though? Won't that potentially change the exception-
> handling behaviour of functions and classes he imports from other
> modules?

No, any existing ‘except’ clause will be unaffected by re-binding
‘sys.excepthook’. As I understand the documentation, that function is
called only if the exception is uncaught by anything else.

>>> 1 / 0
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero

>>> import sys
>>> def reverse_handler(exc_type, exc_instance, exc_traceback):
... print exc_type.__name__[::-1], str(exc_instance)[::-1]
...
>>> sys.excepthook = reverse_handler

>>> try:
... 1 / 0
... except ZeroDivisionError:
... print "You created a black hole."
... 
You created a black hole.
>>> 1 / 0
rorrEnoisiviDoreZ orez yb oludom ro noisivid regetni

In other words, it is the function that (unless re-bound) prints the
traceback we're all familiar with when an exception is uncaught. It is
exposed via the name ‘sys.excepthook’ precisely for the purpose of
changing the default handler for uncaught exceptions

-- 
 \ “I have yet to see any problem, however complicated, which, |
  `\  when you looked at it in the right way, did not become still |
_o__)more complicated.” —Paul Anderson |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copy a file

2009-07-14 Thread Krishnakant
On Tue, 2009-07-14 at 12:27 +0530, [email protected] wrote:
> Dear all,
> 
> Can anyone tell me that suppose i want to copy few lines from one text
> file to another then how can i do that.Looking forward for soon reply.
> 

very simple.  open one file and open the source file.
seek till to the point where u want to start copying and loop till the
end with readline function.
then write it to the destination file.

To find the starting point, keep looping through the content and come
out of that loop when you find a match to the word you are looking for.
happy hacking.
Krishnakant.

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


Remote audio recording in a multiuser environment

2009-07-14 Thread nelson -
Hi all!
   I'm developing an application that will be used in a school. It
will allow client connected over ssh to liste to a multimedia file on
the server. The server componente will record the audio taken from a
specified client microphone, or it would pair two client, allowing
them to communicate each other registering the conversation.

I think to use pygst to record the microphone, but i can' figure out
how to register remote sound and how to create the channel between two
client. Do you think i have to use twisted (i don't know this
framework at all), or there is a simple solution?

I will surely use wxpython for the UI on the client and on the server.

Thank for any advice,
  nelson

-- 
Consulenze Linux e Windows

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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Carl Banks
On Jul 13, 8:25 pm, Steven D'Aprano
 wrote:
> On Mon, 13 Jul 2009 17:49:23 -0700, Carl Banks wrote:
> > On Jul 13, 12:31 pm, Piet van Oostrum  wrote:
> >> > seldan24  (s) wrote:
> >> >s> Hello,
> >> >s> I'm fairly new at Python so hopefully this question won't be too s>
> >> >awful.  I am writing some code that will FTP to a host, and want to s>
> >> >catch any exception that may occur, take that and print it out s>
> >> >(eventually put it into a log file and perform some alerting action).
> >> >s> I've figured out two different ways to do this, and am wondering
> >> >which s> is the best (i.e. cleanest, 'right' way to proceed).  I'm
> >> >also trying s> to understand exactly what occurs for each one. s> The
> >> >first example:
> >> >s> from ftplib import FTP
> >> >s> try:
> >> >s>     ftp = FTP(ftp_host)
> >> >s>     ftp.login(ftp_user, ftp_pass) s> except Exception, err:
> >> >s>     print err
>
> >> I think you should restrict yourself to those exceptions that are
> >> related to ftp. Do you want to catch an exception like a misspelling in
> >> one of the variables?
>
> > He quite reasonably could want that, such as if the program is designed
> > to be run from a cron job, or in some other non-interactive way.
>
> Why is it okay for non-interactive programs to silently have incorrect
> behaviour?
>
> What's the point of a cron job that doesn't do what it is supposed to,
> because it has a bug which is silently swallowed?

Seriously, do you *ever* take more than 2 seconds to consider whether
you might be missing something obvious before following up with these
indignant knee-jerk responses?

I never said a thing about swallowing errors.  I was talking about
catching exceptions, whence you might do all kinds of things besides
swallowing (like logging).  I was pointing out there are reasons why
you might want to catch variable misspelling errors when you're
running non-interactively (like for instance, to log the error
somewhere).

Or would you rather let all unexpected exceptions print to standard
error, which is often a black hole in non-interactive sitations?


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


RE: list of all possible values

2009-07-14 Thread Andreas Tawn
> David Gibb:
> > For example: if my values are ['a', 'b', 'c'], then all possible
lists
> > of length 2 would be: aa, ab, ac, ba, bb, bc, ca, cb, cc.
> 
> >>> from itertools import product
> >>> list(product("abc", repeat=2))
> [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b',
> 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
> 
> Bye,
> bearophile

Certainly possible with list comprehensions.

>>> a = "abc"
>>> [(x, y) for x in a for y in a]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'),
('c', 'a'), ('c', 'b'), ('c', 'c')]

But I like bearophile's version better.

Cheers,

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


How to unbuffer Python's output

2009-07-14 Thread Lily Gao
Hi, All
I am calling a python program in perl and use redirection,
Like :
`python x.py > 1.log 2>&1`
When x.py crash, I get nothing from 1.log, and if I don’t use redirection, I 
can get useful log from the screen.
How can I do to make x.py ‘s  output un-buffered when redirection log to files 
,just exactly same with print to the screen?

When I use perl’s $|=1 to unbuffer output, it take no effect. So I think it may 
be caused by python.
Thanks!

Thanks,
Lily Gao(高雁)
ACRD PSEB Catapult TD
+86-21-38664379

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


Re: MySQLdb + SSH Tunnel

2009-07-14 Thread R C
Got it working.  Thanks for your help

1) login to B
2) setup a tunnel in the shell   machine-B> ssh -L
B_ip_address:B_port:C_ip_address:C_port u...@c_ip_address

   for example:
 machine-B has ip 1.1.1.1
 machine-C has ip 2.2.2.2

   then I would type:
   machine-B> ssh -L 1.1.1.1:3307:2.2.2.2:3306 [email protected]

   now the code that is running on machine-A would use MySQLdb in the
following way

   import MySQLdb
   connection = MySQLdb.connect
(user='myname',passwd='mypass',db='mydb',host='1.1.1.1',port=3307)

   NOTE: the port is an integer, NOT a string



On Jul 12, 9:18 pm, Riley Crane  wrote:
> OVERVIEW:
> I am running a script on one machine that connects to a MySQL database
> on another machine that is outside of our university's domain.
> According to the administrator, network policies do not allow the
> compute nodes to access machines outside of our university's domain.
>
> COMPUTERS:
> A = compute node within university (I do not have shell access)
> B = 2nd machine within university that does not block outside
> connections (I have root access)
> C = machine outside of university (I have root access)
> mysqldb on A cannot connect to C but.
> mysqldb on A can connect to B
>
> WHAT I WOULD LIKE TO DO:
> Is it possible to set something up where A talks to a port on B, and
> that port is actually nothing more than 3306 on C?  Can I do this with
> an SSH tunnel?
>
> Can anyone please give precise instructions?

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


Re: MySQLdb + SSH Tunnel

2009-07-14 Thread Riley Crane
Got it working.  Thanks for your help!

1) login to B
2) setup a tunnel in the shell   machine-B> ssh -L
B_ip_address:B_port:C_ip_address:C_port u...@c_ip_address

   for example:
 machine-B has ip 1.1.1.1
 machine-C has ip 2.2.2.2

   then I would type:
   machine-B> ssh -L 1.1.1.1:3307:2.2.2.2:3306 [email protected]

   now the code that is running on machine-A would use MySQLdb in the
following way

   import MySQLdb
   connection = MySQLdb.connect
(user='myname',passwd='mypass',db='mydb',host='1.1.1.1',port=3307)

   NOTE: the port is an integer, NOT a string


On Jul 12, 9:18 pm, Riley Crane  wrote:
> OVERVIEW:
> I am running a script on one machine that connects to a MySQL database
> on another machine that is outside of our university's domain.
> According to the administrator, network policies do not allow the
> compute nodes to access machines outside of our university's domain.
>
> COMPUTERS:
> A = compute node within university (I do not have shell access)
> B = 2nd machine within university that does not block outside
> connections (I have root access)
> C = machine outside of university (I have root access)
> mysqldb on A cannot connect to C but.
> mysqldb on A can connect to B
>
> WHAT I WOULD LIKE TO DO:
> Is it possible to set something up where A talks to a port on B, and
> that port is actually nothing more than 3306 on C?  Can I do this with
> an SSH tunnel?
>
> Can anyone please give precise instructions?

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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Steven D'Aprano
On Tue, 14 Jul 2009 01:30:48 -0700, Carl Banks wrote:

> Seriously, do you *ever* take more than 2 seconds to consider whether
> you might be missing something obvious before following up with these
> indignant knee-jerk responses?

Obviously not.


[...]
> Or would you rather let all unexpected exceptions print to standard
> error, which is often a black hole in non-interactive sitations?

Fair point. Of course you're right.



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


Re: Passing python list from C to python

2009-07-14 Thread hartley
> > I'm very new at wrapping Python/C, and I have run into some problems.
>
> > I have one python module that provides me with a list (provideBuffer
> > in provideBuff.py):
>
> >  Py_Initialize();
> >         pName = PyString_FromString("provideBuff");
> >         pModule = PyImport_Import(pName);
>
> >         pFunc = PyObject_GetAttrString(pModule,"provideBuffer");
>
> >         pValue = PyObject_CallObject(pFunc,NULL);
>
> > pValue is now a PyList - i've even verified this with:
>
> > int a = PyList_Check(pValue);
> >         printf("%d\n", a);
>
> > However, I want to send this PyList to another python module,
>
> Please explain "send" ... do you mean the C equivalent of the Python
> statement C_embedding.buff = the_pylist ?
>
> BTW C-embedding would trigger a syntax error in Python source; best to
> avoid ...


I'm sorry I'm not using the proper terms when trying to describe this
- i've never really learnt those terms, I guess i should do that one
day.


Imagine that the python function C-embedding.buff looks like this:

def buff(a):
if isinstance(a,list):
print "success"

I want to send, pass, call, whatever a list argument from the C code
onto this function. As simple as this - how can you call a function in
python from C, and providing a python list as an argument?

As I wrote earlier - I already have a PyList, called pValue. But I
have not been able to use this as an argument for C-embedding.buff
using the code I described last time.


> > but I
> > don't know how to do this. Initially I though I could just do like
> > above, only swapping NULL with pValue, but that is not working.
>
> > pName2 = PyString_FromString("C-embedding");
> > pModule2 = PyImport_Import(pName2);
> > pFunc2 = PyObject_GetAttrString(pModule2,"buff");
>
> Get?? Do you want Set? Is buff a Python function? Or is it the
> destination of the "sending"? Any good reason for not checking the
> return value for an error? [Rhetorical question; answer == "No"]
>
> > pValue2 = PyObject_CallObject(pFunc2,pValue);
>
> CallObject?? You used this before because you had a function and
> wanted to call it because it returned you a value  now you want to
> do one of (in Python terms)
>
> value = amodule.anattr
> value = getattr(amodule, "anattr")
>
> or
>
> amodule.anattr = value
> setattr(amodule, "anattr", value)
>
> > pValue2 is now False!
>
> False?? Do you mean the C NULL?
>
> > So i guess i cannot pass pValue as an argument
> > to PyObject_CallObject when i want to pass an python list as an
> > argument. But how must a go about to make this work?
>
> It's mainly just a matter of (1) knowing what you want to do (2)
> picking the API that does what you want (3) checking the returned
> value for error after every call.
>
> HTH,
> John

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


Re: How to unbuffer Python's output

2009-07-14 Thread Chris Rebert
2009/7/13 Lily Gao :
> Hi, All
>
> I am calling a python program in perl and use redirection,
>
> Like :
>
> `python x.py > 1.log 2>&1`
>
> When x.py crash, I get nothing from 1.log, and if I don’t use redirection, I
> can get useful log from the screen.
>
> How can I do to make x.py ‘s  output un-buffered when redirection log to
> files ,just exactly same with print to the screen?

Use the -u flag to python:
−uForce stdin, stdout and stderr to be totally unbuffered.

python -u x.py > 1.log 2>&1

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


'unable to execute cc: No such file or directory' with distutils on Solaris

2009-07-14 Thread Tim Edwards
Hi,

I'm trying to compile http://sourceforge.net/projects/astlib/ 0.17.1 on
a Solaris 10 SPARC system. This python module uses distutils.ccompiler.
The problem seems to be that although I have gcc installed in
/usr/sfw/bin/gcc it keeps trying to execute the command 'cc', which
doesn't work:

cc -c actread.c -o actread.o
unable to execute cc: No such file or directory
error: command 'cc' failed with exit status 1


I've tried modifying the setup.py file to specify "cc.compiler =
'/usr/sfw/bin/gcc'" and setting the $CC envrionment var.
But I get the same error everytime. Can someone suggest how to change
where distutils is looking for the compiler?

Thanks

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


copy a few lines

2009-07-14 Thread amrita


Dear all,

I want to know if i want to copy one paragraph from one text file to
another then what command i have to use in python.Looking forwaard for
soon reply.


Thanks,
Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

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


Re: copy a few lines

2009-07-14 Thread Chris Rebert
On Tue, Jul 14, 2009 at 2:43 AM,  wrote:
>
>
> Dear all,
>
> I want to know if i want to copy one paragraph from one text file to
> another then what command i have to use in python.Looking forwaard for
> soon reply.

Please don't double-post. It wastes everyone's time, especially when
(a) your previous post was less than 3 hours ago, and
(b) your previous post got a response.

If you're refining your question, it's best to just reply to your own
prior post.

Also, you're going to need to define what precisely qualifies as a
"paragraph" for your purposes.

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


Re: renice

2009-07-14 Thread JonPeirce


Note that with os.nice you can only *decrease* priority. For increasing
priority you need to run;
os.system("sudo renice -n %s %s" % (new_nice, os.getpid()))
or simply set the nice level when you run python in the first place (you do
also need sudo for this):
sudo nice -n -15 python myScript.py

Jon
-- 
View this message in context: 
http://www.nabble.com/renice-tp13422771p24477000.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Efficient binary search tree stored in a flat array?

2009-07-14 Thread Florian Brucker
Douglas Alan wrote:
> Thank you. My question wasn't intended to be Python specific, though.
> I am just curious for purely academic reasons about whether there is
> such an algorithm. All the sources I've skimmed only seem to the
> answer the question via omission. Which is kind of strange, since it
> seems to me like an obvious question to ask.

IIRC comp.programming would be the place to ask such questions.


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


Re: Passing python list from C to python

2009-07-14 Thread hartley
On Jul 13, 6:35 pm, John Machin  wrote:
> On Jul 14, 1:47 am, hartley  wrote:
>
>
>
> > I'm very new at wrapping Python/C, and I have run into some problems.
>
> > I have one python module that provides me with a list (provideBuffer
> > in provideBuff.py):
>
> >  Py_Initialize();
> >         pName = PyString_FromString("provideBuff");
> >         pModule = PyImport_Import(pName);
>
> >         pFunc = PyObject_GetAttrString(pModule,"provideBuffer");
>
> >         pValue = PyObject_CallObject(pFunc,NULL);
>
> > pValue is now a PyList - i've even verified this with:
>
> > int a = PyList_Check(pValue);
> >         printf("%d\n", a);
>
> > However, I want to send this PyList to another python module,
>
> Please explain "send" ... do you mean the C equivalent of the Python
> statement C_embedding.buff = the_pylist ?
>
> BTW C-embedding would trigger a syntax error in Python source; best to
> avoid ...
>
> > but I
> > don't know how to do this. Initially I though I could just do like
> > above, only swapping NULL with pValue, but that is not working.
>
> > pName2 = PyString_FromString("C-embedding");
> > pModule2 = PyImport_Import(pName2);
> > pFunc2 = PyObject_GetAttrString(pModule2,"buff");
>
> Get?? Do you want Set? Is buff a Python function? Or is it the
> destination of the "sending"? Any good reason for not checking the
> return value for an error? [Rhetorical question; answer == "No"]
>
> > pValue2 = PyObject_CallObject(pFunc2,pValue);
>
> CallObject?? You used this before because you had a function and
> wanted to call it because it returned you a value  now you want to
> do one of (in Python terms)
>
> value = amodule.anattr
> value = getattr(amodule, "anattr")
>
> or
>
> amodule.anattr = value
> setattr(amodule, "anattr", value)
>
> > pValue2 is now False!
>
> False?? Do you mean the C NULL?
>
> > So i guess i cannot pass pValue as an argument
> > to PyObject_CallObject when i want to pass an python list as an
> > argument. But how must a go about to make this work?
>
> It's mainly just a matter of (1) knowing what you want to do (2)
> picking the API that does what you want (3) checking the returned
> value for error after every call.
>
> HTH,
> John

I tried to keep this simple, but I realise that since I'm not using
the terminology correctly, it may be hard understand what I mean.

I'll do something even simpler:

Say you have the function:

C-embedding.buff

def buff(s):
if isinstance(s,list):
   return s

how can i call (use,invoke,?? - sorry, about the terminology again)
this function from C so that I call this function with an argument
that is (accepted as) a python list?

foo.bar

def bar():


pName = PyString_FromString("foo");
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule,"bar");
pValue = PyObject_CallObject(pFunc,NULL);
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DBI module deprecated at Python 2.5--what to use in its place?

2009-07-14 Thread dana
On Jul 10, 12:15 pm, "M.-A. Lemburg"  wrote:
> If you're looking for a stable and maintained ODBC for Python,
> have a look at our mxODBC extension or mxODBC Connect package:
> http://www.egenix.com/products/python/mxODBC/http://www.egenix.com/products/python/mxODBCConnect/

I'm looking for a free module. Is yours a commercial product?

Thanks.

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


Re: Tkinter / Entry widget problem

2009-07-14 Thread Peter Otten
Andras Szabo wrote:

> Hello. I searched the archives but couldn't find a solution to a
> problem related to the Entry widget in Tkinter.
> 
> When creating a pop-up window in an app, which contains an Entry
> widget, I want this widget to contain some default string, to have all
> this default string selected (as if the user had manually selected
> everything), and to have the focus transferred to this widget.
> 
> (The idea is then that if the window pops up, the user won't have to
> click or press Tab any more before being able to type what is needed
> in the textbox, overwriting what is written there already.)
> 
> I thought this might be the way to go:
> 
> entrybox=Entry(toplevel_parent_window)
> entrybox.insert(0,"Some default string")
> entrybox.select_range(0,END)
> entrybox.focus_set()
> entrybox.pack()
> 
> But it doesn't seem to work - the focus is not transferred to the
> Entry widget, and the text does not appear to be selected (even though
> after this entrybox.selection_present() returns True).
> 
> What am I doing wrong?

Nothing, I would think. Can you post a minimal runnable example?

Peter

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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Lawrence D'Oliveiro
In message <93f6a517-63d8-4c80-
[email protected]>, Carl Banks wrote:

> Or would you rather let all unexpected exceptions print to standard
> error, which is often a black hole in non-interactive sitations?

Since when?

Cron, for example, collects standard error and mails it to you.

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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Lawrence D'Oliveiro
In message , seldan24 wrote:

> For this particular script, all exceptions are fatal
> and I would want them to be.  I just wanted a way to catch them and
> log them prior to program termination.

You don't need to. They will be written to standard error anyway.

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


Re: The meaning of "=" (Was: tough-to-explain Python)

2009-07-14 Thread Lawrence D'Oliveiro
In message , Steven 
D'Aprano wrote:

> Are we supposed to interpret that post as Dumb Insolence or just Dumb?

"Insolence" indeed ... another wanker to plonk, I think.

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


Re: Efficient binary search tree stored in a flat array?

2009-07-14 Thread Piet van Oostrum
> Douglas Alan  (DA) wrote:

>DA> On Jul 13, 3:57 pm, [email protected] (Aahz) wrote:
>>> Still, unless your list is large (more than thousands of elements),
>>> that's the way you should go.  See the bisect module.  Thing is, the
>>> speed difference between C and Python means the constant for insertion
>>> and deletion is very very small relative to bytecode speed.  Keep in
>>> mind that Python's object/binding model means that you're shuffling
>>> pointers in the list rather than items.

>DA> Thank you. My question wasn't intended to be Python specific, though.
>DA> I am just curious for purely academic reasons about whether there is
>DA> such an algorithm. All the sources I've skimmed only seem to the
>DA> answer the question via omission. Which is kind of strange, since it
>DA> seems to me like an obvious question to ask.

Of course you can take any BST algorithm and replace pointers by indices
in the array and allocate new elements in the array. But then you need
array elements to contain the indices for the children explicitely.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing python list from C to python

2009-07-14 Thread John Machin
On Jul 14, 7:22 pm, hartley  wrote:
> > > I'm very new at wrapping Python/C, and I have run into some problems.
[snip]

> > >         pValue = PyObject_CallObject(pFunc,NULL);
>
> > > pValue is now a PyList - i've even verified this with:
>
> > > int a = PyList_Check(pValue);
> > >         printf("%d\n", a);
>
> > > However, I want to send this PyList to another python module,
>
> > Please explain "send" ... do you mean the C equivalent of the Python
> > statement C_embedding.buff = the_pylist ?
>
> > BTW C-embedding would trigger a syntax error in Python source; best to
> > avoid ...
>
> I'm sorry I'm not using the proper terms when trying to describe this
> - i've never really learnt those terms, I guess i should do that one
> day.

Today would be a good day to start :-)

>
> Imagine that the python function C-embedding.buff looks like this:
>
> def buff(a):
>     if isinstance(a,list):
>         print "success"
>
> I want to send, pass, call, whatever a list argument from the C code
> onto this function. As simple as this - how can you call a function in
> python from C, and providing a python list as an argument?
>
> As I wrote earlier - I already have a PyList, called pValue. But I
> have not been able to use this as an argument for C-embedding.buff
> using the code I described last time.
>
> > > but I
> > > don't know how to do this. Initially I though I could just do like
> > > above, only swapping NULL with pValue, but that is not working.
>
> > > pName2 = PyString_FromString("C-embedding");
> > > pModule2 = PyImport_Import(pName2);
> > > pFunc2 = PyObject_GetAttrString(pModule2,"buff");

> >  Any good reason for not checking the
> > return value for an error? [Rhetorical question; answer == "No"]
>
> > > pValue2 = PyObject_CallObject(pFunc2,pValue);

Your problem is here, in the second arg of PyObject_CallObject. It
should be either NULL if no args are being supplied, or a tuple
containing the args if 1 or more args are being supplied. pValue is
the arg itself; you need to wrap it in a tuple.

See http://docs.python.org/c-api/object.html#PyObject_CallObject

Actually you might like to use this instead (no tuple hassles):

http://docs.python.org/c-api/object.html#PyObject_CallFunctionObjArgs

What are you using as a source of information? Have you read this:

http://docs.python.org/extending/embedding.html#pure-embedding ?

It contains a very thorough example of calling a Python function from
C, with all the reference-counting and error-checking stuff and it's
quite runnable -- I've just now compiled it and run it (1) as-is (2)
changed to pass a list instead of multiple ints (3) changed again to
emulate you trying to pass the list directly instead of wrapped in a
tuple ... here's the result:

TypeError: argument list must be a tuple
Call failed

Oh by the way, you can get away with C-embedding as a module name if
you are importing it from C, but importing it from Python [so that you
could test it independently of your C program] presents a difficulty
(syntax error) ... better to change it to c_embedding.

> > It's mainly just a matter of (1) knowing what you want to do (2)
> > picking the API that does what you want (3) checking the returned
> > value for error after every call.

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


Python code for testing well parenthesized expression

2009-07-14 Thread candide
Hi,

I'm trying to implement in Python a function testing if an expression is well
parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik" is correctly
parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not.

My code follows at the end.

If you have a better algorithm or a better Python code (I'm a beginner in the
Python world), don't hesitate ...



#--

# The obvious iterative version
def i(s):
op = 0 # op : open parenthesis
for k in range(len(s)):
op += (s[k] == '(') - (s[k] == ')')
if op < 0: break
return op


# Recursive implementation of the preceding version
def r(s,op=0): # op : open parenthesis
if len(s)==0:
return op
elif s[0]=='(':
return r(s[1:],op+1)
elif s[0]==')':
if op==0:
return -1
else :
return r(s[1:],op-1)
else :
return r(s[1:],op)


# "functional" style version
def f(s):
if (len(s)!=0 and s[0]=='('):
z=f(s[1:])
if len(z)!=0:
return f(z[1:])
else:
return None
elif len(s)==0 or s[0] == ')':
return s
else:
return f(s[1:])


def test(t,f):
for z in t:
print (z,f(z)==0)

# True True True True True False False
t=["zx4er(1(er(Yy)ol)ol)ik",
"x(x)x(x(x)xx(xx(x)x(x(x)xx)())x(x(x)xx)()x)()",
"a(ty(y(y(bn)))lokl)kl",
"xc(er(tgy(rf(yh)()uj)ki))",
"e",
"rf(tgt)juj)jkik(jun)",
"zx(4er(1(er(Yy)ol)ol)ik"]

test(t,i)
print

test(t,r)
print

def test(t):
for s in t: print (s,f(s)=="")

test(t)
#---

and the corresponding output :


('zx4er(1(er(Yy)ol)ol)ik', True)
('x(x)x(x(x)xx(xx(x)x(x(x)xx)())x(x(x)xx)()x)()', True)
('a(ty(y(y(bn)))lokl)kl', True)
('xc(er(tgy(rf(yh)()uj)ki))', True)
('e', True)
('rf(tgt)juj)jkik(jun)', False)
('zx(4er(1(er(Yy)ol)ol)ik', False)

('zx4er(1(er(Yy)ol)ol)ik', True)
('x(x)x(x(x)xx(xx(x)x(x(x)xx)())x(x(x)xx)()x)()', True)
('a(ty(y(y(bn)))lokl)kl', True)
('xc(er(tgy(rf(yh)()uj)ki))', True)
('e', True)
('rf(tgt)juj)jkik(jun)', False)
('zx(4er(1(er(Yy)ol)ol)ik', False)

('zx4er(1(er(Yy)ol)ol)ik', True)
('x(x)x(x(x)xx(xx(x)x(x(x)xx)())x(x(x)xx)()x)()', True)
('a(ty(y(y(bn)))lokl)kl', True)
('xc(er(tgy(rf(yh)()uj)ki))', True)
('e', True)
('rf(tgt)juj)jkik(jun)', False)
('zx(4er(1(er(Yy)ol)ol)ik', False)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: explode()

2009-07-14 Thread Fred Atkinson
On Tue, 14 Jul 2009 05:41:40 GMT, Tim Harig 
wrote:

>On 2009-07-14, Fred Atkinson  wrote:
>>  The one thing I really dislike about Python over PHP is that
>> Python can usually only appear in the cgi directory (unless other
>> arragements are made with your hosting provider or if you reconfigure
>> Apache on your own server if you have your own).  With PHP, I can put
>> them in any folder on my Web site without any problem.  
>
>That is a server configuration and has nothing to do with Python directly.

Agreed, it doesn't.  But if my hosting provider won't change it, I'm
stuck with it.  

Regards, 



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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Jeremy Sanders
candide wrote:

> I'm trying to implement in Python a function testing if an expression is
> well parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik"
> is correctly parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not.
> 
> My code follows at the end.
> 
> If you have a better algorithm or a better Python code (I'm a beginner in
> the Python world), don't hesitate ...

Don't you want to just test that the number of "("s equals the number of 
")"s or am I missing the point?

>>> a='aAAA(bbb(cc)))'
>>> a.count('(') == a.count(')')

Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/

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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Adrian Dziubek
Strings are immutable, so your method of slicing one letter at time
will be building lots of them. That shouldn't hurt you here, but it
will when you hit a bigger problem. In the i() there should be "return
op == 0" on the end.

def well(expr):
  mapping = {'(':1, ')':-1}
  count = 0
  for s in expr:
if s in mapping:
  count += mapping[s]
if s < 0:
  return False
  return count == 0

def test_well():
  examples = [
('zx4er(1(er(Yy)ol)ol)ik', True),
('x(x)x(x(x)xx(xx(x)x(x(x)xx)())x(x(x)xx)()x)()',
True),
('a(ty(y(y(bn)))lokl)kl', True),
('xc(er(tgy(rf(yh)()uj)ki))', True),
('e', True),
('rf(tgt)juj)jkik(jun)', False),
('zx(4er(1(er(Yy)ol)ol)ik', False),
  ]
  for expr, expected in examples:
assert well(expr) == expected
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Diez B. Roggisch
Jeremy Sanders wrote:

> candide wrote:
> 
>> I'm trying to implement in Python a function testing if an expression is
>> well parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik"
>> is correctly parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not.
>> 
>> My code follows at the end.
>> 
>> If you have a better algorithm or a better Python code (I'm a beginner in
>> the Python world), don't hesitate ...
> 
> Don't you want to just test that the number of "("s equals the number of
> ")"s or am I missing the point?

Yep, you are:

"(((("

is certainly not "well parenthized".

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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Adrian Dziubek
> Don't you want to just test that the number of "("s equals the number of
> ")"s or am I missing the point?
I had this idea too, but there is additional requirement that any
beginning must have greater or equal number of '(' than ')'.
--
Adrian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: explode()

2009-07-14 Thread Fred Atkinson
On Mon, 13 Jul 2009 23:54:11 -0700 (PDT), alex23 
wrote:

>Fred Atkinson  wrote:
>>         I wish the Python site was as well written as the PHP site. On
>> the PHP site, I can look up a command and they show not only the docs
>> on that command but a list of all other commands associated with it.  
>
>Hey Fred,
>
>My problem is the complete opposite, I wish I could as easily
>interrogate objects in PHP about their behaviour as I can Python :)
>
>In case you're not familiar with this, you can see what methods are
>attached to an object using the intepreter via dir() and see the
>associated docstring for them via help(). Try looking at 'dir(str)'
>for a list of methods that strings recognise, then 'help(str.join)' to
>see the help on join.
>
>This is such a handy ability to have that I miss this casual
>introspection in everything else in which I'm required to develop.
>
>Hope this helps.

I appreciate the information.  I'm halfway through a course in
PHP and Python.  We are given assignments and we have to write the
assignment in both languages.  

I'll take a look at that as I work on this week's assignment
(I've only got a month to finish the course but I can probably take
some time to look at this.  

Regards, 




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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Martin P. Hellwig

candide wrote:
To add to your implementations; a readable version:

+++file parantheses.py+++
"""Parentheses Module Test"""

def parentheses_are_paired(input_string):
"Check if 'input_string' contains paired parentheses, if so return 
True."

parenthesis_count = 0
parenthesis_open = '('
parenthesis_close = ')'

for character in input_string:
if character == parenthesis_open:
parenthesis_count += 1
elif character == parenthesis_close:
parenthesis_count -= 1


if parenthesis_count == 0:
return(True)
else:
if parenthesis_count < 0:
error_text = 'More closing parantheses than opening ones'

elif parenthesis_count > 0:
error_text = 'More opening parantheses than closing ones'

raise(ValueError(error_text))

if __name__ == '__main__':
TEST_TRUE = 'zx4er(1(er(Yy)ol)ol)ik'
TEST_ERROR = 'zx(4er(1(er(Yy)ol)ol)ik'

print(parentheses_are_paired(TEST_TRUE))

try:
print(parentheses_are_paired(TEST_ERROR))
except(ValueError):
print(False)

---file parantheses.py---

--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Jeremy Sanders
Diez B. Roggisch wrote:

> Yep, you are:
> 
> "(((("
> 
> is certainly not "well parenthized".

Thanks for that!

-- 
Jeremy Sanders
http://www.jeremysanders.net/

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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread David Smith
Jeremy Sanders wrote:
> candide wrote:
> 
>> I'm trying to implement in Python a function testing if an expression is
>> well parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik"
>> is correctly parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not.
>>
>> My code follows at the end.
>>
>> If you have a better algorithm or a better Python code (I'm a beginner in
>> the Python world), don't hesitate ...
> 
> Don't you want to just test that the number of "("s equals the number of 
> ")"s or am I missing the point?
> 
 a='aAAA(bbb(cc)))'
 a.count('(') == a.count(')')
> 
> Jeremy
> 

Using straight counting, )z))ab(c(ew( would be well parenthesized.  I
suspect a better way would be to iterate over the string using a balance
counter that increases 1 for every open, decreases 1 for every close.  A
negative balance at any moment would indicate an error as well as an
ending balance greater than 0.

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


Re: Efficient binary search tree stored in a flat array?

2009-07-14 Thread Scott David Daniels

Piet van Oostrum wrote:

Douglas Alan  (DA) wrote:



DA> On Jul 13, 3:57 pm, [email protected] (Aahz) wrote:

Still, unless your list is large (more than thousands of elements),
that's the way you should go.  See the bisect module.  Thing is, the
speed difference between C and Python means the constant for insertion
and deletion is very very small relative to bytecode speed.  Keep in
mind that Python's object/binding model means that you're shuffling
pointers in the list rather than items.



DA> Thank you. My question wasn't intended to be Python specific, though.
DA> I am just curious for purely academic reasons about whether there is
DA> such an algorithm. All the sources I've skimmed only seem to the
DA> answer the question via omission. Which is kind of strange, since it
DA> seems to me like an obvious question to ask.


It may well be that there is no good simple solution, and people avoid
writing about non-existent algorithms.  I certainly cannot imagine
trying to write an article that carefully covered ideas which don't
have well-studied data structures available, and calling them out
only to say, "we don't know how to do this well."  If such an algorithm
were simple and obvious, I dare say you'd be taught about it around the
time you learn binary search.


Of course you can take any BST algorithm and replace pointers by indices
in the array and allocate new elements in the array. But then you need
array elements to contain the indices for the children explicitely.


And you loower your locality of reference (cache-friendliness).
Note the insert in Python, for example, is quite cache-friendly.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Martin P. Hellwig

Martin P. Hellwig wrote:

candide wrote:
To add to your implementations; a readable version:

+++file parantheses.py+++
"""Parentheses Module Test"""

def parentheses_are_paired(input_string):
"Check if 'input_string' contains paired parentheses, if so return 
True."

parenthesis_count = 0
parenthesis_open = '('
parenthesis_close = ')'

for character in input_string:
if character == parenthesis_open:
parenthesis_count += 1
elif character == parenthesis_close:
parenthesis_count -= 1


if parenthesis_count == 0:
return(True)
else:
if parenthesis_count < 0:
error_text = 'More closing parantheses than opening ones'

elif parenthesis_count > 0:
error_text = 'More opening parantheses than closing ones'

raise(ValueError(error_text))

if __name__ == '__main__':
TEST_TRUE = 'zx4er(1(er(Yy)ol)ol)ik'
TEST_ERROR = 'zx(4er(1(er(Yy)ol)ol)ik'

print(parentheses_are_paired(TEST_TRUE))

try:
print(parentheses_are_paired(TEST_ERROR))
except(ValueError):
print(False)

---file parantheses.py---



However as Mr. Roggisch commented this wouldn't check if it is on the 
right spot, by moving the check that at any time you can not have more 
closing ones than opening ones within the loop you will get those 
exceptions too.


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for testing well parenthesized expression

2009-07-14 Thread John Machin
candide  free.invalid> writes:

> # The obvious iterative version
> def i(s):
> op = 0 # op : open parenthesis
> for k in range(len(s)):
> op += (s[k] == '(') - (s[k] == ')')
> if op < 0: break
> return op
> 

E: H c, w t P.
F: A c, b à P.

Suggested better code:

def iterative(string):
paren_count = 0
for char in string:
paren_count += (char == '(') - (char == ')')
if paren_count < 0: break
return paren_count

You don't need the other versions :-)

Try an iterative version of checking that () [] and {}
are balanced and nested appropriately.

Cheers,
John

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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread John Machin
On Jul 14, 11:08 pm, David Smith  wrote:
> Jeremy Sanders wrote:
> > candide wrote:
>
> >> I'm trying to implement in Python a function testing if an expression is
> >> well parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik"
> >> is correctly parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not.
>
> >> My code follows at the end.
>
> >> If you have a better algorithm or a better Python code (I'm a beginner in
> >> the Python world), don't hesitate ...
>
> > Don't you want to just test that the number of "("s equals the number of
> > ")"s or am I missing the point?
>
>  a='aAAA(bbb(cc)))'
>  a.count('(') == a.count(')')
>
> > Jeremy
>
> Using straight counting, )z))ab(c(ew( would be well parenthesized.  I
> suspect a better way would be to iterate over the string using a balance
> counter that increases 1 for every open, decreases 1 for every close.  A
> negative balance at any moment would indicate an error as well as an
> ending balance greater than 0.
>
> --David

Ummm isn't that the OP's first function?
-- 
http://mail.python.org/mailman/listinfo/python-list


WHIFF 0.4 += repoze.who authentication + menus + calculator + docs.

2009-07-14 Thread Aaron Watters
WHIFF (WSGI HTTP Integrated Filesystem Frames) 0.4 released.

The new WHIFF 0.4 release linked from

http://whiff.sourceforge.net

includes the following enhancements:

Built in support for repoze.who based authentication
(from http://static.repoze.org/whodocs/ ) + tutorial
   see: http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1500.who .

AJAX calculator demo and tutorial:
   see: http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1400.calc .

Built in drop-down menu support and tutorial:
   see: http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1300.menus .

Some subtle but important bug fixes, including a thread
race condition bug fix.  Auto-reload support.

Also documentation improvements: particularly
for standard middleware
   see: http://aaron.oirt.rutgers.edu/myapp/docs/W1200_1400.stdMiddleware

What is WHIFF?

WHIFF is a collection of support services for Python WSGI
applications which allows applications to be composed
by "dropping" dynamic pages into container directories.
This mode of development will be familiar to developers
who have created PHP applications, vanilla CGI scripts,
Apache/modpy Publisher applications, JSP pages, or
static web content.

The WHIFF implementation significantly generalizes the
"drop in" paradigm to support WSGI middleware components
and application fragments as well as stand-alone pages.

WHIFF provides other services in addition to supporting
"drop in" components, such as managed application
resources.

I created WHIFF to address complexity issues I
encounter when creating and fixing sophisticated
Web applications which include complex database
interactions and dynamic features such as AJAX
(Asynchronous Javascript And XML).

Project home page:
   http://whiff.sourceforge.net .
Documentation index:
   http://aaron.oirt.rutgers.edu/myapp/docs/W.intro .

I hope you like it!

   -- Aaron Watters

===
% ping elvis
elvis is alive
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python code for testing well parenthesized expression

2009-07-14 Thread John Machin
Adrian Dziubek  gmail.com> writes:


> In the i() there should be "return
> op == 0" on the end.

Hard to tell. In the absence of any docs, we have to resort to divination on the
function name :-P ... is "i" short for "iterative" or "imbalanced"?



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


Re: PDF: finding a blank image

2009-07-14 Thread DrLeif
On Jul 13, 6:22 pm, Scott David Daniels  wrote:
> DrLeif wrote:
> > I have about 6000 PDF files which have been produced using a scanner
> > with more being produced each day.  The PDF files contain old paper
> > records which have been taking up space.   The scanner is set to
> > detect when there is information on the backside of the page (duplex
> > scan).  The problem of course is it's not the always reliable and we
> > wind up with a number of PDF files containingblankpages.
>
> > What I would like to do is have python detect a "blank" pages in a PDF
> > file and remove it.  Any suggestions?
>
> I'd check into ReportLab's commercial product, it may well be easily
> capable of that.  If no success, you might contact PJ at Groklaw, she
> has dealt with a _lot_ of PDFs (and knows people who deal with PDFs
> in bulk).
>
> --Scott David Daniels
> [email protected]

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


Re: Infinite loops and synchronization

2009-07-14 Thread Aahz
In article ,
Vincent Gulinao   wrote:
>
>lst = list()
>
>while True:
>   if len(lst) == SOME_NUMBER:
>   return lst
>
>Q2: operating on list from threads (mostly appends) must be safe,
>right (synchronization)?

What do you mean by "safe"?  Python certainly won't crash, but there's
no guarantee that the list will be consistent from *your* perspective.
Consider what happens if len(lst) == SOME_NUMBER - 1 and some other part
of your code adds two elements to lst.  You'll skip right over your if
condition.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compilation problem of python on AIX 6.1

2009-07-14 Thread Aahz
In article <51c556a8-7277-474d-821f-190adf155...@f16g2000vbf.googlegroups.com>,
Amit   wrote:
>
>THen I decided to compile python 2.5.4 on my AIX box. I downloaded the
>python source code from www.python.org and tried to compile on my AIX
>both using gcc.
>
>   case $MAKEFLAGS in  *-s*)  CC='gcc -pthread' LDSHARED='./Modules/
>ld_so_aix gcc -pthread -bI:Modules/python.exp' OPT='-DNDEBUG -g -
>fwrapv -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q
>build;;  *)  CC='gcc -pthread' LDSHARED='./Modules/ld_so_aix gcc -
>pthread -bI:Modules/python.exp' OPT='-DNDEBUG -g -fwrapv -O3 -Wall -
>Wstrict-prototypes' ./python -E ./setup.py build;;  esac
>running build
>running build_ext
>building 'bz2' extension
>gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -
>Wstrict-prototypes -I. -I/avre/Python-2.5.4/./Include -I. -IInclude -
>I./Include -I/avre/Python-2.5.4/Include -I/avre/Python-2.5.4 -c /avre/
>Python-2.5.4/Modules/bz2module.c -o build/temp.aix-6.1-2.5/avre/
>Python-2.5.4/Modules/bz2module.o
>building '_tkinter' extension
>./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/
>temp.aix-6.1-2.5/avre/Python-2.5.4/Modules/_tkinter.o build/
>temp.aix-6.1-2.5/avre/Python-2.5.4/Modules/tkappinit.o -L/usr/X11/lib -
>ltk8.4 -ltcl8.4 -lX11 -o build/lib.aix-6.1-2.5/_tkinter.so
>*** WARNING: renaming "_tkinter" since importing it failed:0509-022
>Cannot load module build/lib.aix-6.1-2.5.
>   0509-026 System error: A file or directory in the path name does not
>exist.

This looks like a generic AIX compilation error finding system libraries;
you probably will get better results from asking on an AIX forum.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


one-time factory in python for an experienced java guy

2009-07-14 Thread phonky

Hi

I have searched all over and haven't found the solution
for my problem yet. I am new to python, and all the time realize I
do program python in java, which is not great.

Besides being a real-life problem, I want to
solve it as elegant as I can, using it to
also learn about python (I know I could just
hack something easy for now).

That's what I want to do.

I have an Account class.
An Account instance has to get an account number.
On instance creation, I want the account number to
be generated (I don't want callers to pass
the account # to ensure uniqueness):

class Account(object):
def __init__(self, holder):
self.__accountnumber = self.__generate_account_number()

Now, I do not know yet how the account number scheme looks like.
For now, I just want to have an incremental number; later,
when going to production, we'll need the proper one.

Furthermore, as we plan to distribute the package, we want
to allow custom account numbering schemes. Thus, customers
should be able to plug in their own AccountNumberGenerator implementation.

For now, I have a generators.py module.

I have an AccountNumberGenerator base class,
all subclasses should implement "generate".

I have an IncrementalGenerator subclass.

So for now, I need to instantiate IncrementalGenerator,
allowing for a future module to plugin their own generator.

Any suggestions on how to do this?
Thanks so much
--
http://mail.python.org/mailman/listinfo/python-list


Re: PDF: finding a blank image

2009-07-14 Thread DrLeif
On Jul 13, 6:22 pm, Scott David Daniels  wrote:
> DrLeif wrote:
> > I have about 6000 PDF files which have been produced using a scanner
> > with more being produced each day.  The PDF files contain old paper
> > records which have been taking up space.   The scanner is set to
> > detect when there is information on the backside of the page (duplex
> > scan).  The problem of course is it's not the always reliable and we
> > wind up with a number of PDF files containingblankpages.
>
> > What I would like to do is have python detect a "blank" pages in a PDF
> > file and remove it.  Any suggestions?
>
> I'd check into ReportLab's commercial product, it may well be easily
> capable of that.  If no success, you might contact PJ at Groklaw, she
> has dealt with a _lot_ of PDFs (and knows people who deal with PDFs
> in bulk).
>
> --Scott David Daniels
> [email protected]


Thanks everyone for the quick reply.

I had considered using ReportLab however, was uncertain about it's
ability to detect a blank page.

Scott, I'll drop an email to ReportLab and PJ

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


Re: Tkinter / Entry widget problem

2009-07-14 Thread John Posner



Andras Szabo wrote:

  

Hello. I searched the archives but couldn't find a solution to a
problem related to the Entry widget in Tkinter.

When creating a pop-up window in an app, which contains an Entry
widget, I want this widget to contain some default string, to have all
this default string selected (as if the user had manually selected
everything), and to have the focus transferred to this widget.

(The idea is then that if the window pops up, the user won't have to
click or press Tab any more before being able to type what is needed
in the textbox, overwriting what is written there already.)

I thought this might be the way to go:

entrybox=Entry(toplevel_parent_window)
entrybox.insert(0,"Some default string")
entrybox.select_range(0,END)
entrybox.focus_set()
entrybox.pack()

But it doesn't seem to work - the focus is not transferred to the
Entry widget, and the text does not appear to be selected (even though
after this entrybox.selection_present() returns True).

What am I doing wrong?



Nothing, I would think. Can you post a minimal runnable example?

Peter


This works for me, on Windows and Linux:

 from Tkinter import *

 rt = Tk()
 rt.title("root window")
 pop = Toplevel()
 pop.title("second window")

 entrybox=Entry(pop)
 entrybox.insert(0,"Some default string")
 entrybox.select_range(0,END)
 entrybox.focus_set()
 entrybox.pack()

 rt.withdraw()
 rt.mainloop()


On Win/XP SP3:

 > python
 Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
  (Intel)] on   win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import Tkinter
 >>> Tkinter.TkVersion
 8.5
 >>> Tkinter.TclVersion
 8.5

On Ubuntu Linux (Ubu-SL 2.6.27.14-generic):

 $ python
 Python 2.6.1 (r261:67515, Jan  9 2009, 19:06:23)
 [GCC 4.3.2] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import Tkinter
 >>> Tkinter.TkVersion
 8.4004
 >>> Tkinter.TclVersion
 8.4004


-John

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


Re: explode()

2009-07-14 Thread Piet van Oostrum
> Fred Atkinson  (FA) wrote:

>FA> On Tue, 14 Jul 2009 05:41:40 GMT, Tim Harig 
>FA> wrote:

>>> On 2009-07-14, Fred Atkinson  wrote:
 The one thing I really dislike about Python over PHP is that
 Python can usually only appear in the cgi directory (unless other
 arragements are made with your hosting provider or if you reconfigure
 Apache on your own server if you have your own).  With PHP, I can put
 them in any folder on my Web site without any problem.  
>>> 
>>> That is a server configuration and has nothing to do with Python directly.

>FA> Agreed, it doesn't.  But if my hosting provider won't change it, I'm
>FA> stuck with it.  

That's a good reason to dislike your hosting provider, not a good reason
to dislike Python.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Stefan Behnel
phonky wrote:
> class Account(object):
> def __init__(self, holder):
> self.__accountnumber = self.__generate_account_number()
> 
> Now, I do not know yet how the account number scheme looks like.
> For now, I just want to have an incremental number; later,
> when going to production, we'll need the proper one.

Use a global variable in the module.

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


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Paul Rubin
Stefan Behnel  writes:

> phonky wrote:
> > class Account(object):
> > def __init__(self, holder):
> > self.__accountnumber = self.__generate_account_number()
> > 
> > Now, I do not know yet how the account number scheme looks like.
> > For now, I just want to have an incremental number; later,
> > when going to production, we'll need the proper one.
> 
> Use a global variable in the module.

Yuch!  Don't use a global.  Try something like:

import itertools

class Account(object):
   def __init__(self, holder, gen=itertools.count()):
  self.__accountnumber = gen.next()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread phonky

Stefan, thanks first of all


Use a global variable in the module.


I have an account_number_generator variable in the module,
I got that hint from searching the web.

But where my stubborn java mind doesn't release me:
what does the variable contain? Do I create the actual
IncrementalGenerator object there? Or the super class?
Or just a string, which a factory method takes to
create the actual object?

What I especially don't get:
How will an external module overwrite that variable?

I fail to see, python being interpreted, how I can ensure
that a future module is being executed later, thus
overwriting the variable.

Thanks again.

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


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Paul Rubin
phonky  writes:
> But where my stubborn java mind doesn't release me: what does the
> variable contain? Do I create the actual IncrementalGenerator object
> there? Or the super class?  Or just a string, which a factory method
> takes to create the actual object?

Ugh, just forget everything you ever knew about java.  Do some Zen
exercises to erase your mind.  Then read a Python tutorial as if
you're starting from nothing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why does extend() fail in this case, and what am I doing wrong?

2009-07-14 Thread Xavier Ho
Why doesn't the second output print [1, 2, 3,  , 7, 8, 9] ?
The code is run at: http://codepad.org/wgLU4JZh

class A():
def __init__(self):
self.n = [1, 2, 3, 4, 5]

a = A()
print a.n
print a.n.extend([6, 7, 8, 9])

#Output:
#[1, 2, 3, 4, 5]
#None

I really don't know, but I'm probably missing something. Any pointers would
be great.

Best regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: [email protected]
Website: http://xavierho.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread phonky

Thanks Paul,


Ugh, just forget everything you ever knew about java.  Do some Zen
exercises to erase your mind.  Then read a Python tutorial as if
you're starting from nothing.


Yeah, surely right, but easier said than done...
I'm working on it.

Taking your example.

import itertools

class Account(object):
   def __init__(self, holder, gen=itertools.count()):
  self.__accountnumber = gen.next()

If you consider my python illiteracy,

"itertools.count(): Make an iterator that returns consecutive integers 
starting with n"


to me that sounds like that solves the increment issue, but what about
future modules wanting to plug in a different
numbering format, e.g. 205434.1234 or whatever?


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


Re: Why does extend() fail in this case, and what am I doing wrong?

2009-07-14 Thread Pablo Torres N.
This has been asked extensively before, here and elsewhere.

On Tue, Jul 14, 2009 at 09:52, Xavier Ho wrote:
> Why doesn't the second output print [1, 2, 3,  , 7, 8, 9] ?
> The code is run at: http://codepad.org/wgLU4JZh
>
> class A():
>     def __init__(self):
>     self.n = [1, 2, 3, 4, 5]
>
> a = A()
> print a.n
> print a.n.extend([6, 7, 8, 9])
>
> #Output:
> #[1, 2, 3, 4, 5]
> #None
>
> I really don't know, but I'm probably missing something. Any pointers would
> be great.
>
> Best regards,
>
> Ching-Yun "Xavier" Ho, Technical Artist
>
> Contact Information
> Mobile: (+61) 04 3335 4748
> Skype ID: SpaXe85
> Email: [email protected]
> Website: http://xavierho.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
Pablo Torres N.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Mahmoud Abdelkader
What Paul was trying to elaborate on is that have your customers or whomever
will use this implement their own generator protocol to generate whatever
number format they need. Paul just gave you an example with
itertools.count(), where it is an infinite generator that yields count+1
every time.

Read up on the iterator protocol, have your customers pass in a generator to
establish their own formats.
http://docs.python.org/library/stdtypes.html#iterator-types

This is much more elegant than AbstractCustomerRandomFormatGenerator..etc
which is what the reference to "erase everything from Java" is attempting to
relate.

--
mahmoud mack abdelkader
python powered
http://blog.mahmoudimus.com/
[email protected]


On Tue, Jul 14, 2009 at 10:55 AM, phonky  wrote:

> Thanks Paul,
>
>  Ugh, just forget everything you ever knew about java.  Do some Zen
>> exercises to erase your mind.  Then read a Python tutorial as if
>> you're starting from nothing.
>>
>
> Yeah, surely right, but easier said than done...
> I'm working on it.
>
> Taking your example.
>
> import itertools
>
>class Account(object):
>   def __init__(self, holder, gen=itertools.count()):
>  self.__accountnumber = gen.next()
>
> If you consider my python illiteracy,
>
> "itertools.count(): Make an iterator that returns consecutive integers
> starting with n"
>
> to me that sounds like that solves the increment issue, but what about
> future modules wanting to plug in a different
> numbering format, e.g. 205434.1234 or whatever?
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does extend() fail in this case, and what am I doing wrong?

2009-07-14 Thread MRAB

Xavier Ho wrote:

Why doesn't the second output print [1, 2, 3,  , 7, 8, 9] ?
The code is run at: http://codepad.org/wgLU4JZh

class A():
def __init__(self):
self.n = [1, 2, 3, 4, 5]
   
a = A()

print a.n
print a.n.extend([6, 7, 8, 9])

#Output:
#[1, 2, 3, 4, 5]
#None

I really don't know, but I'm probably missing something. Any pointers 
would be great.



The extend() method modifies the list in-place and returns None. Try
printing a.n after extending.
--
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Paul Rubin
phonky  writes:
> "itertools.count(): Make an iterator that returns consecutive integers
> starting with n"
> 
> to me that sounds like that solves the increment issue, but what about
> future modules wanting to plug in a different
> numbering format, e.g. 205434.1234 or whatever?

You'd write a different generator for that, and use it instead of
itertools.count.  E.g. (untested):

  def different_gen():
  a  = 201593.0768  # initial number
  while True:
 yield '%.04f'% a
 a += 123.4567  # increase in increments of this much
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does extend() fail in this case, and what am I doing wrong?

2009-07-14 Thread Jochen Schulz
Xavier Ho:
>
> Why doesn't the second output print [1, 2, 3,  , 7, 8, 9] ?
-- snip
> print a.n.extend([6, 7, 8, 9])

extend doesn't fail. It just returns None and extends the list in place.

In [1]: l = [1, 2, 3]

In [2]: l.extend([4, 5, 6])

In [3]: l
Out[3]: [1, 2, 3, 4, 5, 6]


J.
-- 
When I get home from the supermarket I don't know what to do with all the
plastic.
[Agree]   [Disagree]
 


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Peter Otten
phonky wrote:

> Thanks Paul,
> 
>> Ugh, just forget everything you ever knew about java.  Do some Zen
>> exercises to erase your mind.  Then read a Python tutorial as if
>> you're starting from nothing.
> 
> Yeah, surely right, but easier said than done...
> I'm working on it.
> 
> Taking your example.
> 
> import itertools
> 
>  class Account(object):
> def __init__(self, holder, gen=itertools.count()):
>self.__accountnumber = gen.next()
> 
> If you consider my python illiteracy,
> 
> "itertools.count(): Make an iterator that returns consecutive integers
> starting with n"
> 
> to me that sounds like that solves the increment issue, but what about
> future modules wanting to plug in a different
> numbering format, e.g. 205434.1234 or whatever?

In that case you may want to stick with the class attribute:

>>> class Account(object):
... def __init__(self):
... self.account = self.next_account()
... def __str__(self):
... return "Account(number=%r)" % self.account
... __repr__ = __str__
...
>>> from itertools import count
>>> Account.next_account = count(42).next
>>> a = Account()
>>> b = Account()
>>> a, b
(Account(number=42), Account(number=43))
>>> from uuid import uuid1
>>> Account.next_account = staticmethod(uuid1)
>>> c = Account()
>>> d = Account()
>>> c, d
(Account(number=UUID('b0f8dfc6-7087-11de-be16-001d923f29c5')), 
Account(number=UUID('b310c90e-7087-11de-be16-001d923f29c5')))

You can plug in arbitrary callables at runtime. The only complication I can 
see is that you may have to wrap them into a staticmethod to prevent python 
from passing the self reference. You can avoid that if you just use a global 
instead:

# account.py
next_account = ...
class Account(object):
   def __init__(self): self.number = next_account()

You can then set the factory elsewhere

# main.py
import account
account.next_account = ...
a = Account()

In general in python we like to keep simple things simple rather than 
creating a huge bureaucracy.

Peter

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


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Aahz
In article <[email protected]>,
phonky   wrote:
>
>import itertools
>
> class Account(object):
>def __init__(self, holder, gen=itertools.count()):
>   self.__accountnumber = gen.next()
>
>If you consider my python illiteracy,
>
>"itertools.count(): Make an iterator that returns consecutive integers 
>starting with n"
>
>to me that sounds like that solves the increment issue, but what about
>future modules wanting to plug in a different
>numbering format, e.g. 205434.1234 or whatever?

Here's what I would do:

class Account:
gen = itertools.count
gen_instance = None

def __init__(self, holder):
if self.gen_instance is None:
self.__class__.gen_instance = self.gen()
self._account = self.gen_instance()

Notice that I'm using only a single underscore for ``_account`` to make
inheritance simpler, and I'm using ``self`` to access class attributes
*except* when I need to *set* the class attribute, which requires
``self.__class__``.

Now anyone who wants to change the generator can simply do
module.Account.gen = other_gen 
and it will work as long as no Account() instances have been created (you
don't want the generator to change mid-stream, right?).
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread pdpi
On Jul 14, 3:03 pm, phonky  wrote:
> Hi
>
> I have searched all over and haven't found the solution
> for my problem yet. I am new to python, and all the time realize I
> do program python in java, which is not great.
>
> Besides being a real-life problem, I want to
> solve it as elegant as I can, using it to
> also learn about python (I know I could just
> hack something easy for now).
>
> That's what I want to do.
>
> I have an Account class.
> An Account instance has to get an account number.
> On instance creation, I want the account number to
> be generated (I don't want callers to pass
> the account # to ensure uniqueness):
>
> class Account(object):
>         def __init__(self, holder):
>                 self.__accountnumber = self.__generate_account_number()
>
> Now, I do not know yet how the account number scheme looks like.
> For now, I just want to have an incremental number; later,
> when going to production, we'll need the proper one.
>
> Furthermore, as we plan to distribute the package, we want
> to allow custom account numbering schemes. Thus, customers
> should be able to plug in their own AccountNumberGenerator implementation.
>
> For now, I have a generators.py module.
>
> I have an AccountNumberGenerator base class,
> all subclasses should implement "generate".
>
> I have an IncrementalGenerator subclass.
>
> So for now, I need to instantiate IncrementalGenerator,
> allowing for a future module to plugin their own generator.
>
> Any suggestions on how to do this?
> Thanks so much

You don't want an AccountNumberGenerator class and subclassing, all
you need is an iterator/generator of some form.

These might help:
http://docs.python.org/tutorial/classes.html#iterators
http://docs.python.org/tutorial/classes.html#generators
(in fact, that whole page is pretty relevant)

Once your code expects one of those, it's trivially easy to plug
something else in there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: Decimal literals in Python.

2009-07-14 Thread Scott David Daniels

Tim Roberts wrote:

My favorite notation for this comes from Ada, which allows arbitrary bases
from 2 to 16, and allows for underscores within numeric literals:

  x23_bin : constant :=  2#0001_0111#;
  x23_oct : constant :=  8#27#;
  x23_dec : constant := 10#23#;
  x23_hex : constant := 16#17#;

And mine is one w/o the base 10 bias:
.f.123 == 0x123
.7.123 == 0o123
.1.1101 == 0b1101
That is, ..
-- show the base by showing base-1 in the base.
I actually built this into "OZ," an interpretter.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does extend() fail in this case, and what am I doing wrong?

2009-07-14 Thread Xavier Ho
I see. Thanks!

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: [email protected]
Website: http://xavierho.com/


On Tue, Jul 14, 2009 at 11:20 PM, Jochen Schulz  wrote:

> Xavier Ho:
> >
> > Why doesn't the second output print [1, 2, 3,  , 7, 8, 9] ?
> -- snip
> > print a.n.extend([6, 7, 8, 9])
>
> extend doesn't fail. It just returns None and extends the list in place.
>
> In [1]: l = [1, 2, 3]
>
> In [2]: l.extend([4, 5, 6])
>
> In [3]: l
> Out[3]: [1, 2, 3, 4, 5, 6]
>
>
> J.
> --
> When I get home from the supermarket I don't know what to do with all the
> plastic.
> [Agree]   [Disagree]
> 
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.9 (GNU/Linux)
>
> iEYEARECAAYFAkpcoiwACgkQ+AfZydWK2zmchgCfZjRCOGTa0OZ1Q045sCLZfpvD
> EIEAnjJ8/uNwPYFfCsGNbQIDd5+LnkbA
> =fCdV
> -END PGP SIGNATURE-
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Carl Banks
On Jul 14, 2:14 am, Steven D'Aprano
 wrote:
> On Tue, 14 Jul 2009 01:30:48 -0700, Carl Banks wrote:
> > Seriously, do you *ever* take more than 2 seconds to consider whether
> > you might be missing something obvious before following up with these
> > indignant knee-jerk responses?
>
> Obviously not.
>
> [...]
>
> > Or would you rather let all unexpected exceptions print to standard
> > error, which is often a black hole in non-interactive sitations?
>
> Fair point. Of course you're right.

I don't want to be mean or anything.  I agree with you on 95% of
issues probably, of course I only follow up to disagree

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


Re: Proposal: Decimal literals in Python.

2009-07-14 Thread MRAB

Scott David Daniels wrote:

Tim Roberts wrote:
My favorite notation for this comes from Ada, which allows arbitrary 
bases

from 2 to 16, and allows for underscores within numeric literals:

  x23_bin : constant :=  2#0001_0111#;
  x23_oct : constant :=  8#27#;
  x23_dec : constant := 10#23#;
  x23_hex : constant := 16#17#;

And mine is one w/o the base 10 bias:
.f.123 == 0x123
.7.123 == 0o123
.1.1101 == 0b1101
That is, ..
-- show the base by showing base-1 in the base.
I actually built this into "OZ," an interpretter.


Smalltalk uses "r" (for "radix"). If we also permit underscores:

x23_bin =  2r0001_0111
x23_oct =  8r27
x23_dec = 10r23
x23_hex = 16r17
--
http://mail.python.org/mailman/listinfo/python-list


why did you choose the programming language(s)you currently use?

2009-07-14 Thread Deep_Feelings
So you have chosen programming language "x" so shall you tell us why
you did so , and  what negatives or positives it has ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The meaning of "="

2009-07-14 Thread Aahz
In article , Piet van Oostrum   wrote:
>> Lawrence D'Oliveiro  (LD) wrote:
>
>>LD> In message , Aahz wrote:
>
>>Aahz> class AttrDict:
>>Aahz> def __getitem__(self, key):
>>Aahz> return getattr(self, key)
>
>>LD> OK, let's try it:
>
>>LD> >>> c = {}
>>LD> >>> c["x"] = 3
>>LD> >>> c.x = 4   
>>LD> Traceback (most recent call last):
>>LD>   File "", line 1, in 
>>LD> AttributeError: 'dict' object has no attribute 'x'
>>LD> >>> class AttrDict:
>>LD> ... def __getitem__(self, key):
>>LD> ... return getattr(self, key)
>>LD> ...
>>LD> >>> c.x = 4
>>LD> Traceback (most recent call last):
>>LD>   File "", line 1, in 
>>LD> AttributeError: 'dict' object has no attribute 'x'
>
>>LD> Nope, still doesn't work...
>
>Of course you need c = AttrDict()

Absolutely -- Lawrence really needs to learn to do his own debugging.

>And to get c.x = 4 working you also need a __setitem__. 

Nope.  You do need __setitem__ so that this works:

c['x'] = 4

>And to get c["x"] working AtrrDict should subclass dict:

Definitely not.  There's a perfectly good dict inside a regular class
instance already.  The only reason to subclass from dict is so that you
get all the dict methods for free; however, the cost is that you get
ugly bugs because of e.g.

c['update'] = 'foo'

Overally, I think it's much better/safer to explicitly pull the dict
methods you want to use.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


how to determine if python is run interactively? (-i)

2009-07-14 Thread jfrancis4970
how do you determine, from within a python program, whether the python
interpreter was launched in interactive mode? in other words, if i
have a program called "test.py", i want to ensure that the program was
launched with this command line:

python -i test.py

(and not just with "python test.py"). the reason is that i'm doing
some very expensive and lengthy initialization in my test.py program
that will be useless unless the program exits to the python prompt
when it is done, where the user can run further python commands.

obviously i can't use sys.argv since that is only for parameters
passed to the test.py program, not for parameters passed to the python
interpreter itself. i haven't found a way to access these options...

any help would be greatly appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter / Entry widget problem

2009-07-14 Thread Andras Szabo
So it's either that I use Python 2.5.1, or that I use it on a Mac.  
(John, your code still doesn't work the way it's supposed to here.) I  
guess I'll upgrade to 2.6.1 and see if it makes a difference. (The  
Tkinter/Tcl versions are the same for me.) Thanks for your help.


andras

On Jul 14, 2009, at 5:07 PM, John Posner wrote:




Andras Szabo wrote:



Hello. I searched the archives but couldn't find a solution to a
problem related to the Entry widget in Tkinter.

When creating a pop-up window in an app, which contains an Entry
widget, I want this widget to contain some default string, to have  
all

this default string selected (as if the user had manually selected
everything), and to have the focus transferred to this widget.

(The idea is then that if the window pops up, the user won't have to
click or press Tab any more before being able to type what is needed
in the textbox, overwriting what is written there already.)

I thought this might be the way to go:

entrybox=Entry(toplevel_parent_window)
entrybox.insert(0,"Some default string")
entrybox.select_range(0,END)
entrybox.focus_set()
entrybox.pack()

But it doesn't seem to work - the focus is not transferred to the
Entry widget, and the text does not appear to be selected (even  
though

after this entrybox.selection_present() returns True).

What am I doing wrong?



Nothing, I would think. Can you post a minimal runnable example?

Peter


This works for me, on Windows and Linux:

from Tkinter import *

rt = Tk()
rt.title("root window")
pop = Toplevel()
pop.title("second window")

entrybox=Entry(pop)
entrybox.insert(0,"Some default string")
entrybox.select_range(0,END)
entrybox.focus_set()
entrybox.pack()

rt.withdraw()
rt.mainloop()


On Win/XP SP3:

> python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
 (Intel)] on   win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> Tkinter.TkVersion
8.5
>>> Tkinter.TclVersion
8.5

On Ubuntu Linux (Ubu-SL 2.6.27.14-generic):

$ python
Python 2.6.1 (r261:67515, Jan  9 2009, 19:06:23)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> Tkinter.TkVersion
8.4004
>>> Tkinter.TclVersion
8.4004


-John




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


Re: Best Way to Handle All Exceptions

2009-07-14 Thread Carl Banks
On Jul 14, 4:48 am, Lawrence D'Oliveiro  wrote:
> In message <93f6a517-63d8-4c80-
>
> [email protected]>, Carl Banks wrote:
> > Or would you rather let all unexpected exceptions print to standard
> > error, which is often a black hole in non-interactive sitations?
>
> Since when?
>
> Cron, for example, collects standard error and mails it to you.

1. Cron is only one way to run programs non-interactively. (Would that
work with, say, Windows services?)
2. Many systems don't run MTAs these days
3. In my experience the pipeline from cron to mail delivery is error
prone, mainly due to the complexity of configuring MTAs
4. Even if all this works, you might just want to do your logging
directly in Python anyway


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


Re: why did you choose the programming language(s)you currently use?

2009-07-14 Thread MRAB

Deep_Feelings wrote:

So you have chosen programming language "x" so shall you tell us why
you did so , and  what negatives or positives it has ?


I've heard of "C" and "D", but not "x", unless you mean XPL (X
Programming Language) or PLAN-X. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to set timeout while colling a soap method?

2009-07-14 Thread ryles
On Jul 13, 9:07 am, dzizes  wrote:
> Hello!
>
> I wrote some some python code for executing a soap method:
>
> import SOAPpy
> from SOAPpy import WSDL
>
> _server = WSDL.Proxy(some wsdl)
> r=_server.generuj(some parameters...)
> print r.encode('cp1250')
>
> It works fine. However, the execution time of this soap method might be
> long. Therefore, I would like to set a timeout like 1 minute, after which I
> would post a timeoute message.
>
> Any ideas?
> Greats,
>
> --
> View this message in 
> context:http://www.nabble.com/how-to-set-timeout-while-colling-a-soap-method-...
> Sent from the Python - python-list mailing list archive at Nabble.com.

I don't believe SOAPpy supports this directly. You can set the timeout
globally before you make your SOAP call:

import socket
socket.setdefaulttimeout(60)

http://docs.python.org/library/socket.html#socket.setdefaulttimeout
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to determine if python is run interactively? (-i)

2009-07-14 Thread Duncan Booth
[email protected] wrote:

> how do you determine, from within a python program, whether the python
> interpreter was launched in interactive mode?

sys.flags.interactive or sys.flags.inspect

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


Re: Python code for testing well parenthesized expression

2009-07-14 Thread Duncan Booth
John Machin  wrote:

> Try an iterative version of checking that () [] and {}
> are balanced and nested appropriately.

Here's how I might approach the more general case:

def balanced(s, parens=("()",)):
'''
Example:
>>> balanced('aAAA(b[bb(c]c))')
True
>>> balanced('aAAA(b[bb(c]c))', parens=("()", "[]"))
False
'''
s = re.sub("[^%s]+" % re.escape("".join(parens)), "", s)
for i in range(len(s)/2):
for p in parens:
s = s.replace(p, "")
return not s

For short strings this is obviously slower than your 'iterative' function, 
but the run time mostly depends on the number of pairs of parentheses 
rather than the total length of the string, so for example it starts 
winning on a string with 2 pairs of parentheses about 75 characters long.
-- 
http://mail.python.org/mailman/listinfo/python-list


select lines in python

2009-07-14 Thread amrita
Dear all,

Can anyone tell me that suppose i have a file having content like:

_Atom_name
  _Atom_type
  _Chem_shift_value
  _Chem_shift_value_error
  _Chem_shift_ambiguity_code
 1 1   PHE   H H  8.49 0.02 1
 2 1   PHE   HAH  4.60 0.02 1
 3 1   PHE   CAC 57.83  0.3 1
 4 2   LEU   H H  8.23 0.02 1
 5 2   LEU   HAH  4.25 0.02 1
 6 2   LEU   HB2   H  1.54 0.02 1
 7 3   ASP   H H  8.10 0.02 1
 8 3   ASP   HAH  4.52 0.02 1
 9 3   ASP   HB2   H  2.65 0.02 1
stop


now what i want that instead of copying all the lines it will just write
the information about PHE and ASP then how i acn do that using python
programming.Kindly tell me the command for that.

Thanks,
Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

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


Re: select lines in python

2009-07-14 Thread David Gibb
try something like:

for line in open("filename").readlines():
if (re.search("PHE|ASP",line):
print line

On Tue, Jul 14, 2009 at 1:33 PM,  wrote:
> Dear all,
>
> Can anyone tell me that suppose i have a file having content like:
>
>    _Atom_name
>      _Atom_type
>      _Chem_shift_value
>      _Chem_shift_value_error
>      _Chem_shift_ambiguity_code
>     1     1   PHE       H     H      8.49     0.02     1
>     2     1   PHE       HA    H      4.60     0.02     1
>     3     1   PHE       CA    C     57.83      0.3     1
>     4     2   LEU       H     H      8.23     0.02     1
>     5     2   LEU       HA    H      4.25     0.02     1
>     6     2   LEU       HB2   H      1.54     0.02     1
>     7     3   ASP       H     H      8.10     0.02     1
>     8     3   ASP       HA    H      4.52     0.02     1
>     9     3   ASP       HB2   H      2.65     0.02     1
> stop
>
>
> now what i want that instead of copying all the lines it will just write
> the information about PHE and ASP then how i acn do that using python
> programming.Kindly tell me the command for that.
>
> Thanks,
> Amrita Kumari
> Research Fellow
> IISER Mohali
> Chandigarh
> INDIA
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread phonky

Thanks for all replies.

I need to practice much more pythonese
In fact I don't think to understand all
of your suggestions, so I'll need to
go through them and decide what approach I am going
to take.

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


Re: why did you choose the programming language(s)you currently use?

2009-07-14 Thread Mensanator
On Jul 14, 10:55 am, Deep_Feelings  wrote:
> So you have chosen programming language "x" so shall you tell us why
> you did so , and  what negatives or positives it has ?

language must have

- unlimited precision integers
- easy to program
- IDE not required
- reasonable speed
- math library needs to include number theoretic functions
  like GCD, LCM, Modular Inverse, etc.
- not fucking retarded like F#

That leaves Python (along with gympy, the Python wrapper for
the GMP library, which could be used with C or C++ if it weren't
for the ease of use issue) as the obvious choice.

As for negatives, the GMP library doesn't factor.

As for positives, you can call a factoring program from Python
and capture the output (and have it correct the bug in the factoring
program without having to fix the factoring program).
-- 
http://mail.python.org/mailman/listinfo/python-list


ImportError: No module named _functools

2009-07-14 Thread Tony Lay
I'm sooo close to getting this meld program runninghad to install
a lot of things in /usr/local to get to pygtk2 functional and I'm
trying to run the meld program and get...

RHEL4 server


Traceback (most recent call last):
  File "/usr/local/bin/meld", line 35, in 
import gettext
  File "/usr/local/lib/python2.6/gettext.py", line 49, in 
import locale, copy, os, re, struct, sys
  File "/usr/local/lib/python2.6/locale.py", line 15, in 
import functools
  File "/usr/local/lib/python2.6/functools.py", line 10, in 
from _functools import partial, reduce
ImportError: No module named _functools

This is with me building all of the dependencies as well as python
with
./configure --prefix=/usr/local --exec-prefix=/usr/local
make distclean
make
make -i install
ldconfig

export PYTHONHOME=/usr/local/lib/python2.6
export PYTHONPATH=/usr/local/lib/python2.6:/usr/local/lib/python2.6/
site-packages

I thought it might have been an err of the application, but I ran
python and received the same error:
[r...@orlstscts1 meld-1.0.0]# python
Python 2.6.2 (r262:71600, Jul 14 2009, 11:47:04)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/functools.py", line 10, in 
from _functools import partial, reduce
ImportError: No module named _functools

Kind of a python n00b, but the functools.py is there, it's in the
path...everything seems to be lined up right.

Problem is that the server this is on is stable (read older), and I am
to not touch the older software unless it's as a last resort.  For
this reason everything is in /usr/local and built from the ground up.

I'm hoping that there's some silly dependency I'm missing.  I've
installed the following:
atk-1.26.0
pkg-config-0.23
cairo-1.8.8
libglade-2.6.4
pycairo-1.8.6
fontconfig-2.7.0
libpng-1.2.37
pygobject-2.18.0
freetype-2.1.10
libxml2-2.7.3
pygtk-2.15.2
gettext-0.17
meld-1.0.0
pygtk-2.8.6
glade3-3.6.7
meld-1.1.5
Python-2.6.2
glib-2.20.4
glibc-2.9
meld-1.3.0 (no install)
tcl8.5.7
tk8.5.7
gtk+-2.16.4
pango-1.20.5
intltool-0.35.5
pixman-0.15.14

Took me a while to get by fontconfig/freetype junk because (usr/local/
lib/libfontconfig.so: undefined reference to `FT_Select_Size') but
that's a little OT.

If there are any recommendations of what to attack or further
information would help let me know!

Regards,

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


Re: Why not enforce four space indentations in version 3.x?

2009-07-14 Thread John Nagle

walterbyrd wrote:

I believe Guido himself has said that all indentions should be four
spaces - no tabs.

Since backward compatibility is being thrown away anyway, why not
enforce the four space rule?

At least that way, when I get python code from somebody else, I would
know what I am looking at, without having to do a hex dump, or
something.


   Python 3 enforces the rule that you can't mix tabs and spaces
for indentation in the same file.  That (finally) guarantees that
the indentation you see is what the Python parser sees.  That's
enough to prevent non-visible indentation errors.

   It also means that the Python parser no longer has to have
any concept of how many spaces equal a tab.  So the problem
is now essentially solved.

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


How to keep a function as a generator function when the yield operator is moved into its sub-functions??

2009-07-14 Thread weafon

Hi guys,

I have a question about the usage of yield. As shown in the below 
example, in general, if there is a code segment commonly used by two or 
more functions, we may isolate the segment into a function and then call 
it from other functions if necessary.


def func1():
   
   while(cond):
   .
   commoncode()
   ...


def func2():
   
   while(cond):
   .
   commoncode()
   ...

def commoncode()
   
   
   

However, if there is a 'yield' operation in the common code segment, the 
isolation causes that func1 and func2 become a non-generator function!! 
Although I can prevent such an isolation by just duplicating the segment 
in func1 and func2 to keep both of them being generator functions, the 
code may become ugly and hard to maintain particularly when coomoncode() 
is long.


The problem may be resolved if I can define the commoncode() as an 
inline function or marco. Unfortunately, inline and marco do not seems 
to be implemented in python. Thus, how can I isolate a common segment 
into a function when there are yield operations in the common segment?


Thanks,
Weafon





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


Re: select lines in python

2009-07-14 Thread Rhodri James

On Tue, 14 Jul 2009 18:48:06 +0100, David Gibb  wrote:

[Something top-posted, which I've shuffled down]


On Tue, Jul 14, 2009 at 1:33 PM,  wrote:

Dear all,

Can anyone tell me that suppose i have a file having content like:

   _Atom_name
     _Atom_type
     _Chem_shift_value
     _Chem_shift_value_error
     _Chem_shift_ambiguity_code
    1     1   PHE       H     H      8.49     0.02     1
    2     1   PHE       HA    H      4.60     0.02     1
    3     1   PHE       CA    C     57.83      0.3     1
    4     2   LEU       H     H      8.23     0.02     1
    5     2   LEU       HA    H      4.25     0.02     1
    6     2   LEU       HB2   H      1.54     0.02     1
    7     3   ASP       H     H      8.10     0.02     1
    8     3   ASP       HA    H      4.52     0.02     1
    9     3   ASP       HB2   H      2.65     0.02     1
stop


now what i want that instead of copying all the lines it will just write
the information about PHE and ASP then how i acn do that using python
programming.Kindly tell me the command for that.



try something like:

for line in open("filename").readlines():
if (re.search("PHE|ASP",line):
print line



The readlines() is unnecessary, and if your file is at all long you'd
be better off precompiling the regular expression.

import re

expr = re.compile("PHE|ASP")
with open("filename") as f:
for line in f:
if expr.search(line):
print line

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


Re: How to keep a function as a generator function when the yield operator is moved into its sub-functions??

2009-07-14 Thread Miles Kaufmann

On Jul 14, 2009, at 2:03 PM, weafon wrote:


Hi guys,

I have a question about the usage of yield. As shown in the below  
example, in general, if there is a code segment commonly used by two  
or more functions, we may isolate the segment into a function and  
then call it from other functions if necessary.


def func1():
  
  while(cond):
  .
  commoncode()
  ...


def func2():
  
  while(cond):
  .
  commoncode()
  ...

def commoncode()
  
  
  

However, if there is a 'yield' operation in the common code segment,  
the isolation causes that func1 and func2 become a non-generator  
function!! Although I can prevent such an isolation by just  
duplicating the segment in func1 and func2 to keep both of them  
being generator functions, the code may become ugly and hard to  
maintain particularly when coomoncode() is long.


The problem may be resolved if I can define the commoncode() as an  
inline function or marco. Unfortunately, inline and marco do not  
seems to be implemented in python. Thus, how can I isolate a common  
segment into a function when there are yield operations in the  
common segment?


def func1():
...
while cond:
...
for x in commoncode():
yield x
...

See also:
 - PEP 380: http://www.python.org/dev/peps/pep-0380/
 - Stackless: http://www.stackless.com/

-Miles

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


missing 'xor' Boolean operator

2009-07-14 Thread Dr. Phillip M. Feldman

Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
have an 'xor' operator as well.
-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24485116.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: why did you choose the programming language(s)you currently use?

2009-07-14 Thread Stefan Behnel
Deep_Feelings wrote:
> So you have chosen programming language "x" so shall you tell us why
> you did so , and  what negatives or positives it has ?

Java, pays a living.

*duck*

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


Re: missing 'xor' Boolean operator

2009-07-14 Thread Mark Dickinson
On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" 
wrote:
> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
> have an 'xor' operator as well.

Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
that it's sufficiently useful to justify adding a new keyword 'xor' to
the language;  I suspect that would be an uphill struggle. :)

I'll just note that:

(1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)

(2) 'and' and 'or' are special in that they have useful short-
circuiting behaviour; xor doesn't have this property (that is, you
always need to evaluate *both* operands to determine the result).

I'd also guess that 'xor' would be much less used than 'and' or 'or',
but maybe that's just a reflection of the sort of code that I tend to
write.

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


Re: select lines in python

2009-07-14 Thread amrita
Can i become more precise like instead of printing all lines for PHE and
ASP is it possible that for PHE python will print only those lines which
will have information about H and HA and for ASP it will print those lines
which will have information about HA and HB.

Thanks


> On Tue, 14 Jul 2009 18:48:06 +0100, David Gibb  wrote:
>
> [Something top-posted, which I've shuffled down]
>
>> On Tue, Jul 14, 2009 at 1:33 PM,  wrote:
>>> Dear all,
>>>
>>> Can anyone tell me that suppose i have a file having content like:
>>>
>>>    _Atom_name
>>>      _Atom_type
>>>      _Chem_shift_value
>>>      _Chem_shift_value_error
>>>      _Chem_shift_ambiguity_code
>>>     1     1   PHE       H     H      8.49     0.02    
>>> 1
>>>     2     1   PHE       HA    H      4.60     0.02    
>>> 1
>>>     3     1   PHE       CA    C     57.83      0.3    
>>> 1
>>>     4     2   LEU       H     H      8.23     0.02    
>>> 1
>>>     5     2   LEU       HA    H      4.25     0.02    
>>> 1
>>>     6     2   LEU       HB2   H      1.54     0.02    
>>> 1
>>>     7     3   ASP       H     H      8.10     0.02    
>>> 1
>>>     8     3   ASP       HA    H      4.52     0.02    
>>> 1
>>>     9     3   ASP       HB2   H      2.65     0.02    
>>> 1
>>> stop
>>>
>>>
>>> now what i want that instead of copying all the lines it will just
>>> write
>>> the information about PHE and ASP then how i acn do that using python
>>> programming.Kindly tell me the command for that.
>
>> try something like:
>>
>> for line in open("filename").readlines():
>> if (re.search("PHE|ASP",line):
>> print line
>>
>
> The readlines() is unnecessary, and if your file is at all long you'd
> be better off precompiling the regular expression.
>
> import re
>
> expr = re.compile("PHE|ASP")
> with open("filename") as f:
>  for line in f:
>  if expr.search(line):
>  print line
>
> --
> Rhodri James *-* Wildebeest Herder to the Masses
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

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


Re: select lines in python

2009-07-14 Thread Grant Edwards
On 2009-07-14, [email protected]  wrote:

> Can i become more precise like instead of printing all lines
> for PHE and ASP is it possible that for PHE python will print
> only those lines which will have information about H and HA
> and for ASP it will print those lines which will have
> information about HA and HB?

Yes.

-- 
Grant Edwards   grante Yow! I KAISER ROLL?!
  at   What good is a Kaiser Roll
   visi.comwithout a little COLE SLAW
   on the SIDE?
-- 
http://mail.python.org/mailman/listinfo/python-list


[email protected]

2009-07-14 Thread ~km
Hi,

I'm experiencing a strange behaviour of the Python prompt when using
the
four arrow keys ( not the VIM' nor Emacs' ones ;-) ). Instead of
getting
the previous and next command respectively I get ugly characters. See
it
yourself:
http://tinypic.com/view.php?pic=m78cgp&s=3

This is not directly Python-specific, but you feel quite handicapped
if
you must rewrite each command again... so my obvious question is:

How can I fix this? Please, let me know if you can tell me something.

Additional information:
I'm running Ubuntu Linux
I've tried the python prompt in several shell environments and got the
same issue in csh, dash... all negative.

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


bad behaviour in interactive Python prompt

2009-07-14 Thread ~km
Hi,

I'm experiencing a strange behaviour of the Python prompt when using
the
four arrow keys ( not the VIM' nor Emacs' ones ;-) ). Instead of
getting
the previous and next command respectively I get ugly characters. See
it
yourself:
http://tinypic.com/view.php?pic=m78cgp&s=3

This is not directly Python-specific, but you feel quite handicapped
if
you must rewrite each command again... so my obvious question is:

How can I fix this? Please, let me know if you can tell me something.

Additional information:
I'm running Ubuntu Linux
I've tried the python prompt in several shell environments and got the
same issue in csh, dash... all negative.

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


Re: select lines in python

2009-07-14 Thread David Gibb
I think what Grant is saying is that you should read the documentation
for the re module.

David

On Tue, Jul 14, 2009 at 3:12 PM, Grant Edwards wrote:
> On 2009-07-14, [email protected]  wrote:
>
>> Can i become more precise like instead of printing all lines
>> for PHE and ASP is it possible that for PHE python will print
>> only those lines which will have information about H and HA
>> and for ASP it will print those lines which will have
>> information about HA and HB?
>
> Yes.
>
> --
> Grant Edwards                   grante             Yow! I KAISER ROLL?!
>                                  at               What good is a Kaiser Roll
>                               visi.com            without a little COLE SLAW
>                                                   on the SIDE?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bad behaviour in interactive Python prompt

2009-07-14 Thread Mark Dickinson
On Jul 14, 8:20 pm, "~km"  wrote:
> I'm experiencing a strange behaviour of the Python prompt when using
> the
> four arrow keys ( not the VIM' nor Emacs' ones ;-) ). Instead of
> getting
> the previous and next command respectively I get ugly characters. See
> it
> yourself:http://tinypic.com/view.php?pic=m78cgp&s=3
>
> This is not directly Python-specific, but you feel quite handicapped
> if
> you must rewrite each command again... so my obvious question is:
>
> How can I fix this? Please, let me know if you can tell me something.
>
> Additional information:
> I'm running Ubuntu Linux
> I've tried the python prompt in several shell environments and got the
> same issue in csh, dash... all negative.

Where did your version of Python 2.6 come from?

If you built your copy of Python 2.6 from source, then the problem is
probably that either the readline library is missing, or (much more
likely) the include files for the readline library are missing.  Look
for a package called something like libreadline5-dev or readline-devel
and install it, and then try rebuilding Python.

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


Re: missing 'xor' Boolean operator

2009-07-14 Thread Chris Rebert
On Tue, Jul 14, 2009 at 11:47 AM, Mark Dickinson wrote:
> On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" 
> wrote:
>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
>> have an 'xor' operator as well.
>
> Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
> that it's sufficiently useful to justify adding a new keyword 'xor' to
> the language;  I suspect that would be an uphill struggle. :)
>
> I'll just note that:
>
> (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)

Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)

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


[email protected]

2009-07-14 Thread Chris Rebert
On Tue, Jul 14, 2009 at 12:15 PM, ~km wrote:
> Hi,
>
> I'm experiencing a strange behaviour of the Python prompt when using
> the
> four arrow keys ( not the VIM' nor Emacs' ones ;-) ). Instead of
> getting
> the previous and next command respectively I get ugly characters. See
> it
> yourself:
> http://tinypic.com/view.php?pic=m78cgp&s=3
>
> This is not directly Python-specific, but you feel quite handicapped
> if
> you must rewrite each command again... so my obvious question is:
>
> How can I fix this? Please, let me know if you can tell me something.

I would guess that your Python wasn't compiled with GNU readline support.
Do you get an error if you `import readline`?

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


Re: missing 'xor' Boolean operator

2009-07-14 Thread Mark Dickinson
On Jul 14, 8:43 pm, Chris Rebert  wrote:
> On Tue, Jul 14, 2009 at 11:47 AM, Mark Dickinson wrote:
> > (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)
>
> Using the xor bitwise operator is also an option:
> bool(x) ^ bool(y)

Good point.  For some reason I expected bitwise operations on bools to
return ints rather than bools.  Now I know better. :-)

Thanks,

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


Re: missing 'xor' Boolean operator

2009-07-14 Thread Dr. Phillip M. Feldman

!= does do what I want, except that it doesn't indicate to someone reading
the code that the operands are being treated as logicals.  (Readability is
supposed to be one of the major selling points of Python).  But, this is
probably good enough.

Here's a related issue: I would like to see an option for type checking on
operands of logical operators, so that attempting to apply a logical
operator to non-Boolean entities generates a warning message.  With operand
type checking, 'xor' and != would be different.


Mark Dickinson wrote:
> 
> On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" 
> wrote:
>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
>> to
>> have an 'xor' operator as well.
> 
> Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
> that it's sufficiently useful to justify adding a new keyword 'xor' to
> the language;  I suspect that would be an uphill struggle. :)
> 
> I'll just note that:
> 
> (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)
> 
> (2) 'and' and 'or' are special in that they have useful short-
> circuiting behaviour; xor doesn't have this property (that is, you
> always need to evaluate *both* operands to determine the result).
> 
> I'd also guess that 'xor' would be much less used than 'and' or 'or',
> but maybe that's just a reflection of the sort of code that I tend to
> write.
> 
> --
> Mark
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24486661.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: one-time factory in python for an experienced java guy

2009-07-14 Thread Jonathan Gardner
On Jul 14, 7:03 am, phonky  wrote:
>
> Now, I do not know yet how the account number scheme looks like.

Exactly. The data store knows a lot more than the client (your
program) will ever know.

The correct answer is to do nothing. Use your data store to generate
the IDs for you. The implementations discussed here will not generate
unique IDs across invocations, but the data store will persist the
sequence for you appropriately.

The more correct answer is to abstract away the client to your data
store as well. See SQLAlchemy.

If you're writing a data store, you're doing it wrong. See PostgreSQL,
MySQL, or any other data store out there that are perfectly fine for
development and production use.

I like to use UUIDs for the IDs. Others like big ints that are a
sequence. I've seen people use encrypted big ints, basically random
strings that aren't really random. In the end, you only have to change
the code that talks to the data store, and the rest of your program
only cares about the equality of the id.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Chris Rebert
> Mark Dickinson wrote:
>>
>> On Jul 14, 7:25 pm, "Dr. Phillip M. Feldman" 
>> wrote:
>>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
>>> to
>>> have an 'xor' operator as well.
>>
>> Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
>> that it's sufficiently useful to justify adding a new keyword 'xor' to
>> the language;  I suspect that would be an uphill struggle. :)
>>
>> I'll just note that:
>>
>> (1) It's easy to emulate xor:  'x xor y' <-> bool(x) != bool(y)
>>
>> (2) 'and' and 'or' are special in that they have useful short-
>> circuiting behaviour; xor doesn't have this property (that is, you
>> always need to evaluate *both* operands to determine the result).
>>
>> I'd also guess that 'xor' would be much less used than 'and' or 'or',
>> but maybe that's just a reflection of the sort of code that I tend to
>> write.
On Tue, Jul 14, 2009 at 12:56 PM, Dr. Phillip M.
Feldman wrote:

> Here's a related issue: I would like to see an option for type checking on
> operands of logical operators, so that attempting to apply a logical
> operator to non-Boolean entities generates a warning message.  With operand
> type checking, 'xor' and != would be different.

That's probably not gonna happen. Python is dynamically and duck
typed, and has a sweet coercion system (__bool__ or __nonzero__
depending on your version) to coerce non-booleans to booleans in a
sensible and useful way. So, it's not gonna change any time soon.

Some illustrative examples:
>>> #empty containers considered false
>>> bool([] or {} or set() or "")
>>> False
>>> #zero and null considered false
>>> bool(0 or None)
>>> False
>>> #anything else is, by default, true
>>> bool(object())
>>> True

And like I said, a class can override a special method to provide
whatever boolean semantics are desired. It's surprisingly handy.

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


Re: explode()

2009-07-14 Thread Jonathan Gardner
On Jul 14, 6:56 am, Fred Atkinson  wrote:
>
> Agreed, it doesn't.  But if my hosting provider won't change it, I'm
> stuck with it.  
>

Nowadays you can find hosts that allow you to run FastCGI scripts in
any language for dirt cheap. (Hostmonster for instance.) If your host
doesn't allow it, it's time to upgrade.

Any hosting service that supports Ruby on Rails supports Python
through the exact same mechanism.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >