Re: C interpreter in Lisp/scheme/python

2010-07-14 Thread Ian Kelly
On Wed, Jul 14, 2010 at 11:17 PM, bolega  wrote:
> This makes some sense. He replied on the newsgroup in a lengthy post
> that there are sufficient resources out there giving hint that no one
> need help me out.

I have no record of such a post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C interpreter in Lisp/scheme/python

2010-07-14 Thread geremy condra
On Wed, Jul 14, 2010 at 10:17 PM, bolega  wrote:
> On Jul 13, 11:18 pm, geremy condra  wrote:
>> On Tue, Jul 13, 2010 at 11:01 PM, bolega  wrote:
>> > On Jun 20, 9:31 pm, Richard Fateman  wrote:
>> >> Define Macro wrote:
>> >> > On Jun 13, 7:07 pm, bolega  wrote:
>> >> >> I am trying to compare LISP/Scheme/Python for their expressiveness.
>>
>> >> >> For this, I propose a vanilla C interpreter. I have seen a book which
>> >> >> writes C interpreter in C.
>>
>> >> >> The criteria would be the small size and high readability of the code.
>>
>> >> >> Are there already answers anywhere ?
>>
>> >> Sure.  Lots of texts on compilers provide exercises which, in one way or
>> >> another suggest how to write an interpreter and perhaps a compiler too
>> >> for some language.  Anyone taking a course on compilers is likely to
>> >> have followed such exercises in order to pass the course.  Some
>> >> instructors are enlightened enough to allow students to pick the
>> >> implementation language.
>>
>> >> Ask any such instructor.
>>
>> > Beware, he does not tell the readers the financial details. This is
>> > what he wrote to me by email.
>>
>> > 
>> > I would be willing to meet with you here in Berkeley to educate you on
>> > these matters at a consulting rate of  $850 per hour, with a minimum
>> > of 8 hours.
>>
>> > RJF
>> > 
>>
>> He's Berkeley's former CS chair and was implementing lisp before
>> common lisp was a twinkle in anybody's eye. His time is valuable.
>>
>> Geremy Condra
>
> This makes some sense. He replied on the newsgroup in a lengthy post
> that there are sufficient resources out there giving hint that no one
> need help me out.

No one does. Your problem is yours to solve.

> Then I was called "lazy" in one email and tersely
> given JUST the last name of an author who has many books each many
> 100s pages, when I asked for a relevant book, as if i am a scholar in
> the field, although he did spend lots of words on irrelevant and
> unbeneficial things which diminished my enthusiasm.

Yes, you've failed to take advantage of the resources which have been
made available to you, preferring to have other people solve your
problem. Sounds like a pretty good working definition of laziness.

> Now, I find out
> from you that he has/had a business concern or interest in a company
> that is writing/wrote lisp interpreter in C. Correct me if I am making
> an error.

You're making an error. Given that there are probably only a handful
of people on earth more qualified to teach you anything you'd want to
know about this I'd say he's made you an exceptional offer. Expect no
better help elsewhere.

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


Re: C interpreter in Lisp/scheme/python

2010-07-14 Thread bolega
On Jul 13, 11:35 pm, Paul Rubin  wrote:
> bolega  writes:
> > I am trying to compare LISP/Scheme/Python for their expressiveness...
> > Are there already answers anywhere ?
> > How would a gury approach such a project ?
>
> These two articles
>
>    http://page.mi.fu-berlin.de/~prechelt/Biblio/jccpprt_computer2000.pdf
>    http://www.haskell.org/papers/NSWC/jfp.ps
>
> about language comparisons (Python is in the first but not the second)
> might be of interest.
>
> If you want to know how to implement C, there is a pretty good book by
> Hanson and Fraser about LCC, called "A Retargetable C Compiler".
> Basically a code walkthrough of a small C compiler written in C.

I have decided to limit my goal to tyni LISP interpreter in C because
its a smaller and simpler language.

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


Re: C interpreter in Lisp/scheme/python

2010-07-14 Thread bolega
On Jul 13, 11:18 pm, geremy condra  wrote:
> On Tue, Jul 13, 2010 at 11:01 PM, bolega  wrote:
> > On Jun 20, 9:31 pm, Richard Fateman  wrote:
> >> Define Macro wrote:
> >> > On Jun 13, 7:07 pm, bolega  wrote:
> >> >> I am trying to compare LISP/Scheme/Python for their expressiveness.
>
> >> >> For this, I propose a vanilla C interpreter. I have seen a book which
> >> >> writes C interpreter in C.
>
> >> >> The criteria would be the small size and high readability of the code.
>
> >> >> Are there already answers anywhere ?
>
> >> Sure.  Lots of texts on compilers provide exercises which, in one way or
> >> another suggest how to write an interpreter and perhaps a compiler too
> >> for some language.  Anyone taking a course on compilers is likely to
> >> have followed such exercises in order to pass the course.  Some
> >> instructors are enlightened enough to allow students to pick the
> >> implementation language.
>
> >> Ask any such instructor.
>
> > Beware, he does not tell the readers the financial details. This is
> > what he wrote to me by email.
>
> > 
> > I would be willing to meet with you here in Berkeley to educate you on
> > these matters at a consulting rate of  $850 per hour, with a minimum
> > of 8 hours.
>
> > RJF
> > 
>
> He's Berkeley's former CS chair and was implementing lisp before
> common lisp was a twinkle in anybody's eye. His time is valuable.
>
> Geremy Condra

This makes some sense. He replied on the newsgroup in a lengthy post
that there are sufficient resources out there giving hint that no one
need help me out. Then I was called "lazy" in one email and tersely
given JUST the last name of an author who has many books each many
100s pages, when I asked for a relevant book, as if i am a scholar in
the field, although he did spend lots of words on irrelevant and
unbeneficial things which diminished my enthusiasm. Now, I find out
from you that he has/had a business concern or interest in a company
that is writing/wrote lisp interpreter in C. Correct me if I am making
an error. I dont want to think deprecatingly of any good soul but this
is what i experienced.

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


Re: M2Crypto-0.20.2, SWIG-2.0.0, and OpenSSL-1.0.0a build problem

2010-07-14 Thread Adam Mercer
Anyone have any ideas about this?

Cheers

Adam

On Tue, Jul 13, 2010 at 16:18, Adam Mercer  wrote:
> Hi
>
> I'm trying to build M2Crypto on Mac OS X 10.6.4 against python2.5
> (python2.6 fails in the same way), with SWIG 2.0.0 and OpenSSL 1.0.0a
> and it is failing with the following:
>
> 105     :info:build swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c
> 106     :info:build swig -python
> -I/opt/local/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5
> -I/opt/local/include -includeall -o SWIG/_m2crypto_wrap.c
> SWIG/_m2crypto.i
> 107     :info:build SWIG/_bio.i:64: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 108     :info:build SWIG/_rand.i:19: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 109     :info:build SWIG/_evp.i:156: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 110     :info:build SWIG/_dh.i:36: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 111     :info:build SWIG/_rsa.i:43: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 112     :info:build SWIG/_dsa.i:31: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 113     :info:build SWIG/_ssl.i:207: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 114     :info:build SWIG/_x509.i:313: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 115     :info:build SWIG/_pkcs7.i:42: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 116     :info:build SWIG/_pkcs7.i:42: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 117     :info:build SWIG/_util.i:9: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 118     :info:build SWIG/_ec.i:111: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 119     :info:build SWIG/_engine.i:162: Warning 454: Setting a
> pointer/reference variable may leak memory.
> 120     :info:build creating build/temp.macosx-10.6-x86_64-2.5
> 121     :info:build creating build/temp.macosx-10.6-x86_64-2.5/SWIG
> 122     :info:build /usr/bin/gcc-4.2 -fno-strict-aliasing -mno-fused-madd
> -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
> -I/opt/local/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5
> -I/opt/local/include
> -I/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25-m2crypto/work/M2Crypto-0.20.2/SWIG
> -c SWIG/_m2crypto_wrap.c -o
> build/temp.macosx-10.6-x86_64-2.5/SWIG/_m2crypto_wrap.o -DTHREADING
> 123     :info:build SWIG/_m2crypto_wrap.c: In function 'rand_pseudo_bytes':
> 124     :info:build SWIG/_m2crypto_wrap.c:3899: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 125     :info:build SWIG/_m2crypto_wrap.c: In function 
> 'pkcs5_pbkdf2_hmac_sha1':
> 126     :info:build SWIG/_m2crypto_wrap.c:3973: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 127     :info:build SWIG/_m2crypto_wrap.c: In function 'bytes_to_key':
> 128     :info:build SWIG/_m2crypto_wrap.c:4132: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 129     :info:build SWIG/_m2crypto_wrap.c: In function 'sign_final':
> 130     :info:build SWIG/_m2crypto_wrap.c:4228: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 131     :info:build SWIG/_m2crypto_wrap.c: In function 'pkey_as_der':
> 132     :info:build SWIG/_m2crypto_wrap.c:4300: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 133     :info:build SWIG/_m2crypto_wrap.c: In function 'pkey_get_modulus':
> 134     :info:build SWIG/_m2crypto_wrap.c:4333: warning: value computed is 
> not used
> 135     :info:build SWIG/_m2crypto_wrap.c:4358: warning: value computed is 
> not used
> 136     :info:build SWIG/_m2crypto_wrap.c: In function 'AES_crypt':
> 137     :info:build SWIG/_m2crypto_wrap.c:: warning: pointer targets
> in passing argument 1 of 'PyString_FromStringAndSize' differ in
> signedness
> 138     :info:build SWIG/_m2crypto_wrap.c: At top level:
> 139     :info:build SWIG/_m2crypto_wrap.c:5846: error: expected '=', ',',
> ';', 'asm' or '__attribute__' before '*' token
> 140     :info:build SWIG/_m2crypto_wrap.c:5850: error: expected ')' before 
> '*' token
> 141     :info:build SWIG/_m2crypto_wrap.c:5854: error: expected ')' before 
> '*' token
> 142     :info:build SWIG/_m2crypto_wrap.c:5858: error: expected '=', ',',
> ';', 'asm' or '__attribute__' before '*' token
> 143     :info:build SWIG/_m2crypto_wrap.c:5862: error: expected ')' before 
> '*' token
> 144     :info:build SWIG/_m2crypto_wrap.c:5866: error: expected ')' before 
> '*' token
> 145     :info:build SWIG/_m2crypto_wrap.c: In function 'i2d_x509':
> 146     :info:build SWIG/_m2crypto

Re: Issue with logging.config

2010-07-14 Thread Joe Hughes
Hi Vinay,

I think I figured out what you are talking about after reading RFC 
5424.  I think this means that this code

syslog.info("Status - " + mcu_dict[pinged.ip] + " is " + status[pinged.status])

needs to become something like this

BOM = 0xEFBBBF
msg = str(BOM) + "Status - " + mcu_dict[pinged.ip] + " is " + 
status[pinged.status]
syslog.info(msg)

This would add the BOM to the message that RFC 5424 requires.  Or did I totally 
misread it?

Thanks,
Joe

On Jul 14, 2010, at 8:20 PM, Vinay Sajip wrote:

> On Jul 14, 7:08 pm, Joe Hughes  wrote:
>> This is why I did what I did, because I couldn't figure it out either.  I 
>> did find issue 5421 at python.org which is where I got the idea for the code 
>> change.
> 
> Perhaps you should read the messages for issue 7077, linked to by
> Peter above. You'll see that according to RFC 5424, syslog UDP
> messages should be encoded in UTF-8 with a BOM, not ASCII. Revisions
> r75586 and later of the Python repository implement the correct fix
> for the problem.
> 
> My suggestion (in the blog post I linked to) would apply to socket
> applications other than syslog.
> 
> Regards,
> 
> Vinay Sajip
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Identify the Color of an Image

2010-07-14 Thread Gary Herron

On 07/14/2010 05:37 AM, Monyl wrote:

Hi,

1. How can I find the color of  an image present the webpage?

2. How to identify the font type of the selected text present in the
content of the web page

It would be much helpfull, if anyone responds to it ASAP

Thanks
Mohmyda
   




Please be clearer about what you want.

1. An image does not "have" a color, although each pixel in an image 
does have a color.


2.  Text in a web page does not (necessarily)  have a font, although the 
display engine will use a font of its choice to render text.  And my 
browser will probably use a different font than yours.



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


Re: Easy questions from a python beginner

2010-07-14 Thread r
On Jul 14, 1:24 pm, Grant Edwards  wrote:

> As of a few minutes ago, this thread had 48 postings on my news
> server.
>
> To paraphrase somebody famous:
>
>     There are no such things as easy questions.  There are, however,
>     easy answers.  And they're wrong.        

Ha! This is the very reason i always steer clear of any post with the
words "easy", "simple", or "BUSTARDS" in the title. ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting numeric litterals

2010-07-14 Thread candide

MRAB a écrit :


want to split them over several lines. It is somewhat unusual to have a
_numeric_ literal that's very very long!



I agree. But consider RSA-155 for instance ... ;)



For an integer literal you could use a string literal and convert it to
an integer:

 >>> int("1000\
000\
000")
10
 >>>


OK.

In C, the following code is allowed :

int x=1000\
000\
000;

but not very usefull for sure !
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting numeric litterals

2010-07-14 Thread MRAB

candide wrote:
The escape sequence \ENTER allows to split a string over 2 consecutive 
lines. On the other hand, it seems impossible to split a numeric 
litteral across multiple lines, compare :


 >>> "1000\
... 000\
... 000"
'10'
 >>> 1000\
... 000\
  File "", line 2
000\
  ^
SyntaxError: invalid syntax
 >>>


Is this the general behaviour ? So, how do you edit code containing a 
very very long numeric constant ?


Normally it's only string literals that could be so long that you might
want to split them over several lines. It is somewhat unusual to have a
_numeric_ literal that's very very long!

For an integer literal you could use a string literal and convert it to
an integer:

>>> int("1000\
000\
000")
10
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting numeric litterals

2010-07-14 Thread Steven D'Aprano
On Thu, 15 Jul 2010 03:30:24 +0200, candide wrote:

> The escape sequence \ENTER allows to split a string over 2 consecutive
> lines. On the other hand, it seems impossible to split a numeric
> litteral across multiple lines
[...]
> Is this the general behaviour ? 

Yes. You can't put any whitespace in the middle of a numeric literal:


>>> n = 4 2
  File "", line 1
n = 4 2
  ^
SyntaxError: invalid syntax



> So, how do you edit code containing a very very long numeric constant ?



s = (
"1234567890123456789012345678901234567890"
"1234567890123456789012345678901234567890"
"1234567890123456789012345678901234567890"
"1234567890123456789012345678901234567890"
"1234567890123456789012345678901234567890"
)
assert len(s) == 200
n = int(s)



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


Splitting numeric litterals

2010-07-14 Thread candide
The escape sequence \ENTER allows to split a string over 2 consecutive 
lines. On the other hand, it seems impossible to split a numeric 
litteral across multiple lines, compare :


>>> "1000\
... 000\
... 000"
'10'
>>> 1000\ 


... 000\
  File "", line 2 


000\
  ^ 


SyntaxError: invalid syntax
>>>


Is this the general behaviour ? So, how do you edit code containing a 
very very long numeric constant ?

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


Re: Issue with logging.config

2010-07-14 Thread Vinay Sajip
On Jul 14, 7:08 pm, Joe Hughes  wrote:
> This is why I did what I did, because I couldn't figure it out either.  I did 
> find issue 5421 at python.org which is where I got the idea for the code 
> change.

Perhaps you should read the messages for issue 7077, linked to by
Peter above. You'll see that according to RFC 5424, syslog UDP
messages should be encoded in UTF-8 with a BOM, not ASCII. Revisions
r75586 and later of the Python repository implement the correct fix
for the problem.

My suggestion (in the blog post I linked to) would apply to socket
applications other than syslog.

Regards,

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


Re: Please Help

2010-07-14 Thread Gary Herron

On 07/14/2010 01:51 PM, Hayathms wrote:

PLease anyone help me ,,

program not running


from tkinter import ttk
from tkinter import *

class Hami(ttk.Frame):
def __init__(self,master=None):
ttk.Frame.__init__(self,master,borderwidth=5)
self.grid(column=0,row=0,sticky=('W,E,N,S'),padx=5,pady=5)


class Honey(ttk.Label):
def __init__(self,master=None,te='Honey'):
ttk.Label.__init__(master,text=te)
self.grid(column=0,row=0)


root=Tk()
root.title('Employee')
root.option_add('*tearOff',FALSE)
sam=Hami(root)
harmain=Honey(master=sam)
root.mainloop()


Error is  >


Traceback (most recent call last):
  File "C:/Python31/hayathhh.py", line 20, in 
harmain=Honey(master=sam)
  File "C:/Python31/hayathhh.py", line 13, in __init__
self.grid(column=0,row=0)
  File "C:\Python31\lib\tkinter\__init__.py", line 1843, in grid_configure
self.tk.call(
AttributeError: 'Honey' object has no attribute 'tk'
>>>



Here is *one* clear problem.  Others may exist.

Since Honey is derived from ttk.Label, Honey's constructor must call 
Label's constructor, (which you do), *however* when called as 
ttk.Label.__init__, you must provide it with the 'self' parameter.


class Honey(ttk.Label):
def __init__(self,master=None,te='Honey'):
ttk.Label.__init__(*self*,master,text=te)# self parameter 
added here

self.grid(column=0,row=0)






--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: floatref

2010-07-14 Thread Tino Wildenhain

Am 13.07.2010 19:26, schrieb Roald de Vries:
> Hi all,
>
> I have two objects that should both be able to alter a shared float. 
> So i need something like a mutable float object, or a float reference 
> object. Does anybody know if something like that exists? I know it's 
> not hard to build, but I have a feeling that there should be a

> standard solution to it.

Nice question to reflect our understanding of the basics of this language.

From what I know, we have the terms:

- reference
- name

(pointer is not really used beside from indices into lists or such)

I see it this way: you have named and unnamed references to objects. 
This means you
can bind any number of names to an object as well as reference the 
object in a list, tupe or set:


>>> (1,2,3) # unnamed references to int objects 1,2 and 3

>>> a=(1,2,3)[1]  # binds a to tuple element #1 (int 2 object)

>>> b=a # now a and b are bound to the same int 2 object

So back to your question:

>>> a=b=1.0 # binds the names a and b to the same float object 1.0

>>> a,b
(1.0, 1.0)

now, there is no way to alter the float object since it is immutable (as 
there are str, unicode, int, long, tuple...)


>>> a+=0.5
>>> a,b
(1.5, 1.0)

now you see even the "in place" addition creates a new object and
binds the name to it.

What you'd need to do would probably wrapping the float value into a
class where you can simulate a mutable float by providing a constant
name or reference for it within the class.

For example:

>>> a=b=[1.0]
>>> a[0]+=0.5
>>> a,b
([1.5], [1.5])

HTH
Tino




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


Re: Getting started with python on macintosh snow leopard with mysql - need help

2010-07-14 Thread Ned Deily
In article 
,
 Benjamin Kaplan  wrote:

> On Sun, Jul 11, 2010 at 1:18 PM, dk  wrote:
[...]
> > when i try to compile mysql-python-1.2.3 i get the following error
> > returned from python setup.py build -
> >
> > building '_mysql' extension
> > gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing
> > -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'final',0) -
> > D__version__=1.2.3 -I/usr/local/mysql/include -I/Library/Frameworks/
> > Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/
> > temp.macosx-10.3-fat-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -
> > D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -
> > DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL
> > In file included from /Library/Frameworks/Python.framework/Versions/
> > 2.6/include/python2.6/unicodeobject.h:4,
> >                 from /Library/Frameworks/Python.framework/Versions/
> > 2.6/include/python2.6/Python.h:85,
> >                 from pymemcompat.h:10,
> >                 from _mysql.c:29:
> > /Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h:4:25: error:
> > stdarg.h: No such file or directory
> > In file included from _mysql.c:36:
> > /usr/local/mysql/include/my_config.h:1053:1: warning: "HAVE_WCSCOLL"
> > redefined
> > In file included from /Library/Frameworks/Python.framework/Versions/
> > 2.6/include/python2.6/Python.h:8,
> >                 from pymemcompat.h:10,
> >                 from _mysql.c:29:
> > /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/
> > pyconfig.h:808:1: warning: this is the location of the previous
> > definition
> > error: command 'gcc-4.0' failed with exit status 1
> > --
> 
> Strange. Seems that the package is trying to use gcc-4.0 and the
> MacOSX10.4 SDK. The default version of gcc on Snow Leopard is 4.2, and
> XCode only comes with the SDKs for the previous two versions of OS X.

Not strange at all.  The python.org Python 2.6 (which is installed to 
/Library/Frameworks/Python.framework) is deliberately built to be 
compatible with OS X 10.3.9 through 10.6 and, as such, requires gcc-4.0 
and the 10.4u SDK.  The latter is included in the 10.6 Xcode 
distribution as a separate package but is not installed by default; to 
build a Python C extension module for that Python, you need to go back 
to the Xcode installer for Snow Leopard (or download a new one from 
Apple) and do a custom installation of that SDK.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Check if a command is valid

2010-07-14 Thread Grant Edwards
On 2010-07-14, Steven W. Orr  wrote:
> On 07/12/10 21:29, quoth Kenny Meyer:
>
>> I have to figure out if a string is callable on a Linux system. I'm
>> actually doing this:
>> 
>> def is_valid_command(command):
>> retcode = 100 # initialize
>> if command:
>> retcode = subprocess.call(command, shell=True)
>> if retcode is 0:
>> print "Valid command."
>> else:
>> print "Looks not so good..."
>> 
>> is_valid_command("ls")
>> 
>> Never mind the code, because this is not the original. The side
>> effect of subprocess.call() is that it *actually* executes it, but I
>> just need the return code. What are better ways of doing this?
>
> Luke! Use the force!
>
> #! /usr/bin/python
>
> import os
> def is_valid_command(command):
> looking_good = False
> for ii in os.environ['PATH'].split(':'):
> if os.access(ii + '/' + command, os.X_OK):
> looking_good = True
> break
> print ["Looks not so good...", "Valid command."][looking_good]
>
> is_valid_command('python')
> is_valid_command('pythoon')

Just to be clear, that's not the same as the OP's code in two
respects:

 1) It doesn't handle shell builtins or aliases.

 2) It determines not whether a command is valid (returns 0), but
whether a command exists as an executable.  "Valid" is a rather
small subset of "exists".

Of course the OP didn't explain what he meant by "callable", so all we
have to go on is his posted code.
   
> This way you don't start up any subprocesses and you are actually
> doing what the shell would do for you.
>
> THE ONLY DIFFERENCE is that a persistent bash would hash all of the
> contents of what lives in PATH and so might have a slight shot of
> being faster under somewhat obscure conditions.

No, there are other differences.  See above.

> I would strongly encourage you to not execute an arbitrary string to
> see if it returns a pretty return code.
>
> is_valid_command('{cd /; rm -rf /}')
>
> Warning:

> * It only checks if the command exists in PATH and is executable TO
>   YOU:

Which is different than determining whether a command (including
arguments) is valid (callable and returns 0).  However, running a
command to determine if it's valid is going to cause problems sooner
or later due to side-effects of that command.

For example, the first time you the command "rm /path/to/a/file" it
may be valid, but the second time it won't be.

> * Do not make fun of is_valid_command. It will get angry.

And don't taunt happy fun ball!

> * You might also want to beef it up a la
> pp = ii + '/' + command
> if os.access(pp, (os.X_OK) and not os.stat.isdir(p)):
> so you are checking executable files and not directories etc...
> * More warnings can be amplified upon over pitchers of beer.


-- 
Grant Edwards   grant.b.edwardsYow! My mind is making
  at   ashtrays in Dayton ...
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Please Help

2010-07-14 Thread Hayathms
PLease anyone help me ,,

program not running


from tkinter import ttk
from tkinter import *

class Hami(ttk.Frame):
def __init__(self,master=None):
ttk.Frame.__init__(self,master,borderwidth=5)
self.grid(column=0,row=0,sticky=('W,E,N,S'),padx=5,pady=5)


class Honey(ttk.Label):
def __init__(self,master=None,te='Honey'):
ttk.Label.__init__(master,text=te)
self.grid(column=0,row=0)


root=Tk()
root.title('Employee')
root.option_add('*tearOff',FALSE)
sam=Hami(root)
harmain=Honey(master=sam)
root.mainloop()


Error is  >


Traceback (most recent call last):
  File "C:/Python31/hayathhh.py", line 20, in 
harmain=Honey(master=sam)
  File "C:/Python31/hayathhh.py", line 13, in __init__
self.grid(column=0,row=0)
  File "C:\Python31\lib\tkinter\__init__.py", line 1843, in grid_configure
self.tk.call(
AttributeError: 'Honey' object has no attribute 'tk'
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-14 Thread lkcl
On Jul 11, 10:39 pm, "Martin P. Hellwig" 
wrote:
> On 07/11/10 04:59, Luke Kenneth Casson Leighton wrote:> source at:
> >http://github.com/lkcl/grailbrowser
>
> > $ python grail.py (note the lack of "python1.5" or "python2.4")
>
> > conversion of the 80 or so regex's to re has been carried out.
> > entirely successfully or not is a matter yet to be determined.  always
> > a hoot to try browsinghttp://www.bbc.co.ukorhttp://www.youtube.com
> > with a browser from 11+ years ago, it still cannot be resisted as
> > grail is the only working graphical web browser in the world written
> > in pure python [pybrowser is still in development, stalled].
>
> > l.
>
> Congrats!
> Are you planning to take over the world with grail and pyjs? :-)

 mwahaahhah basically, yes.  i'm fed up with the mozilla foundation,
who have trashed python-xpcom _just_ at the point where i demonstrated
its usefulness: the only reason things still work across linux
distributions is due to inertia as the distros are still offering
xulrunner-1.9.1, and i'm definitely fed up with the webkit developers,
one in particular, whose treatment of and attitude to the work that i
did to get python bindings to the DOM of webkit was beyond atrocious.

 so, python-based web browser it is, implement the W3C DOM API with
it.  hack it about, combine paul bonser's pybrowser back-end (which
was where paul did most of the work, and stalled on the front-end),
job done, one compliant python browser supporting W3C TR1,2 and 3 and
if we're reaaallly lucky i maybe add some HTML5 features too.

 just don't expect it to be quick!

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-14 Thread lkcl
On Jul 11, 5:44 am, rantingrick  wrote:
> On Jul 10, 10:59 pm, Luke Kenneth Casson Leighton
>
>  wrote:
> > source at:http://github.com/lkcl/grailbrowser
>
> > $ python grail.py (note the lack of "python1.5" or "python2.4")
>
> > conversion of the 80 or so regex's to re has been carried out.
> > entirely successfully or not is a matter yet to be determined.  always
> > a hoot to try browsinghttp://www.bbc.co.ukorhttp://www.youtube.com
> > with a browser from 11+ years ago, it still cannot be resisted as
> > grail is the only working graphical web browser in the world written
> > in pure python [pybrowser is still in development, stalled].
>
> > l.
>
> Congratulations on this effort Luke. However you know what project i
> would really like to see the community get around? ...dramatic pause
> here... a cross platform Python file browser!

 weeelll... you _could_ always just use grailbrowser :)  it does still
support file:// so it lists directories, shows text files and
downloads anything it doesn't understand.

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


Re: Check if a command is valid

2010-07-14 Thread Steven W. Orr
On 07/12/10 21:29, quoth Kenny Meyer:
> Hello,
> 
> I have to figure out if a string is callable on a Linux system. I'm
> actually doing this:
> 
> def is_valid_command(command):
> retcode = 100 # initialize
> if command:
> retcode = subprocess.call(command, shell=True)
> if retcode is 0:
> print "Valid command."
> else:
> print "Looks not so good..."
> 
> is_valid_command("ls")
> 
> Never mind the code, because this is not the original.
> The side effect of subprocess.call() is that it *actually* executes
> it, but I just need the return code. What are better ways of doing
> this?

Luke! Use the force!

#! /usr/bin/python

import os
def is_valid_command(command):
looking_good = False
for ii in os.environ['PATH'].split(':'):
if os.access(ii + '/' + command, os.X_OK):
looking_good = True
break
print ["Looks not so good...", "Valid command."][looking_good]

is_valid_command('python')
is_valid_command('pythoon')

This way you don't start up any subprocesses and you are actually doing what
the shell would do for you.

THE ONLY DIFFERENCE is that a persistent bash would hash all of the contents
of what lives in PATH and so might have a slight shot of being faster under
somewhat obscure conditions.

I would strongly encourage you to not execute an arbitrary string to see if it
returns a pretty return code.

is_valid_command('{cd /; rm -rf /}')

Warning:
* It only checks if the command exists in PATH and is executable TO YOU:
* Do not make fun of is_valid_command. It will get angry.
* You might also want to beef it up a la
pp = ii + '/' + command
if os.access(pp, (os.X_OK) and not os.stat.isdir(p)):
so you are checking executable files and not directories etc...
* More warnings can be amplified upon over pitchers of beer.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: Is Python portable/Can I install it on an USB Stick?

2010-07-14 Thread Christian Heimes
> Is Python portable?
> 
> Can I install it on an USB Stick?
> 
> Or is Python installing (at least on WinXP) services or register some DLLs or 
> write something into Registry?

Yes, a single user installation of Python is portable. An installation
for every user is not portable since it installs some DLLs in system32.
Some features and extensions are not portable, e.g. COM with pywin32
because they require registered DLLs.

Christian

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


Re: Is Python portable/Can I install it on an USB Stick?

2010-07-14 Thread Philip Semanchuk


On Jul 14, 2010, at 3:28 PM, Thomas Tundor wrote:


Is Python portable?

Can I install it on an USB Stick?

Or is Python installing (at least on WinXP) services or register  
some DLLs or

write something into Registry?



http://www.portablepython.com/
--
http://mail.python.org/mailman/listinfo/python-list


Is Python portable/Can I install it on an USB Stick?

2010-07-14 Thread Thomas Tundor
Is Python portable?

Can I install it on an USB Stick?

Or is Python installing (at least on WinXP) services or register some DLLs or 
write something into Registry?

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


Re: adodb.NewADOConnection('postgres') returns None

2010-07-14 Thread Mladen Gogala
On Wed, 14 Jul 2010 05:14:08 -0700, micayael wrote:

> Thanks Thomas.
> :-( then adodb today dosn't work with postgres (at least on ubuntu)
> right?

No, ADOdb doesn't work with the newer versions of Postgres. ADOdb doesn't 
work with Psycopg2 and the guy who maintains it did not reply to my 
email. That is unfortunate because ADOdb is my favorite PHP class 
library. It seems, though, that the Python version is not nearly as well 
maintained as the PHP one.




-- 
http://mgogala.byethost5.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adodb.NewADOConnection('postgres') returns None

2010-07-14 Thread Mladen Gogala
On Wed, 14 Jul 2010 20:04:59 +0200, Thomas Jollans wrote:


> It certainly looks that way. It may be possible to install an old
> psycopg module by hand - I'd expect that to work as well.

Not on Ubuntu 9.10:


checking PostgreSQL type catalog... /usr/include/postgresql/catalog/
pg_type.h
checking for mxDateTime.h... configure: error: can't build without mx 
headers
mgog...@nycwxp2622:/tmp/psycopg-1.1.21$

ADOdb package for PostgreSQL is broken and needs fixing.



-- 
http://mgogala.byethost5.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Errno 9] Bad file descriptor

2010-07-14 Thread Thomas Jollans
On 07/14/2010 01:21 PM, joblack wrote:
>> |
>> | Starting point:
>> | ...
>> | self.status['text'] = 'Processing ...'
>> | try:
>> | cli_main(argv)
>> | except Exception, e:
>> | self.status['text'] = 'Error: ' + str(e)
>> | return
>> | ...
>> | cli_main:
>> |
>> | keypath, inpath, outpath = argv[1:]
>> | ...
>> | with open(inpath, 'rb') as inf:
>> | serializer = PDFSerializer(inf, keypath)
>> | with open(outpath, 'wb') as outf:
>> | filenr = outf.fileno()
>> | serializer.dump(outf)
>> | return 0
>> |
>> | PDFSerializer.dump:
>> |
>> | def dump(self, outf):
>> | self.outf = outf
>> | ...
>>
>> See that you set serializer.outf to the outf you open in cli_main?
>> Any attempt to use serializer _after_ exiting the "with open(outpath,
>> 'wb') as outf" will use serializer.outf, but the outf is now closed.
>> And thus itsfiledescriptoris invalid.
> 
> Okay, I changed it to a try: ... finally: block where I open the file
> and in finally I close it. Nothing has changed. The error still
> occures.

Where does the error occur? If Cameron is right, it occurs somewhere
completely different, when serializer.dump() is already long done, when
some unsuspecting fool tries to do something with serializer.outf (such
as closing it)

> 
> Doesn't the
> 
> with open(outpath, 'wb') as outf:
> 
> clause has to wait until the pdfserialiser.dump method has finished
> anyway? IMHO it can't just call it and immediately close it.
> 
> At least the try: finally: construct should work? Or does it the same
> (call the method and immediately jump to the finally close)?
> 
> Would it work if I would write:
> 
> with closing(outpath, 'wb') as outf: ?
> 
> I'm a little bit confused about Python's strange processing ...

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


Re: Easy questions from a python beginner

2010-07-14 Thread Grant Edwards
On 2010-07-11, wheres pythonmonks  wrote:

> I have some easy issues (Python 2.6)

As of a few minutes ago, this thread had 48 postings on my news
server.

To paraphrase somebody famous:

There are no such things as easy questions.  There are, however,
easy answers.  And they're wrong.

-- 
Grant Edwards   grant.b.edwardsYow! Did I say I was
  at   a sardine?  Or a bus???
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.insert

2010-07-14 Thread Chris Rebert
On Wed, Jul 14, 2010 at 7:54 AM, Eric J. Van der Velden
 wrote:
> Hi,
>
> I understand this:
>
 l=[1,2,3]
 l[1:2]=[8,9]
 l
> [1,8,9,3]
>
> But how do you do this with list.insert?

You can't clobber existing items in the list using just .insert(), so
the closest you could get is something like:
del l[1]
l.insert(1,9)
l.insert(1,8)

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


Re: High Performance solutions are needed to do things like urlretrieve

2010-07-14 Thread MRAB

David wrote:

urlretrieve works fine.  However, when file size get very large.  It
goes on forever, and even fails.

For instance, one of download .zip file is of 363,096KB.

Particularly, when trying to get, with urlretrieve, a zipped folder of
a very large size, it could take up to 20 to 30 minutes.  Often it
fails, never any problem with smaller folders.  Any solution for this?


Do you have any control over the other end? If yes, then you could try
transferring it in multiple chunks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Issue with logging.config

2010-07-14 Thread Joe Hughes
This is why I did what I did, because I couldn't figure it out either.  I did 
find issue 5421 at python.org which is where I got the idea for the code change.

Joe

On Jul 14, 2010, at 12:35 PM, Peter Otten wrote:

> Vinay Sajip wrote:
> 
>> On Jul 14, 3:21 pm, Joe Hughes  wrote:
>>> Thanks for the information.  I sent an email to the maintainer and got
>>> some information that helped me continue with this.  My solution was to
>>> change line 785 of handlers.py to
>>> 
>>> self.socket.sendto(bytes(msg, 'ascii'), self.address)
>>> 
>>> After I made the change, I got exactly what I was looking for.
>>> 
>> 
>> What I suggested was this:
>> 
>> http://plumberjack.blogspot.com/2010/07/using-custom-formatter-to-deal-
> with.html
>> 
>> Of course your change may work for you, but it's not a change we can
>> have in the stdlib - since not everyone will be using ASCII for
>> everything.
> 
> It's not obvious to me how you'd adapt that code to work with python3.1 and 
> the SysLogHandler. Can you give some details?
> 
> Peter
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: adodb.NewADOConnection('postgres') returns None

2010-07-14 Thread Thomas Jollans
On 07/14/2010 02:14 PM, micayael wrote:
> On Jul 13, 5:35 pm, Thomas Jollans  wrote:
>> On 07/13/2010 09:55 PM, micayael wrote:
>>
>>> Hi.
>>
>>> I'm trying to use adodb for postgres. I had instaled in ubuntu 9.10
>>> the adodb and psycopg2 module (sudo apt-get install python-adodb
>>> python-psycopg2) but when I put this
>>
>>> import adodb
>>> print adodb.NewADOConnection('postgres') --> None
>>
>>> but with
>>
>>> print adodb.NewADOConnection('mysql') -->
>>> 
>>
>> http://packages.ubuntu.com/lucid/python-adodb
>>
>> Recommends: python-psycopg (Package not available)
>>
>> If it says it wants psycopg, I wouldn't expect it to work with psycopg2,
>> which is probably quite different in some way - otherwise it would be
>> called the same.
>>
>>  - Thomas
> 
> Thanks Thomas.
> :-( then adodb today dosn't work with postgres (at least on ubuntu)
> right?

It certainly looks that way. It may be possible to install an old
psycopg module by hand - I'd expect that to work as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: High Performance solutions are needed to do things like urlretrieve

2010-07-14 Thread Thomas Jollans
On 07/14/2010 07:49 PM, David wrote:
> 
> urlretrieve works fine.  However, when file size get very large.  It
> goes on forever, and even fails.
> 
> For instance, one of download .zip file is of 363,096KB.
> 
> Particularly, when trying to get, with urlretrieve, a zipped folder of
> a very large size, it could take up to 20 to 30 minutes.  Often it
> fails, never any problem with smaller folders.  Any solution for this?

Does this only occur with urllib, or is this the case for other
software, like a web browser, or a downloader like wget?

The more you try to copy, the longer it takes. The longer it takes, the
more probable a problem affecting a file becomes. 20 to 30 minutes might
well, depending on the network speed, be a readonable timeframe for
360M. And what does "often" mean here?

In other words: Are you sure urlretrieve is to blame for your problems,
why are you sure, and have you tried using urllib2 or the other urllib
functions?

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


High Performance solutions are needed to do things like urlretrieve

2010-07-14 Thread David

urlretrieve works fine.  However, when file size get very large.  It
goes on forever, and even fails.

For instance, one of download .zip file is of 363,096KB.

Particularly, when trying to get, with urlretrieve, a zipped folder of
a very large size, it could take up to 20 to 30 minutes.  Often it
fails, never any problem with smaller folders.  Any solution for this?

Regards.

David


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


Re: Easy questions from a python beginner

2010-07-14 Thread John Posner

On 7/14/2010 12:06 PM, Ethan Furman wrote:


... Have you tried this?

--> def foo():
... print locals()
... blah = 'interesting'
... print locals()
...
--> foo()
{}
{'blah': 'interesting'}

As can be clearly seen, blah does not exist before the assignment -- the
*name* blah has not been *bound* to an object yet, which is also what
the error message says when you try to use it before it exists:


As already cited, according to Section 4.1 "Naming and binding" in the 
Language Reference, the name "blah" *does* exist before the assignment. 
That's the implication of this phrase:


  If the name refers to a local variable that has not been bound,

(BTW, "has not been bound" should really be "is not currently bound", to 
allow for use of *del* earlier in the block.)


Try this:

#--
def foo():
print "1. varnames:", globals()['foo'].__code__.co_varnames
print "2. locals:", locals()
blah = 'interesting'
print "3. locals:", locals()

foo()
#--

The output (Python 2.6.5) is:

1. varnames: ('blah',)
2. locals: {}
3. locals: {'blah': 'interesting'}

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


Re: death of newsgroups (Microsoft closing their newsgroups)

2010-07-14 Thread Ricardo Aráoz

On 14/07/2010 12:19 p.m., Kenneth Tilton wrote:

Steven D'Aprano wrote:

On Tue, 13 Jul 2010 23:24:12 -0400, Kenneth Tilton wrote:


The moral? If you look for the spam, you'll find it.


And if you *don't* look for spam, you can be sure that some goose 
will reply to it and get it past your filters. Thanks for that 
Kenneth, if that is your name and you're not a Xah Lee sock-puppet.


Let me see if I have this right. Your technique for reducing unwanted 
traffic is to openly insult one of the participants? That is how you 
clean things up? Because most people on Usenet respond well to 
personal insults and hush up? I have so much to learn!


PLONK!!!

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


Re: Easy questions from a python beginner

2010-07-14 Thread Steven D'Aprano
On Wed, 14 Jul 2010 09:06:34 -0700, Ethan Furman wrote:

> Alf P. Steinbach /Usenet wrote:
[...]
>> Clearly when the exception is raised, referring to the variable, the
>> variable exists.
> 
> You are the only one spouting nonsense.  Have you tried this?
> 
> --> def foo():
> ...   print locals()
> ...   blah = 'interesting'
> ...   print locals()
> ...
> --> foo()
> {}
> {'blah': 'interesting'}
> 
> As can be clearly seen, blah does not exist before the assignment -- the
>   *name* blah has not been *bound* to an object yet, which is also what
> the error message says when you try to use it before it exists:

While I agree with your basic position that, in a meaningful sense, 
"blah" does not exist before it is assigned to, your explanation is 
invalid.

In CPython, local variables in functions are optimised into pre-allocated 
slots. locals() is a *copy* of the actual locals, and any locals which 
are allocated but not defined are suppressed from the dict.

>>> def f():
... x = 5
... if y:
... z = 1
... return x+z
...
>>> f.func_code.co_nlocals
2
>>> f.func_code.co_freevars
()
>>> f.func_code.co_varnames
('x', 'z')

More here:
http://tech.blog.aknin.name/2010/07/03/pythons-innards-code-objects/

You'll notice that in the sense of having space allocated for them in the 
code object, the variables already exist before the function has even 
been executed. But of course that's not the only sense, or even the most 
important one. I would argue that, in a very real sense, if you call f() 
with the global y set to False, that *semantically* the local z doesn't 
exist, even if the error message says different:

> UnboundLocalError: local variable 'z' referenced before assignment


-- 
Steven

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


Some success with the "Plot" problem :D

2010-07-14 Thread Ritchy lelis
Hello guys

On Following the development of my ADC (Analog-to-Digital converter
Residue function transference) i already got some progress with the
plot problem and (much thanks to colleagues who help me in this forum
and not only) i would like to show you all the progress that has
already got and take the opportunity to leave some doubt:

-
import numpy
import matplotlib.pylab as plt

Vref = numpy.arange(-20, 20, 0.2)
Vi = numpy.arange(-10, 10, 0.1)
V0 = numpy.arange(Vi.shape[0])
i = 0

while i < Vi.shape[0]:
if Vi[i] > Vref[i]/4:
V0[i] = 2*Vi[i]-Vref[i]
elif (-Vref[i]/4)<= Vi[i] and Vi[i] <= Vref[i]/4:
V0[i] = 2*Vi[i]
elif Vi[i] < -Vref[i]/4:
V0[i] = 2*Vi[i] + Vref[i]
i = i + 1

plt.plot(V0)  # this plot will make that seems stairs rising
plt.show()

-

For now i have a draw that seems cool to initialize the second part of
my objectives but anyway i would like to request some help because I'm
not getting on the waveform to start at origin of the coordinate axes.

I'm looking for a better way to create those initial vectors (Vi,
Vref, V0), any sujestions? Forword i want them to be implemented as a
function that in the start of the program, i ask the user the
dimention of the arrays that they want to use.

Also if you have any sujestions to improve the script you can drope it
here, is always welcome.

For who want's to help but don´t have much information about what i'm
doing here it's a link that is pretty cool:

http://www.eit.lth.se/fileadmin/eit/courses/eti220/files/lectures/2009/lec4.pdf

I'll be waiting.

Cheers.

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


Re: Issue with logging.config

2010-07-14 Thread Peter Otten
Vinay Sajip wrote:

> On Jul 14, 3:21 pm, Joe Hughes  wrote:
>> Thanks for the information.  I sent an email to the maintainer and got
>> some information that helped me continue with this.  My solution was to
>> change line 785 of handlers.py to
>>
>> self.socket.sendto(bytes(msg, 'ascii'), self.address)
>>
>> After I made the change, I got exactly what I was looking for.
>>
> 
> What I suggested was this:
> 
> http://plumberjack.blogspot.com/2010/07/using-custom-formatter-to-deal-
with.html
> 
> Of course your change may work for you, but it's not a change we can
> have in the stdlib - since not everyone will be using ASCII for
> everything.

It's not obvious to me how you'd adapt that code to work with python3.1 and 
the SysLogHandler. Can you give some details?

Peter

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


Re: ctypes' c_longdouble: underflow error (bug?)

2010-07-14 Thread Thomas Jollans
On 07/14/2010 03:24 PM, kj wrote:
> 
> 
> 
> I have a C library function hg that returns a long double, so when
> I import it using C types I specify this return type like this:
> 
> MYLIB.hg.restype = ctypes.c_longdouble
> 
> But certain non-zero values returned by hg appear as zero Python-side.
> If I modify hg so that it prints out its value right before returning
> it, I get stuff like the following:
> 
 0 == MYLIB.hg(100, 200, 100, 6000)
> from hg: 2.96517e-161 
> False
 0 == MYLIB.hg(200, 200, 200, 6000)
> from hg: 5.28791e-380
> True
> 
> So, although the value returned by hg in the second invocation
> above is 5.28791e-380, Python sees it as 0.
> 
> What am I doing wrong?

Nothing.

http://docs.python.org/library/ctypes.html#fundamental-data-types

c_longdouble maps to float

http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex

"floating point numbers are implemented using double in C"

ergo, the extra precision a long double gives you versus a normal double
is lost if you use Python (or, at least, ctypes)

If you really want to keep the precision, you need a new/different type.
ctypes won't help you. Cython and NumPy may or may not be useful here.

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


Re: python3: help with subprocess

2010-07-14 Thread Dave Angel

Alan wrote:

Hi there,

Module commands is gone in python3, so I am trying subprocess. So please I
would appreciate if someone can tell me how to do this better:

before I had:

cmd = 'uname -a'
out = commands.getoutput(cmd)

'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

now:

out = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout =
sub.PIPE).communicate()[0][:-1]

b'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

Yes, it's ugly. the [:-1] above is to get read of the last '\n' which with
getoutputs I didn't have. But what's giving headache is this "b'..." in the
beginning.

Can someone explain, point me to where I can now about it and how to make
this better? I wanted a plain string in out.

Many thanks in advance,

Alan
  


In Python3, 'plain string' would be unicode.  But communicate returns 
bytes.  So convert them to a string, for example, by using str().  By 
default that'll assume the bytes are ASCII encoded, so if you have any 
characters above 7f, you'd need something more.


DaveA

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


Re: death of newsgroups (Microsoft closing their newsgroups)

2010-07-14 Thread John Bokma
Kenneth Tilton  writes:

fup2 poster

> Let me see if I have this right. Your technique for reducing unwanted
> traffic is to openly insult one of the participants?

Heh, or just ploinking them (done).

Or making them cry like a little baby:
http://xahlee.org/Periodic_dosage_dir/t2/harassment.html

(it had an effect for a while :-D )

-- 
The John Bokma guy j3b

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


multiline input and readline

2010-07-14 Thread Michele Simionato
Googling for ways to use the readline library with multiline input I
found out the following stackoverflow answer:

http://stackoverflow.com/questions/161495/is-there-a-nice-way-of-handling-multi-line-input-with-gnu-readline

The solution is to use the rl_bind_key function, but it does not look
like such function is wrapped in Python: what are my options?

Notice that compatibility with pyreadline (which work on Windows)
would be a plus.

TIA,

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


Re: Identify the Color of an Image

2010-07-14 Thread John Nagle

On 7/14/2010 5:37 AM, Monyl wrote:

Hi,

1. How can I find the color of  an image present the webpage?

2. How to identify the font type of the selected text present in the
content of the web page

It would be much helpfull, if anyone responds to it ASAP

Thanks
Mohmyda


"Selected text"?  Selected how?  "Selected" implies some form
of user interface, like a browser.  If you're doing something in
a browser, look into Firefox and Greasemonkey.

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


Re: python3: help with subprocess

2010-07-14 Thread Gary Herron

On 07/14/2010 08:38 AM, Alan wrote:

Hi there,

Module commands is gone in python3, so I am trying subprocess. So 
please I would appreciate if someone can tell me how to do this better:


before I had:

cmd = 'uname -a'
out = commands.getoutput(cmd)

'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23 
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 
MacBookPro5,2 Darwin'


now:

out = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout = 
sub.PIPE).communicate()[0][:-1]


b'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23 
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 
MacBookPro5,2 Darwin'


Yes, it's ugly. the [:-1] above is to get read of the last '\n' which 
with getoutputs I didn't have. But what's giving headache is this 
"b'..." in the beginning.


Can someone explain, point me to where I can now about it and how to 
make this better? I wanted a plain string in out.


Many thanks in advance,

Alan
--
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28 <<



The 'b' is not part of the returned value.  If you look at the *type* of 
the returned value, you will find that it is not a string, but rather a 
byte array.   Printing of byte arrays displays the b'...' to indicate 
the type of thing begin printed.


If you want a string, then you must convert the byte array to a 
string.   For instance:


str_out = out.decode('ascii')

(And remember:  in Python3, strings are always unicode.)

Also, using out.strip() or str_out.strip() may be a better way to remove 
the white space.


Gary Herron




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


Re: python3: help with subprocess

2010-07-14 Thread Ben Kaplan

On Jul 14, 2010, at 8:38 AM, Alan wrote:

> Hi there,
> 
> Module commands is gone in python3, so I am trying subprocess. So please I 
> would appreciate if someone can tell me how to do this better:
> 
> before I had:
> 
> cmd = 'uname -a'
> out = commands.getoutput(cmd)
> 
> 'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23 
> 18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2 
> Darwin'
> 
> now:
> 
> out = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout = 
> sub.PIPE).communicate()[0][:-1]
> 
> b'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23 
> 18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2 
> Darwin'
> 
> Yes, it's ugly. the [:-1] above is to get read of the last '\n' which with 
> getoutputs I didn't have. But what's giving headache is this "b'..." in the 
> beginning.
> 
> Can someone explain, point me to where I can now about it and how to make 
> this better? I wanted a plain string in out.
> 
> Many thanks in advance,
> 
> Alan

There are 2 string types in Python: byte strings and unicode strings. In Python 
2.x, they were called str and unicode, the default was str, and unicode was 
signaled by prefixing the string with a u. In python 3.x, they are called bytes 
and str. str (which is what used to be unicode) is the default, and a byte 
string (what used to be str) is signaled by putting a b in front of the string.

Unicode is an abstract concept. Python can move it around internally, but the 
only thing you can send to other computers and programs is a sequence of bytes. 
If you want to convert the byte string to a unicode string, you have to decode 
it afterwards.

out = out.decode("utf-8")


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


Re: Easy questions from a python beginner

2010-07-14 Thread Ethan Furman

Alf P. Steinbach /Usenet wrote:

* MRAB, on 12.07.2010 00:37:

Alf P. Steinbach /Usenet wrote:


Of course there are variables, that's why the docs call them variables.


In Java a variable is declared and exists even before the first
assignment to it. In Python a 'variable' isn't declared and won't exist
until the first 'assignment' to it.


That is a misconception.

>
In Python a variable is declared by having an assignment to it, which 
for a local variable may be anywhere within a routine.


If such a variable is used before it's been assigned to, then you get an 
uninitialized variable exception. Clearly the variable must exist in 
order for the exception to refer to it (not to mention the exception 
occurring at all).


Really?  So it's impossible for the interpreter, upon seeing the name 
'blah', to scan forward to see if 'blah' is somewhere in the function in 
order to give a more meaningful error message?  Of course not.




  def foo():
  print( blah )
  blah = "this is both an assignment and a declaration causing it to 
exist"


  foo()

Clearly when the exception is raised, referring to the variable, the 
variable exists.


You are the only one spouting nonsense.  Have you tried this?

--> def foo():
...   print locals()
...   blah = 'interesting'
...   print locals()
...
--> foo()
{}
{'blah': 'interesting'}

As can be clearly seen, blah does not exist before the assignment -- the 
 *name* blah has not been *bound* to an object yet, which is also what 
the error message says when you try to use it before it exists:


UnboundLocalError: local variable 'blah' referenced before assignment

Nothing religious about it -- just the facts.

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


Re: python app development

2010-07-14 Thread mo reina
On Jul 3, 9:59 pm, Terry Reedy  wrote:
> On 7/3/2010 1:48 PM,mo reinawrote:
>
> > an anyone recommend a resource (book,tutorial,etc.) that focuses on
> > application development in python? something similar to Practical
> > Django Projects, but for stand alone applications instead of web apps
> > (for now).
>
> > i'm in a bit of a funny place, i have a decent/good grasp of python
> > syntax and my logic isn't bad, but i have no clue on how to assemble
> > an application, i seem to be stuck on writing scripts.
>
> > i've looked at the source of a few projects but the flow is way over
> > my head, i understand the syntax but not the logic, which is why i'm
> > looking for a project-cenetered learning resource, instead of a
> > reference or language-feature resource. also, it seems that a lot of
> > app programming is 90% gui bindings, with very little actual code, or
> > am i totally way off mark?
>
> If the app is a gui app and if logic is overly intermixed with gui
> stuff, I am sure it can seem like that. Many recommend the MVC
> model-view-controller model for app design. Even that can be confusing;
> to me it should be model-controller-view, even though that is harder to
> say. What are the data (values and objects) and how are they stored?
> What are the rules for manipulating the data and objects? And then, and
> only then, how to communicate with the user?
>
>
>
> > i recently picked up the django practical projects book, and in a few
> > days i re-wrote a website i did with django. i feel it was the book's
> > project-centric approach that made this possible.
>
> Another issue is who controls the flow of interactions, the user or the
> code. For instance, a gui form used for input tends to direct the user
> along a linear path. The same form, used for edit, presents existing
> data and allows the user to pick and choose the fields to edit. This
> distinction, along with MVC ideas, is important for reading source code.
>
> I have mostly seen this issue discussed in game reviews and game design
> writing. In computer games, there is the same general difference between
> a linear obstacle course game and a world to be explored in whatever
> order one wants. (And there are some with both an explorable world *and*
> a (somewhat optional) linear main quest line.)
>
> I am not familiar with any general app design books, but I have seen
> game design articles and books that are on a par with writing about web
> design. There are other books on business apps.
>
> --
> Terry Jan Reedy

so you're suggesting:
-write core algorithm(model)
-link algorithm(s) with each other and a central menu, if
applicable(controller)
-write views for gui or cli(view)

this is actually the path that i follow when writing django apps, and
is the sequence that is being used in "Practical Django Projects",
where first the different classes/data structures are written, then
linked together through the url file, and finally html is written for
each "view".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issue with logging.config

2010-07-14 Thread Vinay Sajip
On Jul 14, 3:21 pm, Joe Hughes  wrote:
>         Thanks for the information.  I sent an email to the maintainer and 
> got some information that helped me continue with this.  My solution was to 
> change line 785 of handlers.py to
>
> self.socket.sendto(bytes(msg, 'ascii'), self.address)
>
> After I made the change, I got exactly what I was looking for.
>

What I suggested was this:

http://plumberjack.blogspot.com/2010/07/using-custom-formatter-to-deal-with.html

Of course your change may work for you, but it's not a change we can
have in the stdlib - since not everyone will be using ASCII for
everything.

Regards,

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


Re: list.insert

2010-07-14 Thread Emile van Sebille

On 7/14/2010 7:54 AM Eric J. Van der Velden said...

Hi,

I understand this:


l=[1,2,3]
l[1:2]=[8,9]
l

[1,8,9,3]

But how do you do this with list.insert?





>>> l = [1,2,3,4]
>>> l[1:2]=""
>>> dummy = [l.insert(1,x) for x in reversed([8,9])]


Emile

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


python3: help with subprocess

2010-07-14 Thread Alan
Hi there,

Module commands is gone in python3, so I am trying subprocess. So please I
would appreciate if someone can tell me how to do this better:

before I had:

cmd = 'uname -a'
out = commands.getoutput(cmd)

'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

now:

out = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout =
sub.PIPE).communicate()[0][:-1]

b'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

Yes, it's ugly. the [:-1] above is to get read of the last '\n' which with
getoutputs I didn't have. But what's giving headache is this "b'..." in the
beginning.

Can someone explain, point me to where I can now about it and how to make
this better? I wanted a plain string in out.

Many thanks in advance,

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: death of newsgroups (Microsoft closing their newsgroups)

2010-07-14 Thread Kenneth Tilton

Steven D'Aprano wrote:

On Tue, 13 Jul 2010 23:24:12 -0400, Kenneth Tilton wrote:


The moral? If you look for the spam, you'll find it.


And if you *don't* look for spam, you can be sure that some goose will 
reply to it and get it past your filters. Thanks for that Kenneth, if 
that is your name and you're not a Xah Lee sock-puppet.


Let me see if I have this right. Your technique for reducing unwanted 
traffic is to openly insult one of the participants? That is how you 
clean things up? Because most people on Usenet respond well to personal 
insults and hush up? I have so much to learn!


Or was it this?



Followups set to a black hole.




That works? Amazing.

Here, I'll show you what spam looks like: my steadily-improving 
revolution in learning Algebra: http://teamalgebra.com/


kt

--
http://www.stuckonalgebra.com
"The best Algebra tutorial program I have seen... in a class by itself." 
Macworld

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


list.insert

2010-07-14 Thread Eric J. Van der Velden
Hi,

I understand this:

>>> l=[1,2,3]
>>> l[1:2]=[8,9]
>>> l
[1,8,9,3]

But how do you do this with list.insert?

Thanks,

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


stdiodemo (twisted-python) and enable command history

2010-07-14 Thread kak...@gmail.com
Hello again to all,
While playing and extending stdiodemo.py,
a came up with a thought of adding command line history.
Is this possible?
Any hints?

Thanks

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


Re: Issue with logging.config

2010-07-14 Thread Joe Hughes
Peter,

Thanks for the information.  I sent an email to the maintainer and got 
some information that helped me continue with this.  My solution was to change 
line 785 of handlers.py to

self.socket.sendto(bytes(msg, 'ascii'), self.address)

After I made the change, I got exactly what I was looking for.

Joe

On Jul 13, 2010, at 8:02 AM, Peter Otten wrote:

> Joe Hughes wrote:
> 
>> I'm doing some work with logging.config and I'm running into an
>> interesting situation.  I've run this by python-help, but that didn't help
>> so I thought I would send to the list.  Here is the config file
>> 
>> [loggers]
>> keys=root,log,syslog
>> 
>> [handlers]
>> keys=console,log,syslog
>> 
>> [formatters]
>> keys=rootFormat,logFormat,syslogFormat
>> 
>> [logger_root]
>> level=DEBUG
>> handlers=console
>> 
>> [logger_log]
>> level=DEBUG
>> handlers=log
>> qualname=log
>> 
>> [logger_syslog]
>> level=DEBUG
>> handlers=syslog
>> qualname=syslog
>> 
>> [handler_console]
>> class=StreamHandler
>> level=DEBUG
>> formatter=rootFormat
>> args=(sys.stdout,)
>> 
>> [handler_log]
>> class=handlers.RotatingFileHandler
>> level=DEBUG
>> formatter=logFormat
>> args=('E:\local\Logs\syslog_interface.txt', 'a', 1000, 10)
>> propagate=0
>> 
>> [handler_syslog]
>> class=handlers.SysLogHandler
>> level=DEBUG
>> formatter=syslogFormat
>> host=141.232.41.205
>> port=handlers.SYSLOG_UDP_PORT
>> facility=LOG_LOCAL0
>> 
> args=(('141.232.41.205',handlers.SYSLOG_UDP_PORT),handlers.SysLogHandler.LOG_LOCAL0)
>> 
>> [formatter_rootFormat]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> 
>> [formatter_logFormat]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> 
>> [formatter_syslogFormat]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> 
>> and the python code
>> 
>> 
>> # Imports
>> 
>> import logging
>> import logging.config
>> import os
>> import re
>> from threading import Thread
>> 
>> 
>> # Constants
>> 
>> CONFIG_FILENAME = 'E:\local\Config\syslog_interface.conf'
>> MCU_LIST_FILENAME = 'E:\local\Scada_Devices\mcu.txt'
>> 
>> 
>> # Classes
>> 
>> 
>> 
>> # PingIt
>> 
>> class PingIt(Thread):
>>def __init__(self, mcuIP):
>>Thread.__init__(self)
>>self.ip = mcuIP
>>self.status = -1
>> 
>>def run(self):
>>pinging = os.popen("ping -n 2 " + self.ip, 'r')
>> 
>>while 1:
>>line = pinging.readline()
>> 
>>if not line:
>>break
>> 
>>gotResponse = re.findall(PingIt.lifeline, line)
>> 
>>if gotResponse:
>>self.status = int(gotResponse[0])
>> 
>> 
>> # Main Routine
>> 
>> #
>> # Get the logger configuration information
>> #
>> logging.config.fileConfig(CONFIG_FILENAME)
>> 
>> #
>> # Check if running from command line and create logger
>> #
>> if os.environ.get('PROMPT'):
>>#
>># create logger for output to stdout
>>#
>>logger = logging.getLogger('root')
>> else:
>>#
>># create logger for output to logfile
>>#
>>logger = logging.getLogger('log')
>> 
>> #
>> # Create logger for syslog output
>> #
>> syslog = logging.getLogger('syslog')
>> 
>> #
>> # Declare variables
>> #
>> PingIt.lifeline = re.compile(r"Received = (\d)")
>> mcu_dict = {}
>> ping_list = []
>> status = ("Not responding", "Responded to only 1 ping of 2", "Alive")
>> 
>> #
>> # Open the MCU file
>> #
>> mcu_file = open(MCU_LIST_FILENAME, 'r')
>> 
>> #
>> # Loop through the contents of the MCU file and ping the IPs
>> #
>> for mcu in mcu_file:
>>#
>># mcu file contents example
>># 192.168.97.227 MCU_HMSTD
>>#
>># mcu_info[0] = MCU IP Address
>># mcu_info[1] = MCU Name
>>#
>>mcu_info = mcu.split()
>>mcu_dict[mcu_info[0]] = mcu_info[1]
>>current = PingIt(mcu_info[0])
>>logger.info("Pinging " + mcu_info[1])
>>ping_list.append(current)
>>current.start()
>> 
>> #
>> # Loop through ping list and print the response
>> #
>> for pinged in ping_list:
>>pinged.join()
>>logger.info("Status - " + mcu_dict[pinged.ip] + " is " +
>>status[pinged.status]) syslog.info("Status - " + mcu_dict[pinged.ip] +
>>" is " + status[pinged.status])
>> 
>> This is the output from the code
>> 
>> 2010-07-06 14:43:58,280 - log - INFO - Status - netboss2 is Not responding
>> msg =  <134>2010-07-06 14:43:58,312 - syslog - INFO - Status - netboss2 is
>> Not res

Re: nicer way to remove prefix of a string if it exists

2010-07-14 Thread Paul McGuire
On Jul 13, 6:49 pm, News123  wrote:
> I wondered about a potentially nicer way of removing a prefix of a
> string if it exists.
>

Here is an iterator solution:

from itertools import izip

def trim_prefix(prefix, s):
i1,i2 = iter(prefix),iter(s)
if all(c1==c2 for c1,c2 in izip(i1,i2)):
return ''.join(i2)
return s

print trim_prefix("ABC","ABCDEFGHI")
print trim_prefix("ABC","SLFJSLKFSLJFLSDF")


Prints:

DEFGHI
SLFJSLKFSLJFLSDF


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


ctypes' c_longdouble: underflow error (bug?)

2010-07-14 Thread kj



I have a C library function hg that returns a long double, so when
I import it using C types I specify this return type like this:

MYLIB.hg.restype = ctypes.c_longdouble

But certain non-zero values returned by hg appear as zero Python-side.
If I modify hg so that it prints out its value right before returning
it, I get stuff like the following:

>>> 0 == MYLIB.hg(100, 200, 100, 6000)
from hg: 2.96517e-161 
False
>>> 0 == MYLIB.hg(200, 200, 200, 6000)
from hg: 5.28791e-380
True

So, although the value returned by hg in the second invocation
above is 5.28791e-380, Python sees it as 0.

What am I doing wrong?

TIA!

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


Re: Why doesn't python's list append() method return the list itself?

2010-07-14 Thread Nathan Rice
The better question is, do I ever use them? Thinking back over the code I've
written in the last couple of years, I would say probably two or three times
(mostly in unit tests).  I've had to code around string's sequence behavior
DOZENS of times.  Is it nifty that strings can be sliced like that?  Sure.
 In general my experience has been that the string methods (and some misc
functions in other modules) do a better job in simple cases, and regular
expressions do a better job in complex cases.  I just don't see string
slicing having utility that is irreplaceable, and it is bug-inducing in many
cases, or at the very least it can propagate programming errors way down
stream.

 Ultimately, I highly doubt it's going anywhere, so it's a moot point.  I
definitely feel that python is trading real usability for "flash" with
string slicing though.

On Tue, Jul 13, 2010 at 8:48 PM, Aahz  wrote:

> [Original not available on my swerver, responding here]
>
> >On 7/11/10 10:03 PM, Nathan Rice wrote:
> >>
> >> Yeah, I long ago filed the in place place in the same folder as
> >> strings-as-sequences, all() returning True for an empty iterable and any
> >> returning True rather than the thing which triggered it.
>
> Because I love to repeat myself:
>
> "...string iteration isn't about treating strings as sequences of strings,
> it's about treating strings as sequences of characters.  The fact that
> characters are also strings is the reason we have problems, but characters
> are strings for other good reasons."  --Aahz
> http://mail.python.org/pipermail/python-3000/2006-April/000897.html
>
> Do you really want to give up Python's lovely string-slicing
> capabilities?
> --
> Aahz (a...@pythoncraft.com)   <*>
> http://www.pythoncraft.com/
>
> "Normal is what cuts off your sixth finger and your tail..."  --Siobhan
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if a command is valid

2010-07-14 Thread Kenny Meyer
On Jul 13, 4:14 pm, Hans Mulder  wrote:
> Chris Rebert wrote:
> > `where` seems to be a zsh built-in:
> > $ # I'm in UR bash
> > $ nonexistent
> > -bash: nonexistent: command not found
> > $ where bash
> > -bash: where: command not found
>
> > And not everyone has zsh installed, so...
> > I don't see why one shouldn't use the standard `which` *nix command instead.
>
> Because `which` ia a C shell script.  It reads your .cshrc, to see which
> aliases would be defined if you were to use the C shell, but it doesn't
> look at your .bashrc.
>
> You're probably better off using `type`: it knows about built-ins and
> shell functions and that sort of stuff:
>
> $ which type
> /usr/bin/type
> $ type type
> type is a shell builtin
> $
>
> Guess which answer is more relevant to you .
>
> HTH,
>
> -- HansM

Oh thanks, Hans! `type` seems to a good alternative. Surely it can
also get the job (better) done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Identify the Color of an Image

2010-07-14 Thread Monyl
Hi,

1. How can I find the color of  an image present the webpage?

2. How to identify the font type of the selected text present in the
content of the web page

It would be much helpfull, if anyone responds to it ASAP

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


Re: eGenix at EuroPython 2010

2010-07-14 Thread Daniel Fetchinson
> EuroPython 2009 - Making 50 Mio. EUR per year using Python
> http://www.egenix.com/go23/

This link returns a 404.

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adodb.NewADOConnection('postgres') returns None

2010-07-14 Thread micayael
On Jul 13, 5:35 pm, Thomas Jollans  wrote:
> On 07/13/2010 09:55 PM, micayael wrote:
>
> > Hi.
>
> > I'm trying to use adodb for postgres. I had instaled in ubuntu 9.10
> > the adodb and psycopg2 module (sudo apt-get install python-adodb
> > python-psycopg2) but when I put this
>
> > import adodb
> > print adodb.NewADOConnection('postgres') --> None
>
> > but with
>
> > print adodb.NewADOConnection('mysql') -->
> > 
>
> http://packages.ubuntu.com/lucid/python-adodb
>
> Recommends: python-psycopg (Package not available)
>
> If it says it wants psycopg, I wouldn't expect it to work with psycopg2,
> which is probably quite different in some way - otherwise it would be
> called the same.
>
>  - Thomas

Thanks Thomas.
:-( then adodb today dosn't work with postgres (at least on ubuntu)
right?
-- 
http://mail.python.org/mailman/listinfo/python-list


MAKE UPTO $5000 MONTHLY! $2000 INYOUR FIRST 30 DAYS!

2010-07-14 Thread jameser
MAKE UPTO $5000 MONTHLY! $2000 INYOUR FIRST 30 DAYS!

Generate $50 to $100 whenever you have a couple of
hours free time to spare.
You could make $50 or more in the next 2 hours.
Starting right Now!Today!
Earn from your free website
Awesome earnings get paid for your honest work
Join as a free member and get paid to your bank account
To join the Network follow the link

  http://www.freesitesignup.com/a/coupon.php?id=3448

Get paid for your real work and earn awesome 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nicer way to remove prefix of a string if it exists

2010-07-14 Thread Tim Chase

On 07/13/2010 09:22 PM, Shashwat Anand wrote:

  You could write:

rsl = f[len(prefix):] if f.startswith(prefix) else f


Or you can just do split and join, "".join(f.split(prefix, 1)) will do.


This suggestion breaks if the prefix occurs within the string 
rather than at the beginning:


  f = "this has file:// inside it"
  prefix = "file://"

So your suggestion really just operates like

  f.replace(prefix, '', 1)

-tkc




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


Re: Errno 9] Bad file descriptor

2010-07-14 Thread joblack
> |
> | Starting point:
> | ...
> |         self.status['text'] = 'Processing ...'
> |         try:
> |             cli_main(argv)
> |         except Exception, e:
> |             self.status['text'] = 'Error: ' + str(e)
> |             return
> | ...
> | cli_main:
> |
> |     keypath, inpath, outpath = argv[1:]
> | ...
> |     with open(inpath, 'rb') as inf:
> |         serializer = PDFSerializer(inf, keypath)
> |         with open(outpath, 'wb') as outf:
> |             filenr = outf.fileno()
> |             serializer.dump(outf)
> |     return 0
> |
> | PDFSerializer.dump:
> |
> |     def dump(self, outf):
> |         self.outf = outf
> | ...
>
> See that you set serializer.outf to the outf you open in cli_main?
> Any attempt to use serializer _after_ exiting the "with open(outpath,
> 'wb') as outf" will use serializer.outf, but the outf is now closed.
> And thus itsfiledescriptoris invalid.

Okay, I changed it to a try: ... finally: block where I open the file
and in finally I close it. Nothing has changed. The error still
occures.

Doesn't the

with open(outpath, 'wb') as outf:

clause has to wait until the pdfserialiser.dump method has finished
anyway? IMHO it can't just call it and immediately close it.

At least the try: finally: construct should work? Or does it the same
(call the method and immediately jump to the finally close)?

Would it work if I would write:

with closing(outpath, 'wb') as outf: ?

I'm a little bit confused about Python's strange processing ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cpp + Python: static data dynamic initialization in *nix shared lib?

2010-07-14 Thread Alf P. Steinbach /Usenet

* Hrvoje Niksic, on 14.07.2010 10:17:

"Alf P. Steinbach /Usenet"  writes:


Also, things like the 'owned' option is just asking for trouble.


Isn't owned=true (or equivalent) a necessity when initializing from a
PyObject* returned by a function declared to return a "new reference"?


No, not quite.

Consider this signature (PyCXX):

   String( PyObject* pyob, bool owned = false )

versus this (cppy):

   PyString( PyPtr object )

With the first signature, every time you construct a String you have to remember 
to (explicitly or implicitly) set the bool flag correctly depending on where the 
actual argument value comes from.


With the second signature the /type/ of the actual argument decides, 
automatically, so there's much less room for messing things up.


With the second signature, if the actual argument is a raw PyObject* pointer 
then it's not owned, and the PyPtr formal argument doesn't increment the 
reference count but just takes ownership. If the actual argument, on the other 
hand, is a PyPtr, then the object is owned by the collection of PyPtr instances 
that refer to the object, and the new formal argument PyPtr instance then 
increments the reference count. In passing, if it should happen that the Python 
community uses the word 'owned' in the opposite sense of what's conventional in 
C++, then I guess & hope you'll figure out what I mean from this description.


PyPtr currently looks like this (complete code):



// progrock.cppy  --  "C++ plus Python"
// A simple C++ framework for writing Python 3.x extensions.
//
// Copyright (c) Alf P. Steinbach, 2010.

#ifndef CPPY_PYPTR_H
#define CPPY_PYPTR_H
#include 


//- Dependencies:

#include 
#include 
#include 



//- Interface:

namespace progrock{ namespace cppy {
using namespace cppx;

enum DoAddRef {};

class PyPtr
{
private:
PyObject*   p_;

public:
typedef cppy::DoAddRef  DoAddRef;

PyPtr( PyObject* p = 0 ): p_( p ) {}

PyPtr( PyObject* p, DoAddRef ): p_( p )
{
assert( p != 0 );  Py_INCREF( p_ );
}

PyPtr( PyPtr const& other ): p_( other.p_ ) { Py_XINCREF( p_ ); }

~PyPtr() { Py_XDECREF( p_ ); }

void swapWith( PyPtr& other )   { std::swap( p_, other.p_ ); }
PyPtr& operator=( PyPtr other ) { swapWith( other ); return *this; }

PyObject* get() const   { return p_; }

PyObject* release()
{
PyObject* const result  = p_;
p_ = 0;
return result;
}
};

inline PyObject* withAddedRef( PyObject* p )
{
Py_INCREF( p );
return p;
}

inline PyObject* pyNoneRef()
{
return withAddedRef( Py_None );
}
} }  // namespace progrock::cppy


#endif



As you can see at the end there, there is 'withAddedRef' and 'pyNoneRef', and 
for that matter the 'DoAddRef' and the 'release()' method, for the cases where 
PyPtr default handling doesn't quite cut it... :-)




How does your API deal with the distinction between new and borrowed
references?


See above.

There are some cases where it must be dealt with, but the main idea is to encode 
that into /types/, instead of as context-dependent figure-it-out.


That's also the main idea of C++ as compared to C, to encode much more into 
types, which helps both for compile time error detection and for automating 
things (like above), which is Very Nice, but which also can make for enormous 
waste of time trying to make the darned language do what you want it to do! :-)



Cheers & hth.,

- Alf


Disclaimer: it's late in the day/night for me, so the above explanation may have 
big logic holes, mispelings and so on, but I hope it gives the idea.


--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: any issues with long running python apps?

2010-07-14 Thread Maria R
I can second the stated opinion that Python per se is stable enough.
We deliver production systems running 24/7 with uptimes counted in
several months
and from what I can see, compared to the OP's app, ours is vastly more
complex.

The only Python-related issue we have encountered so far, wrt to
stability, is how
timers are working. Extensive creation of timer threads have locked up
after some
indeterminable time. We found that the issue was probably related to
some update in
Windows at the time.
We do not know whether this issue is resolved (we encountered it back
in Python 1.4)
and we rewrote our code to use timers differently.

I also second that partitioning the solution in working (server) parts
and GUI (client)
parts is important.

I do not second the generally outspoken distrust in Windows. Indeed, I
would prefer *nix/*nux
but in our case, stability concerns is not one of the issues behind
that.

We use threading to a certain extent (in addition to partioning into
processes). One approach we have,
and have shown very useful to gain stability, is to use Exception
handling carefully and extensively.
We catch *every* exception, report and counteract but do not allow the
process/thread to die.
This is not a trival approach, by no means, but when one know the app
sufficiently, it can be applied
with good results.

Just my 2 c
//Maria

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


Re: ValueError: invalid literal for float(): -1.#IND (pickle.py)

2010-07-14 Thread Alexander Eisenhuth

Mark Dickinson schrieb:




BTW: I'm tied to version 2.5 of python


Have you tried using pickle protocol 1 or 2, instead of pickle
protocol 0?  That may well solve your  problem.  (Those
protocols write out the binary form of a float directly, instead
of reading and writing a string representation.)



Thanks a lot, it looks like it solves the problem using another version of the 
protocol


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


Re: floatref

2010-07-14 Thread Christian Heimes
> I know, I just wondered if there is a *standard* solution.

Yeah, you have to reset your brain and switch to Python mode. *scnr*

Seriously, your inquiry sounds like you are trying to code C in Python.
I'm using Python for more than seven years and I've never felt the need
for a mutable float ref or something similar. Well, except for the first
year when my brain was still in C pointer mode. :)

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


eGenix at EuroPython 2010

2010-07-14 Thread eGenix Team: M.-A. Lemburg



eGenix at EuroPython 2010




Meet up with eGenix at this year's EuroPython Conference in
Birmingham, UK.

The EuroPython Conference is the one of the premier conferences for
Python users and developers. This year it is being held from the 19th
to 22th July in Birmingham, UK.

This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/EuroPython-Conference-2010.html



MEET UP WITH EGENIX AT EUROPYTHON

eGenix was one of the founding members of the EuroPython conference
team and played a major role in organizing the first EuroPython
conference in the year 2002.

Since then we have attended every EuroPython conference to meet up
face-to-face with the many people we know from the Python & Zope
communities and the many people that we don't yet know from these
communities -- if you are interested in meeting with us, please drop
us a note so that we can arrange a meeting: i...@egenix.com.



EGENIX TALKS AT EUROPYTHON 2010

At this year's EuroPython, eGenix will be giving a talk about an
interesting custom project we successfully finished recently:


Running Ghana VAT on Python
---

At the EuroPython 2009 conference, we gave a lightning talk showcasing
an eGenix Custom Python Project that we have been working on for our
client Aya Technologies, Switzerland:

EuroPython 2009 - Making 50 Mio. EUR per year using Python
http://www.egenix.com/go23/

This year, we will present the fantastic results of that project, go
into more depth, analyze the problems we faced and how we solved them.

Marc-André, CEO of eGenix, will be giving this presentation on Monday,
July 19th in the Library Theatre:

http://www.europython.eu/talks/timetable/

Enjoy,


-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 14 2010)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2010-07-19: EuroPython 2010, Birmingham, UK 4 days to go

::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cpp + Python: static data dynamic initialization in *nix shared lib?

2010-07-14 Thread Hrvoje Niksic
"Alf P. Steinbach /Usenet"  writes:

> Also, things like the 'owned' option is just asking for trouble.

Isn't owned=true (or equivalent) a necessity when initializing from a
PyObject* returned by a function declared to return a "new reference"?

How does your API deal with the distinction between new and borrowed
references?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floatref

2010-07-14 Thread Roald de Vries

On Jul 14, 2010, at 3:53 AM, Steven D'Aprano wrote:

On Tue, 13 Jul 2010 19:26:34 +0200, Roald de Vries wrote:


Hi all,

I have two objects that should both be able to alter a shared  
float. So

i need something like a mutable float object, or a float reference
object. Does anybody know if something like that exists? I know  
it's not

hard to build, but I have a feeling that there should be a standard
solution to it.


One standard solution would be to wrap the float in a class as an
attribute.


I think the nicest solution is to do this with a wrapping descriptor  
class.


Thanks for your input!

Cheers, Roald

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


Re: tarfile and progress information

2010-07-14 Thread Lars Gustäbel
On Wed, Jul 07, 2010 at 11:23:22AM -0400, Nathan Huesken wrote:
> I am packing large files with tarfile. Is there any way I can get
> progress information while packing?

There is no builtin way in tarfile, but there are several possible solutions:

1. Replace the tarfile.copyfileobj() function that is used to copy the files'
contents to the archive with your own.

2. Subclass the TarFile class, replace the addfile() method, and wrap every
file object argument into an object that triggers a callback function for each
block of data being read:

"""
import sys
import os
import tarfile


class FileProxy(object):

def __init__(self, fobj, callback):
self.fobj = fobj
self.callback = callback
self.size = os.fstat(self.fobj.fileno()).st_size

def read(self, size):
self.callback(self.fobj.tell(), self.size)
return self.fobj.read(size)

def close(self):
self.callback(self.size, self.size)
self.fobj.close()


class MyTarFile(tarfile.TarFile):

def __init__(self, *args, **kwargs):
self.callback = kwargs.pop("callback")
super(MyTarFile, self).__init__(*args, **kwargs)

def addfile(self, tarinfo, fileobj=None):
if self.callback is not None and fileobj is not None:
fileobj = FileProxy(fileobj, self.callback)
super(MyTarFile, self).addfile(tarinfo, fileobj)


def callback(processed, total):
sys.stderr.write("%.1f%% \r" % (processed / float(total) * 100))


tar = MyTarFile.open("test.tar.gz", "w:gz", callback=callback)
tar.add("...")
tar.close()
"""

3. If you have a defined set of files to add you can do something like this:

tar = tarfile.open("test.tar.gz", "w:gz")
for filename in filenames:
tarinfo = tar.gettarinfo(filename)
fobj = FileProxy(open(filename, "rb"), callback)
tar.addfile(tarinfo, fobj)
fobj.close()


I hope this helps.

Regards,

-- 
Lars Gustäbel
l...@gustaebel.de

The power of accurate observation is called cynicism
by those who have not got it.
(George Bernard Shaw)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floatref

2010-07-14 Thread Roald de Vries

On Jul 14, 2010, at 3:53 AM, Steven D'Aprano wrote:

On Tue, 13 Jul 2010 19:26:34 +0200, Roald de Vries wrote:


Hi all,

I have two objects that should both be able to alter a shared  
float. So

i need something like a mutable float object, or a float reference
object. Does anybody know if something like that exists? I know  
it's not

hard to build, but I have a feeling that there should be a standard
solution to it.



One standard solution would be to wrap the float in a class as an
attribute.


E.g.: a class FloatWrapper with a get and set method.
Advantages: transparent, easy to implement
Disadvantages: for 'f = FloatWrapper' you have to use 'f.set(1.0)'  
instead of 'f = 1.0', which reads less easily (I think), and a mistake  
like assigning with 'f = 1.0' is easily made.



Another is to put it in a list:

myvalue = [3.1415]
pi = myvalue
myvalue[0] = 3.0
assert pi[0] == 3.0


I thought about something like that, but it's a bit misleading,  
because the value is actually a list.



An even better solution is to avoid the idiom of shared state in the
first place. Whenever people say "I need shared data", the chances are
very good that they don't *need* it at all, but merely *want* it  
because

that's the idiom they're used to.


I want to simulate a distributed algorithm, in which components can  
only communicate through shared state.


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


Re: floatref

2010-07-14 Thread Roald de Vries

On Jul 14, 2010, at 1:26 AM, Gary Herron wrote:

On 07/13/2010 03:02 PM, Roald de Vries wrote:

Hi Gary,

On Jul 13, 2010, at 8:54 PM, Gary Herron wrote:

On 07/13/2010 10:26 AM, Roald de Vries wrote:

Hi all,

I have two objects that should both be able to alter a shared  
float.
So i need something like a mutable float object, or a float  
reference
object. Does anybody know if something like that exists? I know  
it's

not hard to build, but I have a feeling that there should be a
standard solution to it.

Roald


Huh? I must be missing something here. Isn't this what you use a
variable for:


Maybe I didn't explain well:

>>> shared_var = 1.0
>>> x.var = shared_var
>>> y.var = shared_var
>>> x.var = 2.0
>>> y.var
1.0

I wanted y.var and x.var to point to the same value, so that always
x.var == y.var. So that the last line becomes:

>>> y.var
2.0

Cheers, Roald


Please keep responses and further discussions on
 list.python-l...@python.org
instead of using private emails.


Sorry.

Python does not have pointers, so if I take your wording"y.var and  
x.var to point to the same value"  literally, then the answer is NO   
Python does not do that.


Maybe I should have put it between quotes, but I used the words  
'mutable float' and 'float reference' in the original post, and this  
was only an attempt to clarify better.


However, Python does have references all over the place, so you can  
achieve something similar in many ways.


I know, I just wondered if there is a *standard* solution.

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