Re: Lists and Sublists

2007-10-24 Thread Amit Khemka
On 10/24/07, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> dineshv a écrit :
> > We have a list of N (>2,000) keywords (of datatype string).  Each of
> > the N keywords has associated with it a list of names of varying
> > numbers.  For example, keyword(1) will have a list of L1 names
> > associated with it, keyword(2) will have a list of L2 names associated
> > with it and so on with L1 not equal to L2 etc.  All keywords and names
> > are immutable.
> >
> > Given a keyword(n) , we want to get hold of the associated list of Ln
> > names.
> >
> > At anytime, we also want to add keywords to the list of N keywords,
> > and to any of the associated Ln lists - both of which will grow to
> > very large sizes.
> >
> > The data will be read into the Python data structure(s) from disk
> > storage.
> >
> > I am struggling to work out what is the ideal Python data structure
> > for the above.  Any help would be greatly appreciated.
>
> keywords = {}
> keywords['python'] = ['fun', 'simple']
> keywords['another_p_language'] = ['line noise', 'cryptic']
> keywords['python'].append('readable')
>

To add you may want to have a look at "shelve" module , in case you
want to store this object to a file. It can be useful if the data set
is large and does not change frequently and you would want to save on
some startup time .

cheers,

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


Re: Python - why don't this script work?

2007-10-24 Thread Ohmster
[EMAIL PROTECTED] wrote in news:1193127053.740024.144730
@q5g2000prf.googlegroups.com:

> 
> Do note that the reason you may not see images is that the website
> has, '''correctly''', identified your program as an automated bot and
> blocked it access to things...

Probably so, I did not get anything, even with all of that flurry of 
activity, the results were 0 images. :(

-- 
~Ohmster | ohmster /a/t/ ohmster dot com
Put "messageforohmster" in message body
(That is Message Body, not Subject!)
to pass my spam filter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: japanese encoding iso-2022-jp in python vs. perl

2007-10-24 Thread Leo Kislov
On Oct 23, 3:37 am, kettle <[EMAIL PROTECTED]> wrote:
> Hi,
>   I am rather new to python, and am currently struggling with some
> encoding issues.  I have some utf-8-encoded text which I need to
> encode as iso-2022-jp before sending it out to the world. I am using
> python's encode functions:
> --
>  var = var.encode("iso-2022-jp", "replace")
>  print var
> --
>
>  I am using the 'replace' argument because there seem to be a couple
> of utf-8 japanese characters which python can't correctly convert to
> iso-2022-jp.  The output looks like this:
> ↓東京???日比谷線?北千住行
>
>  However if use perl's encode module to re-encode the exact same bit
> of text:
> --
>  $var = encode("iso-2022-jp", decode("utf8", $var))
>  print $var
> --
>
>  I get proper output (no unsightly question-marks):
> ↓東京メトロ日比谷線・北千住行
>
> So, what's the deal?  

Thanks that I have my crystal ball working. I can see clearly that the
forth
character of the input is 'HALFWIDTH KATAKANA LETTER ME' (U+FF92)
which is
not present in ISO-2022-JP as defined by RFC 1468 so python converts
it into
question mark as you requested. Meanwhile perl as usual is trying to
guess what
you want and silently converts that character into 'KATAKANA LETTER
ME' (U+30E1)
which is present in ISO-2022-JP.

> Why can't python properly encode some of these
> characters?

Because "Explicit is better than implicit". Do you care about
roundtripping?
Do you care about width of characters? What about full-width " (U
+FF02)? Python
doesn't know answers to these questions so it doesn't do anything with
your
input. You have to do it yourself. Assuming you don't care about
roundtripping
and width here is an example demonstrating how to deal with narrow
characters:

from unicodedata import normalize
iso2022_squeezing = dict((i, normalize('NFKC',unichr(i))) for i in
range(0xFF61,0xFFE0))
print repr(u'\uFF92'.translate(iso2022_squeezing))

It prints u'\u30e1'. Feel free to ask questions if something is not
clear.

Note, this is just an example, I *don't* claim it does what you want
for any character
in FF61-FFDF range. You may want to carefully review the whole unicode
block:
http://www.unicode.org/charts/PDF/UFF00.pdf

  -- Leo.

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

Re: Iteration for Factorials

2007-10-24 Thread Hendrik van Rooyen
"Jon Ribbens"  wrote:


> On 2007-10-23, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> > Yuk.  Reminds me of one of the Hitachi processors that
> > has a single depth hardware "link register" that tells a 
> > subroutine where it was called from.
> 
> That's how ARM processors work, and they're everywhere these days.

Yes, worse luck.  The market has chosen...

- Hendrik

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


Re: Speed of Nested Functions & Lambda Expressions

2007-10-24 Thread Duncan Booth
beginner <[EMAIL PROTECTED]> wrote:

> It is really convenient to use nested functions and lambda
> expressions. What I'd like to know is if Python compiles fn_inner()
> only once and change the binding of v every time fn_outer() is called
> or if Python compile and generate a new function object every time. If
> it is the latter, will there be a huge performance hit? Would someone
> give some hint about how exactly Python does this internally?

You can use Python's bytecode disassembler to see what actually gets 
executed here:

>>> def fn_outer(v):
a=v*2
def fn_inner():
print "V:%d,%d" % (v,a)

fn_inner()


>>> import dis
>>> dis.dis(fn_outer)
  2   0 LOAD_DEREF   1 (v)
  3 LOAD_CONST   1 (2)
  6 BINARY_MULTIPLY 
  7 STORE_DEREF  0 (a)

  3  10 LOAD_CLOSURE 0 (a)
 13 LOAD_CLOSURE 1 (v)
 16 BUILD_TUPLE  2
 19 LOAD_CONST   2 (", line 3>)
 22 MAKE_CLOSURE 0
 25 STORE_FAST   1 (fn_inner)

  6  28 LOAD_FAST1 (fn_inner)
 31 CALL_FUNCTION0
 34 POP_TOP 
 35 LOAD_CONST   0 (None)
 38 RETURN_VALUE
>>> 

When you execute the 'def' statement, the two scoped variables a and v 
are built into a tuple on the stack, the compiled code object for the 
inner function is also pushed onto the stack and then the function is 
created by the 'MAKE_CLOSURE' instruction. This is then stored in a 
local variable (STORE_FAST) which is then loaded and called.

So the function definition is pretty fast, BUT notice how fn_inner is 
referenced by STORE_FAST/LOAD_FAST whereas a and v are referenced by 
LOAD_DEREF/STORE_DEREF and LOAD_CLOSURE.

The code for fn_inner also uses LOAD_DEREF to get at the scoped 
variables:

  4   0 LOAD_CONST   1 ('V:%d,%d')
  3 LOAD_DEREF   1 (v)
  6 LOAD_DEREF   0 (a)
  9 BUILD_TUPLE  2
 12 BINARY_MODULO   
 13 PRINT_ITEM  
 14 PRINT_NEWLINE   
 15 LOAD_CONST   0 (None)
 18 RETURN_VALUE

(its a bit harder to disassemble that one, I stuck a call to dis.dis 
inside fn_outer to get that)

If you do some timings you'll find that LOAD_DEREF/STORE_DEREF are 
rather slower than LOAD_FAST/STORE_FAST, so while the overhead for 
creating the function is minimal you could find that if you access the 
variables a lot (even in fn_outer) there may be a measurable slow-down.

If timings show that it is a code hotspot then you might find it better 
to nest the function but pass any required values in as parameters (but 
if you don't have evidence for this just write whatever is clearest).
-- 
http://mail.python.org/mailman/listinfo/python-list


"realtime" fs mirror application (backup, Python and Linux inotify)

2007-10-24 Thread Roc Zhou
Recently I started an open source project "cutils" on the sourceforge:
   http://sourceforge.net/projects/crablfs/

The document can be found at:
http://crablfs.sourceforge.net/#ru_data_man

This project's mirrord/fs_mirror tool is a near realtime file system
mirroring application across 2 or more hosts, something like MySQL's
replication, but it's for the file system especially with a great
amountof small files, such as the php scripts and images of a website
or the
(vitual) websites.

There are several ways to use this tool. The simplest is to mirror a
host's file system to another host for backup, and use the rotate
function(in the future version) or rotate scripts to get a daily or
hourly snapshot with the hard link.

Or futhur more, you can use it this way:
  This graph should be displayed with monospaced fonts:

  +--+
  |  worker  | -[mirrord] ---\
  +--+   |
 ..  |
 |
  +--+   |
  |  worker  | -[mirrord] ---\
  +--+   |
 V
[fs_mirror]
 |
  +--+  +--+
  |  worker  | -[mirrord] --->  |  backup  |
  +--+  +--+
   | |
  [take_over]|
   | |
   V |
  +--+   |
  |  rescue  | <--- NFS
  +--+

This is the multi to one backup, which is cost efficient. If one of
the worker hosts fails, you can subsitute the failed worker with the
rescue host, with the aid of any high available method, such as
heartbeat
project. By this way, you can use 1 or 2 hosts to support the HA of
more than 3 servers.

Or you can also use it as an IDS(Intrusion Detection System) like a
realtime "tripware", or you can make a mirror chain that a host B
mirrors from A and be mirrored by C, etc ... I will also try to
research a way
to use it as a distributed implemetation with one write and multi-read
model.

mirrord/fs_mirror makes use of inotify, which is a function afforded
by the recent Linux (from 2.6.12). It is a counterpart of FAM, since
Linux FAM has stopped so long.

Now it works for me, on a RHEL4 system and the LFS 6.2, I hope this
tool can be useful to you too.

Thanks.

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


Re: basic web auth and verification

2007-10-24 Thread Ralf Schönian
[EMAIL PROTECTED] schrieb:
> Trying to figure out how to add login verfication. I believe it is
> logging me in, but theres no way to really tell..any ideas? or
> tutorials out there that can exaplain this to me?
> 
> Thanks
> 
> import urllib,urllib2,cookielib
> 
> passlst = open(passfile, 'r').readlines()
> url="http://somesite";
> cj = cookielib.LWPCookieJar()
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
> urllib2.install_opener(opener)
> TheForm = urllib.urlencode({"username":"myid","password":"mypas"})
> request = urllib2.Request(url, TheForm)
> result = urllib2.urlopen(request)
> html=result.read()
> result.close()
> 

I had the same trouble. There was a redirect after login a had to 
follow. Look at the following code.

 def login(self):
 ''' Log into web site. '''

 self._br.set_handle_redirect(True)
 cj = CookieJar()
 self._br.set_cookiejar(cj)
 self._br.open(Config.urlLogin)
 self._br.select_form(name='login')

 self._br['session_key'] = Config.username
 self._br['session_password'] = Config.password
 response=self._br.submit()
 self._br.set_response(response)
 for link in self._br.links(url_regex="www.somesite.com"):
 self._br.follow_link(link)
 if 'Sign In' in self._br.title():
 raise ValueError('Wrong password')


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


Re: japanese encoding iso-2022-jp in python vs. perl

2007-10-24 Thread kettle
Thanks Leo, and everyone else, these were very helpful replies.  The
issue was exactly as Leo described, and I apologize for not being
aware of it, and thus not quite reporting it correctly.

At the moment I don't care about round-tripping between half-width and
full-width kana, rather I need only be able to rely on any particular
kana character be translated correctly to its half-width or full-width
equivalent, and I need the Japanese I send out to be readable.

I appreciate the 'implicit versus explicit' point, and have read about
it in a few different python mailing lists.  In this instance it seems
that perl perhaps ought to flash a warning notification regarding what
it is doing, but as this conversion between half-width and full-width
characters is by far the most logical one available, it also seems
reasonable that python might perhaps include such capabilities by
default, just as it currently includes the 'replace' option for
mapping missed characters generically to '?'.

I still haven't worked out the entire mapping routine, but Leo's hint
is probably sufficient to get it working with a bit more effort.

Again, thanks for the help.

-Joe

> Thanks that I have my crystal ball working. I can see clearly that the
> forth
> character of the input is 'HALFWIDTH KATAKANA LETTER ME' (U+FF92)
> which is
> not present in ISO-2022-JP as defined by RFC 1468 so python converts
> it into
> question mark as you requested. Meanwhile perl as usual is trying to
> guess what
> you want and silently converts that character into 'KATAKANA LETTER
> ME' (U+30E1)
> which is present in ISO-2022-JP.
>
> > Why can't python properly encode some of these
> > characters?
>
> Because "Explicit is better than implicit". Do you care about
> roundtripping?
> Do you care about width of characters? What about full-width " (U
> +FF02)? Python
> doesn't know answers to these questions so it doesn't do anything with
> your
> input. You have to do it yourself. Assuming you don't care about
> roundtripping
> and width here is an example demonstrating how to deal with narrow
> characters:
>
> from unicodedata import normalize
> iso2022_squeezing = dict((i, normalize('NFKC',unichr(i))) for i in
> range(0xFF61,0xFFE0))
> print repr(u'\uFF92'.translate(iso2022_squeezing))
>
> It prints u'\u30e1'. Feel free to ask questions if something is not
> clear.
>
> Note, this is just an example, I *don't* claim it does what you want
> for any character
> in FF61-FFDF range. You may want to carefully review the whole unicode
> block:http://www.unicode.org/charts/PDF/UFF00.pdf
>
>   -- Leo.


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


trying to remember how to do inline code "testing"

2007-10-24 Thread Alex Hunsley
I can remember Python having a feature which allowed you to add some 
simple tests to your code, something like adding console output to your 
actual python script, like so:


 >>> 1+1
2
 >>> 2*7
14


... then python would actually run these queries and check that the 
expected results occurred.
I can't find the docs for this feauture anywhere, but I'm certain I 
didn't imagine this one!
Can anyone give me a reference?

thanks,
Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to remember how to do inline code "testing"

2007-10-24 Thread Diez B. Roggisch
Alex Hunsley wrote:

> I can remember Python having a feature which allowed you to add some
> simple tests to your code, something like adding console output to your
> actual python script, like so:
> 
> 
>  >>> 1+1
> 2
>  >>> 2*7
> 14
> 
> 
> ... then python would actually run these queries and check that the
> expected results occurred.
> I can't find the docs for this feauture anywhere, but I'm certain I
> didn't imagine this one!
> Can anyone give me a reference?

http://docs.python.org/lib/module-doctest.html

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


Re: trying to remember how to do inline code "testing"

2007-10-24 Thread Alex Hunsley
Diez B. Roggisch wrote:
> Alex Hunsley wrote:
> 
>> I can remember Python having a feature which allowed you to add some
>> simple tests to your code, something like adding console output to your
>> actual python script, like so:
>>
>>
>>  >>> 1+1
>> 2
>>  >>> 2*7
>> 14
>>
>>
>> ... then python would actually run these queries and check that the
>> expected results occurred.
>> I can't find the docs for this feauture anywhere, but I'm certain I
>> didn't imagine this one!
>> Can anyone give me a reference?
> 
> http://docs.python.org/lib/module-doctest.html
 >
 > Diez

Brilliant, thanks for that Diez!
Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


building a linux executable

2007-10-24 Thread Prateek
Hello,

I'm trying to package my python program into a linux executable using
cx_freeze. The goal is that the user should require python on their
system.

I've managed to make the binaries on Fedora Core 6 and they run fine.
However, when I move to Ubuntu (tested on Ubuntu Server 7.04 and
xUbuntu Desktop 7.04), the program fails to run with the following
error:

ImportError: no module named _md5

_md5 being imported by the hashlib module because the import of
_hashlib.so failed.

When I try to import the _hashlib module manually, I see that it
cannot find libssl.so.6 (The _hashlib module in the standard python
installation which came with Ubuntu works just fine). If I manually
copy the libssl.so.6 file from FC6 (its really a symlink pointing to
libssl.so.0.9.8b) to Ubuntu and make the symlink in /lib, it works
fine (the next error is related to libcrypto, libxslt and libjpeg (i'm
also using libxml, libxsl and PIL in my application).

I've scoured the net and it seems that _hashlib.so is dynamically
linked to libssl which is not being "integrated" into the build by
cx_Freeze. Similarly, there are other files with the same problem.

Does anyone have any idea how to make cx_Freeze make a linux
executable which is portable across *nix distros?

Thanks in advance,
-Prateek Sureka

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


Re: python 2.5 scripting in vim on windows: subprocess problem

2007-10-24 Thread Dmitry Teslenko
On 22/10/2007, Andy Kittner <[EMAIL PROTECTED]> wrote:
> >> Are you running this on vim or gvim? If you are running on gvim, my
> >> guess is that the handles that you are passing are not valid. In
> >> either case, try creating explicit handles that are valid (such as for
> >> /dev/null) and create the process with these handles.
> Just as a side note: my vim was a gvim-7.1.140 with dynamic python
> support, so it doesn't look like a general problem.
I've also tried *-1-140 from cream's sourceforge website and it works
just like my custom-built one.

> > I'm passing hadles that I get from subprocess.Popen. Just passing
> > command to Popen constructor and using his handles to read data. No
> > other handle-manipulations.
> When exactly does it throw the exception? Directly on creation of the
> Popen object, or when you try to read stdout?
It throws exception on subprocess.Popen object instantiation.
os.system() works fine but I want Popen functionality.
-- 
http://mail.python.org/mailman/listinfo/python-list


Extracting/finding strings from a list

2007-10-24 Thread neillee
-- 
http://mail.python.org/mailman/listinfo/python-list

Better writing in python

2007-10-24 Thread Alexandre Badez
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
  if arg is True:
lMandatory.append(arg)
  else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...

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


Re: building a linux executable

2007-10-24 Thread Bjoern Schliessmann
Prateek wrote:

> I'm trying to package my python program into a linux executable
> using cx_freeze. The goal is that the user should require python
> on their system.
> 
> I've managed to make the binaries on Fedora Core 6 and they run
> fine. However, when I move to Ubuntu (tested on Ubuntu Server 7.04
> and xUbuntu Desktop 7.04), the program fails to run with the
> following error:

I'm sorry I cannot help, but how many linux distros have no python
installed or no packages of it?

Regards,


Björn
 
-- 
BOFH excuse #151:

Some one needed the powerstrip, so they pulled the switch plug.

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


Re: building a linux executable

2007-10-24 Thread Paul Boddie
On 24 Okt, 14:20, Bjoern Schliessmann  wrote:
>
> I'm sorry I cannot help, but how many linux distros have no python
> installed or no packages of it?

It's not usually the absence of Python that's the problem. What if
your application uses various extension modules which in turn rely on
various libraries (of the .so or .a kind)? It may be more convenient
to bundle all these libraries instead of working out the package
dependencies for all the target distributions, even if you know them
all.

Paul

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


Re: name space problem

2007-10-24 Thread Bruno Desthuilliers
BBands a écrit :
> On Oct 23, 4:20 pm, [EMAIL PROTECTED] wrote:
>> Hello. Indeed the doStuff function in the doStuff module can't do 'a.b
>> = 0' (the double dot was just a typo, right?)
> 
> Yes.
> 
>> because it doesn't know anything about an object named a.
> 
> I was trying to understand why it worked when written in, but not when
> included.

because it's *not* "included" ? Python's imports are not includes, and 
the notion of "global" namespace in Python really means module's namespace.

>> I think the right solution would be not to use 'a' as a global
>> variable, but rather to pass it as an explicit parameter to the
>> function.
> 
> Does doing this make a copy of a?

No. Python nevers copy anything unless very explicitelly asked to. But 
remember that names are locals to their namespaces, so that rebinding 
'a' in doStuff won't affect the object originally bound to 'a' (mutating 
the object bound to 'a' will of course work as expected).

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


Re: Python Windows Installation

2007-10-24 Thread Bjoern Schliessmann
TheFlyingDutchman wrote:
> I am trying to install Python 2.5 on Windows XP. It installs into
> the root directory on C:\ instead of C:\Python25 

BTW, what exactly is behind the idea to install to c:\python25
instead of %PROGRAMFILES%\python25?

Regards,


Björn

-- 
BOFH excuse #339:

manager in the cable duct

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


Re: Better writing in python

2007-10-24 Thread J. Clifford Dyer
On Wed, Oct 24, 2007 at 12:09:40PM -, Alexandre Badez wrote regarding 
Better writing in python:
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
> 
> I think there is a better way, but I can't see how...
> 

I assume cls.dArguments is a dict, correct?

`for arg in cls.dArguments` takes each *key* for cls.dArguments and assigns it 
to arg, so the line 'if arg is True' will test the truth value of each key.  I 
assume (you haven't shown the details here) that your dict looks like this:

cls.dArguments = { 'a': True, 'b': False, 'c': True, 'd': False, '': True, 0: 
False }

and you want your for loop to do this:

lMandatory == [ 'a', 'c', '' ]
lOptional == [ 'b', 'd', 0 ]

in fact, since it's testing the truth value of the keys, not the values, you 
will get this:

lMandatory == [ 'a', 'b', 'c', 'd' ]
lOptional == [ '', 0 ]

In no particular order, of course.

Also, `if x is True:` should be written as `if x:`

Actually, come to think of it, what I said above is false, because the string 
'a' *is not* the boolean value True, per se: it is *equal to* True.  So if you 
change `if x is True:` to `if x == True:`  then everything I said above holds 
true, including that you should change `if x == True:` to `if x:`

As it stands, the only key in your dict that has a snowball's chance in key 
largo of being marked as mandatory is the boolean value True itself.

Cheers,
Cliff

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


Re: Better writing in python

2007-10-24 Thread Marc 'BlackJack' Rintsch
On Wed, 24 Oct 2007 12:09:40 +, Alexandre Badez wrote:

> I'm just wondering, if I could write a in a "better" way this code
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
> 
> I think there is a better way, but I can't see how...

Drop the prefixes. `l` is for list?  `d` is for what!?  Can't be
dictionary because the code doesn't make much sense.

Where is `cls` coming from?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better writing in python

2007-10-24 Thread Paul Hankin
On Oct 24, 1:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

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


Re: Better writing in python

2007-10-24 Thread Paul Hankin
On Oct 24, 1:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

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


Re: Better writing in python

2007-10-24 Thread Paul Hankin
On Oct 24, 1:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

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


Re: Python Windows Installation

2007-10-24 Thread kyosohma
On Oct 24, 7:27 am, Bjoern Schliessmann  wrote:
> TheFlyingDutchman wrote:
> > I am trying to install Python 2.5 on Windows XP. It installs into
> > the root directory on C:\ instead of C:\Python25
>
> BTW, what exactly is behind the idea to install to c:\python25
> instead of %PROGRAMFILES%\python25?
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #339:
>
> manager in the cable duct

That's just the default place that Python wants to install to. I
suppose one reason for this is because DOS is stupid when it comes to
spaces in paths. Other than that, I don't know why the Python
developers chose that as the default location.

Mike

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

Re: Better writing in python

2007-10-24 Thread kyosohma
On Oct 24, 7:09 am, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

You might look into list comprehensions. You could probably do this
with two of them:


# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional  = [arg for arg in cls.dArguments if arg is False]


Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off. See the following links for
more information:

http://www.secnetix.de/olli/Python/list_comprehensions.hawk
http://docs.python.org/tut/node7.html

Mike

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


Re: Better writing in python

2007-10-24 Thread Alexandre Badez
On 10/24/07, J. Clifford Dyer <[EMAIL PROTECTED]> wrote:
>
> On Wed, Oct 24, 2007 at 12:09:40PM -, Alexandre Badez wrote regarding
> Better writing in python:
> >
> > lMandatory = []
> > lOptional = []
> > for arg in cls.dArguments:
> >   if arg is True:
> > lMandatory.append(arg)
> >   else:
> > lOptional.append(arg)
> > return (lMandatory, lOptional)
> >
> > I think there is a better way, but I can't see how...
> >
>
> I assume cls.dArguments is a dict, correct?
>
> `for arg in cls.dArguments` takes each *key* for cls.dArguments and
> assigns it to arg, so the line 'if arg is True' will test the truth value of
> each key.  I assume (you haven't shown the details here) that your dict
> looks like this:
>
> cls.dArguments = { 'a': True, 'b': False, 'c': True, 'd': False, '': True,
> 0: False }
>
> and you want your for loop to do this:
>
> lMandatory == [ 'a', 'c', '' ]
> lOptional == [ 'b', 'd', 0 ]
>
> in fact, since it's testing the truth value of the keys, not the values,
> you will get this:
>
> lMandatory == [ 'a', 'b', 'c', 'd' ]
> lOptional == [ '', 0 ]
>
> In no particular order, of course.
>
> Also, `if x is True:` should be written as `if x:`
>
> Actually, come to think of it, what I said above is false, because the
> string 'a' *is not* the boolean value True, per se: it is *equal to*
> True.  So if you change `if x is True:` to `if x == True:`  then everything
> I said above holds true, including that you should change `if x == True:` to
> `if x:`
>
> As it stands, the only key in your dict that has a snowball's chance in
> key largo of being marked as mandatory is the boolean value True itself.
>
> Cheers,
> Cliff
>

Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
  'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
  }
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
  if cls.dArguments[arg]['mandatory']:
lMandatory.append(arg)
  else:
lOptional.append(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

-- 
Alex
http://alexandre.badez.googlepages.com/
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Better writing in python

2007-10-24 Thread Neil Cerutti
On 2007-10-24, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this
> code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

I don't think there's much improvement to be made. What are your
particular concerns? Is it too slow? Too verbose? Does it not
work correctly?

It appears to be an application of itertools.groupby, but that'll
almost certainly be less efficient. To use groupby, you have to
sort by your predicate, and build lists to save results. Your for
loop avoids the sorting.

Here's some instrumentality for ya:

from itertools import groupby
from operator import truth
from collections import defaultdict

result = defaultdict(list)
for k, g in groupby(sorted(cls.dArguments, key=truth), truth):
  result[k].extend(g)

I like your initial attempt better.

P.S. I didn't realize until working out this example that extend
could consume an iterator.

-- 
Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better writing in python

2007-10-24 Thread Harold Fellermann
Hi Alexandre,

On Oct 24, 2:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this code

Please tell us, what it is you want to achieve. And give us some
context
for this function.

> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)

This snippet will seperate d.Arguments into two lists: one that
holds all elements that are references to True(!) and another list
that holds the rest. The condition 'if args is True' will only
be hold if arg actually _is_ the object _True_. This is probably
not what you want. Apart from that, you might go with

lMandatory = [ arg for arg in cls.dArguments if condition() ]
lOptional = [ arg for arg in cls.dArguments if not condition() ]

the second line could be rewritten

lOptional = list(set(cls.dArguments)-set(lMandatory))

If lMandatory and lOptional do not need to be lists, you can also
write

lMandatory = set(arg for arg in cls.dArguments if condition())
lOptional =  set(cls.dArguments) - lMandatory

But please, give us some more context of what you want to do.

- harold -

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


Re: transforming list

2007-10-24 Thread Scott David Daniels
sandipm wrote:
> hi james,
>   this is one implementation using python dictionaries.
> 
> report ={}
> for row in data:
> if not row[0] in report:
I'd use:
   if row[0] not in report:
> report[row[0]] = [row[0], row[1], 0, 0, 0, 0, 0, 0, 0, 0, 0,
> 0, 0, 0]
> if row[2]:
> report[row[0]][row[2]+1] = row[3]
> reports = report.values()

or even:
 report ={}
 for code, team, game, bet in data:
 if code not in report:
 report[code] = [code, team, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0]
 else:
 assert report[code][1] == team
 if game:
 report[code][game + 1] = bet
 reports = report.values()


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


ANNOUNCE: NUCULAR 0.1 Fielded Full Text Indexing [BETA]

2007-10-24 Thread aaron . watters
ANNOUNCE: NUCULAR 0.1 Fielded Full Text Indexing [BETA]

Nucular is a system for creating disk based full text indices
for fielded data. It can be accessed via a Python API
or via a suite of command line interfaces, and an example
Web based archive browser.

The 0.1 release adds a bunch of features and also improves
the internal data structures significantly.  Most importantly
the cosmetics of the example web interface isn't as
horrible as it was before :).

I'm calling it a beta because I think the core is pretty
stable and near future releases are likely to provide
enhancements or minor bugfixes rather than major changes.

Read more and download at:
   http://nucular.sourceforge.net

ONLINE DEMOS:

Python source search:
 http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=malodorous+parrot
Mondial geographic text search:
 http://www.xfeedme.com/nucular/mondial.py/go?attr_name=ono
Gutenberg book search:
 http://www.xfeedme.com/nucular/gut.py/go?attr_Comments=immoral+english

BACKGROUND:

Nucular is intended to help store and retrieve
searchable information in a manner somewhat similar
to the way that "www.hotjobs.com" stores and
retrieves job descriptions, for example.

Nucular archives fielded documents and retrieves them
based on field value, field prefix, field word prefix,
or full text word prefix, field range, or combinations
of these.

Features:

 -- Nucular is very light weight. Updates and accesses
do not require any server process or other system
support such as shared memory locking.

 -- Nucular supports concurrency. Arbitrary concurrent
updates and accesses by multiple processes or threads
are supported, with no possible locking issues.

 -- Nucular indexes and retrieves large collections quickly.

I hope you like.
   -- Aaron Watters

===
Q: Why is a giraffe's neck so long?
A: Because its head is so far from its body.

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


Re: Better writing in python

2007-10-24 Thread Duncan Booth
Alexandre Badez <[EMAIL PROTECTED]> wrote:

> Thanks for your try Cliff, I was very confused :P
> More over I made some mistake when I post (to make it easiest).
> 
> Here is my real code:
> 
> with
> dArguments = {
>   'argName' : {
> 'mandatory' : bool, # True or False
> [...], # other field we do not care here
>   }
> }
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if cls.dArguments[arg]['mandatory']:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
> 
> So, as you see, we agree each other about "if bool" or "if bool is
> True" ;)
> 
> So, my question was how to give it a better 'python like' look ?
> Any idea ?
> 
> 

For a 'python like' look lose the Hungarian notation (even Microsoft 
have largely stopped using it), increase the indentation to 4 spaces, 
and also get rid of the spurious parentheses around the result. 
Otherwise it is fine: clear and to the point.

If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
(m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
action[bool(cls.dArguments[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better writing in python

2007-10-24 Thread Alexandre Badez
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
  'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
  }
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
  if cls.dArguments[arg]['mandatory']:
lMandatory.append(arg)
  else:
lOptional.append(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

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


Re: Better writing in python

2007-10-24 Thread kyosohma
On Oct 24, 8:02 am, [EMAIL PROTECTED] wrote:
> On Oct 24, 7:09 am, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > I'm just wondering, if I could write a in a "better" way this code
>
> > lMandatory = []
> > lOptional = []
> > for arg in cls.dArguments:
> >   if arg is True:
> > lMandatory.append(arg)
> >   else:
> > lOptional.append(arg)
> > return (lMandatory, lOptional)
>
> > I think there is a better way, but I can't see how...
>
> You might look into list comprehensions. You could probably do this
> with two of them:
>
> 
> # completely untested
> lMandatory = [arg for arg in cls.dArguments if arg is True]
> lOptional  = [arg for arg in cls.dArguments if arg is False]
> 
>
> Something like that. I'm not the best with list comprehensions, so I
> may have the syntax just slightly off. See the following links for
> more information:
>
> http://www.secnetix.de/olli/Python/list_comprehensions.hawkhttp://docs.python.org/tut/node7.html
>
> Mike

After reading the others replies, it makes me think that I'm barking
up the wrong tree. Ah well.

Mike

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


Re: Better writing in python

2007-10-24 Thread A.T.Hofkamp
> On 2007-10-24, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> I'm just wondering, if I could write a in a "better" way this
> code
>
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)
>
> I think there is a better way, but I can't see how...

You can do it shorter, not sure that it also qualifies as better

d = { True : [] , False : [] }
for arg in cls.arguments:
  d[arg == True].append(arg)

return d[True], d[False]

One potential problem here is that 'arg == True' may not be the same as 'if
arg:'. I couldn't come up with a better equivalent expression, maybe one of the
other readers knows more about this?


Albert

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


Parameters in context manager's __enter__ method?

2007-10-24 Thread skip

I am working on a file locking class which I'd like to work with Python
2.5's context managers.  The acquire method takes an optional timeout
argument:

class FileLock:
...
def acquire(self, timeout=None):
...

def __enter__(self):
self.acquire()
return self

Can that optional timeout be somehow accommodated by the with statement?
(I'm thinking no, which may not be a big shortcoming anyway.)

Thx,

Skip


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


Re: Is this a wx bug?

2007-10-24 Thread kyosohma
On Oct 23, 7:06 pm, Chris Carlen <[EMAIL PROTECTED]>
wrote:
> Hi:
>
> #!/usr/bin/env python
>
> """From listing 3.3 in 'wxPython in Action'
> Demonstrates that something funny happens when you click&hold in the
> frame, then drag the mouse over the button window.  The
> wx.EVT_ENTER_WINDOW event is missed.  The wx.EVT_LEAVE_WINDOW event is
> NOT missed when you click&hold the mouse button over the button, and
> leave the button window."""
>
> import wx
>
> class MouseEventFrame(wx.Frame):
>  def __init__(self, parent, id):
>  wx.Frame.__init__(self, parent, id, title="Listing 3.3",
> size=(300, 100))
>  self.panel = wx.Panel(self)
>  self.button = wx.Button(self.panel, label="Not over", pos=(100,
> 15))
>  self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.button)
>  self.button.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
>  self.button.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
>
>  # This is not critical to demonstrating the 'bug', but just provides
>  # feedback that the wx.EVT_BUTTON events are working correctly
>  # in relation to entering/leaving the button window.
>  def OnButtonClick(self, event):
>  if self.panel.GetBackgroundColour() == "Green":
>  self.panel.SetBackgroundColour("Red")
>  else: self.panel.SetBackgroundColour("Green")
>  self.panel.Refresh()
>
>  def OnEnterWindow(self, event):
>  self.button.SetLabel("Over")
>  event.Skip()
>
>  def OnLeaveWindow(self, event):
>  self.button.SetLabel("Not over")
>  event.Skip()
>
> if __name__ == '__main__':
>  app = wx.PySimpleApp()
>  frame = MouseEventFrame(None, id=-1)
>  frame.Show()
>  app.MainLoop()
>
> --
> Good day!
>
> 
> Christopher R. Carlen
> Principal Laser&Electronics Technologist
> Sandia National Laboratories CA USA
> [EMAIL PROTECTED]
> NOTE, delete texts: "RemoveThis" and
> "BOGUS" from email address to reply.

I cannot replicate this issue. It works correctly for me with Python
2.4, wxPython 2.8.4.2 (msw-unicode) on Windows XP SP2.

What version of Python/wxPython are you using? OS? It may just be that
you need to upgrade your wxPython or it's a bug on Mac/Linux. You
should post this to the wxPython mailing group here: 
http://www.wxpython.org/maillist.php

Mike

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


Re: Better writing in python

2007-10-24 Thread Bjoern Schliessmann
Alexandre Badez wrote:
> I'm just wondering, if I could write a in a "better" way this code
> [...]
> I think there is a better way, but I can't see how...

What's "better" for you? Shorter? More performant? More readable?
Complying with best practice? Closely following a specific
programming paradigm?

Regards,


Björn

-- 
BOFH excuse #403:

Sysadmin didn't hear pager go off due to loud music from bar-room
speakers.

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


Re: building a linux executable

2007-10-24 Thread Bjoern Schliessmann
Paul Boddie wrote:
> It's not usually the absence of Python that's the problem. What if
> your application uses various extension modules which in turn rely
> on various libraries (of the .so or .a kind)? It may be more
> convenient to bundle all these libraries instead of working out
> the package dependencies for all the target distributions, even if
> you know them all.

True, thanks for clarification.

Regards,


Björn

-- 
BOFH excuse #218:

The UPS doesn't have a battery backup.

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


Re: Better writing in python

2007-10-24 Thread Paul Hankin
On Oct 24, 2:02 pm, [EMAIL PROTECTED] wrote:
> On Oct 24, 7:09 am, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > I'm just wondering, if I could write a in a "better" way this code
>
> > lMandatory = []
> > lOptional = []
> > for arg in cls.dArguments:
> >   if arg is True:
> > lMandatory.append(arg)
> >   else:
> > lOptional.append(arg)
> > return (lMandatory, lOptional)
>
> > I think there is a better way, but I can't see how...
>
> You might look into list comprehensions. You could probably do this
> with two of them:
>
> 
> # completely untested
> lMandatory = [arg for arg in cls.dArguments if arg is True]
> lOptional  = [arg for arg in cls.dArguments if arg is False]
> 
>
> Something like that. I'm not the best with list comprehensions, so I
> may have the syntax just slightly off.

Your list comprehensions are right, but 'arg is True' and 'arg is
False' are better written as 'arg' and 'not arg' respectively.

--
Paul Hankin

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


Re: escape single and double quotes

2007-10-24 Thread Michael Pelz Sherman
Thanks Gabriel. You are correct - this is even documented in the MySQLdb User's 
Guide (http://mysql-python.sourceforge.net/MySQLdb.html), but it's certainly 
not intuitive, given how python string interpolation normally works.

Gabriel Genellina <[EMAIL PROTECTED]> wrote: En Tue, 23 Oct 2007 20:50:55 
-0300, Michael Pelz Sherman  
 escribió:

> Leif B. Kristensen wrote:
>
  SQL = 'INSERT into TEMP data = %s'
  c.execute(SQL, """ text containing ' and ` and all other stuff we
>>> .  might
>>> .   read from the network""")
>>
>>> Sure, but does this work if you need more than one placeholder?
>
>> Yes it works with more than one placeholder.
>
> Yes, BUT: I have found that all of the placeholders must be STRINGS!
>
> If I try to use other data types (%d, %f, etc.), I get an error:
>
> File "/usr/lib/python2.5/site-packages/MySQLdb/cursors.py", line 149, in  
> execute
> query = query % db.literal(args)
> TypeError: float argument required
>
> It's not a huge problem to convert my non-string args, but it
> seems like this should be fixed if it's a bug, no?

No. The *MARK* is always %s - but the data may be any type (suitable for  
the database column, of course).
The only purpose of %s is to say "insert parameter here". Other adapters  
use a question mark ? as a parameter placeholder, a lot less confusing, as  
it does not look like string interpolation.

-- 
Gabriel Genellina

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

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

win32com.client documentation?

2007-10-24 Thread Mark Morss
I am a unix person, not new to Python, but new to Python programming
on windows.  Does anyone know where to find documentation on
win32com.client?  I have successfully installed this module and
implemented some example code.  But a comprehensive explanation of the
objects and methods available is nowhere to be found.  I have been
able to find a somewhat out-of-date O'Reilly book, nothing more.

I want to be able to script the creation of Excel spreadsheets and
Word documents, interract with Access data bases, and so forth.

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


Re: Better writing in python

2007-10-24 Thread Tim Chase
> Here is my real code:
> 
> with
> dArguments = {
>   'argName' : {
> 'mandatory' : bool, # True or False
> [...], # other field we do not care here
>   }
> }
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if cls.dArguments[arg]['mandatory']:
> lMandatory.append(arg)
>   else:
> lOptional.append(arg)
> return (lMandatory, lOptional)

I'm kinda confused, as you're iterating over cls.dArguments, so 
arg appears to be a dictionary (addressable with ['mandatory']), 
but then you're using it (the arg dictionary) as a key into 
cls.dArguments which seems suspect.  I suspect you want to do 
something like

   for arg in cls.dArguments:
 if arg['manditory']:
   lMandatory.append(arg)
 else:
   lOptional.append(arg)
   return (lMandatory, lOptional)

I've done something like this in the past:

   def partition(i, f):
 # can be made into list-comprehensions instead if iters
 return (x for x in i if f(x)), (x for x in i if not f(x))

   odds,evens = partition(xrange(10), lambda x: x & 1)
   print "Odd numbers:"
   for thing in odds: print thing
   print "Even numbers:"
   for thing in evens: print thing

which could be translated in your case to something like

   return partition(cls.dArguments,
 lambda x: x['manditory']
 )

I don't know if you find it "more pythonic" or easier to read 
(which in a way is an aspect of "more pythonic"), but in some 
cases, I find this fits my brain better.

-tkc






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


Re: Better writing in python

2007-10-24 Thread cokofreedom
On Oct 24, 4:15 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 24, 2:02 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On Oct 24, 7:09 am, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > > I'm just wondering, if I could write a in a "better" way this code
>
> > > lMandatory = []
> > > lOptional = []
> > > for arg in cls.dArguments:
> > >   if arg is True:
> > > lMandatory.append(arg)
> > >   else:
> > > lOptional.append(arg)
> > > return (lMandatory, lOptional)
>
> > > I think there is a better way, but I can't see how...
>
> > You might look into list comprehensions. You could probably do this
> > with two of them:
>
> > 
> > # completely untested
> > lMandatory = [arg for arg in cls.dArguments if arg is True]
> > lOptional  = [arg for arg in cls.dArguments if arg is False]
> > 
>
> > Something like that. I'm not the best with list comprehensions, so I
> > may have the syntax just slightly off.
>
> Your list comprehensions are right, but 'arg is True' and 'arg is
> False' are better written as 'arg' and 'not arg' respectively.
>
> --
> Paul Hankin

Anyone know why towards arg is True and arg is False, arg is None is
faster than arg == None ...

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


Re: Anagrams

2007-10-24 Thread cokofreedom
On Oct 24, 2:28 am, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 23, 9:21 am, [EMAIL PROTECTED] wrote:
>
> > This one uses a dictionary to store prime values of each letter in the
> > alphabet and for each line multiple the results of the characters
> > (which is unique for each anagram) and add them to a dictionary for
> > printing latter.
>
> > def anagram_finder():
> > primeAlpha = {'a':2, 'b':3, 'c':5, 'd':7,'e' : 11, 'f':13, 'g':17,
> > 'h':19,\
> >   'i':23, 'j':29, 'k':31, 'l':37, 'm':41, 'n':43, 'o':
> > 47, 'p':53,\
> >   'q':59, 'r':61, 's':67, 't':71, 'u':73, 'v':79, 'w':
> > 83, 'x':89,\
> >   'y':97, 'z':101}
> > ...
>
> A somewhat nicer start: compute primes (naively) rather than typing
> out the dictionary.
>
> import string
> from itertools import ifilter, count
>
> def anagram_finder():
>  primes = ifilter(lambda p: all(p % k for k in xrange(2, p)),
> count(2))
>  primeAlpha = dict(zip(string.lowercase, primes))
>  ...
>
> --
> Paul Hankin

Towards itertools, apart from the lib page on Python does anyone know
of good tutorials of their usage...(beyond exploring myself it would
be nice to see good examples for usage and effective combinations...)

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


Re: TeX pestilence (was Distributed RVS, Darcs, tech love)

2007-10-24 Thread Michele Dondi
On Mon, 22 Oct 2007 09:07:37 -0400, Lew <[EMAIL PROTECTED]> wrote:

>Xah Lee wrote:
>> i have written ... No coherent argument, 

I've long killfiled XL to the effect that all of his threads are
ignored altogether, since the guy is "nice" enough to only take part
to his own rants, but occasionally some posts slip out and now from
the Subject I infer that the new target for his hate is TeX, which
makes me wonder, given his views on Perl (and "unixisms in general"
iirc) what our "friend" would think about such a wonderful tool as
PerlTeX - from his POV certainly a synergy between two of the worst
devil's devices.  :)


Michele
-- 
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^http://mail.python.org/mailman/listinfo/python-list


Re: Better writing in python

2007-10-24 Thread George Sakkis
On Oct 24, 10:42 am, [EMAIL PROTECTED] wrote:
> On Oct 24, 4:15 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 24, 2:02 pm, [EMAIL PROTECTED] wrote:
>
> > > On Oct 24, 7:09 am, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>
> > > > I'm just wondering, if I could write a in a "better" way this code
>
> > > > lMandatory = []
> > > > lOptional = []
> > > > for arg in cls.dArguments:
> > > >   if arg is True:
> > > > lMandatory.append(arg)
> > > >   else:
> > > > lOptional.append(arg)
> > > > return (lMandatory, lOptional)
>
> > > > I think there is a better way, but I can't see how...
>
> > > You might look into list comprehensions. You could probably do this
> > > with two of them:
>
> > > 
> > > # completely untested
> > > lMandatory = [arg for arg in cls.dArguments if arg is True]
> > > lOptional  = [arg for arg in cls.dArguments if arg is False]
> > > 
>
> > > Something like that. I'm not the best with list comprehensions, so I
> > > may have the syntax just slightly off.
>
> > Your list comprehensions are right, but 'arg is True' and 'arg is
> > False' are better written as 'arg' and 'not arg' respectively.
>
> > --
> > Paul Hankin
>
> Anyone know why towards arg is True and arg is False, arg is None is
> faster than arg == None ...

And quite often incorrect, especially the "arg is True" and "arg is
False".

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


Re: building a linux executable

2007-10-24 Thread Paul Boddie
On 24 Okt, 16:10, Bjoern Schliessmann  wrote:
> Paul Boddie wrote:
> > It's not usually the absence of Python that's the problem. What if
> > your application uses various extension modules which in turn rely
> > on various libraries (of the .so or .a kind)? It may be more
> > convenient to bundle all these libraries instead of working out
> > the package dependencies for all the target distributions, even if
> > you know them all.
>
> True, thanks for clarification.

Any suggestions, then? ;-)

I've also run into similar issues with cx_Freeze: I wanted to package
a game written using PyGame, which itself requires some SDL libraries,
which in turn require different libraries like smpeg (if I remember
correctly). It gets to the point where one is effectively building a
Python distribution (another question asked recently but not answered
sufficiently), which has minimal linkage to other libraries - perhaps
the system C libraries, some X11 libraries, and nothing more. Some
ideas about doing that successfully (perhaps LSB enters the picture)
would be quite useful.

Paul

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


Re: How to find out which functions exist?

2007-10-24 Thread mrstephengross
> import module
> from inspect import getmembers, isclass
> classes = getmembers(module, isclass)

Ok, this makes sense. How can I do it inside the .py file I'm working
on? That is, consider this:

  class A:
pass
  class B:
pass
  import inspect
  print inspect.getmembers(, inspect.isclass) # how can I
express  ?

Thanks again,
--Steve

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


Re: win32com.client documentation?

2007-10-24 Thread kyosohma
On Oct 24, 9:35 am, Mark Morss <[EMAIL PROTECTED]> wrote:
> I am a unix person, not new to Python, but new to Python programming
> on windows.  Does anyone know where to find documentation on
> win32com.client?  I have successfully installed this module and
> implemented some example code.  But a comprehensive explanation of the
> objects and methods available is nowhere to be found.  I have been
> able to find a somewhat out-of-date O'Reilly book, nothing more.
>
> I want to be able to script the creation of Excel spreadsheets and
> Word documents, interract with Access data bases, and so forth.

Actually, the out-of-date book is still very relevant for most
applications. Chun's book, Core Python Programming also has a section
on using Python to manipulate Office documents.

The docs for PyWin32 currently reside here:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html

The com documents specifically can be found here:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/com.html

As Tim Golden has mentioned before, Pywin32 is bound so closely to the
win32 calls that you can basically just look on MSDN and use the
syntax there in Python, for the most part.

Mike

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


Re: Better writing in python

2007-10-24 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
> Anyone know why towards arg is True and arg is False, arg is None is
> faster than arg == None ...

Perhaps reading about both the meaning of the 'is' operator might help ? 
  the expression 'arg is True' will only eval to true if 'id(arg) == 
id(True)'. Now Python objects does have a truth value by themselves. So 
an object can eval to false in a boolean test *without* being the False 
object itself.

For the record, True and False are late additions to the language - at 
first, it only had truth values of objects, basically defined as 'empty 
sequences and containers, numeric zeros and None are false, anything 
else is true unless either:
- the class implements the __len__ magic method and len(obj) == 0
- the class implements the magic method __non_zero__ (IIRC) and this 
obj.__non_zero__ returns false.

So the common idiom is to test the truth value of an object, which is 
expressed as "if obj: " - using 'if obj == True:' being redundant and 
'if obj is True:' usually not what you want.

wrt/ None: Since being None is not the same thing as being false (even 
if the first imply the second) - there may be cases where you want to 
distinguish between an object with a false truth value from the None 
object itself - so you can't just use 'if not obj:'. Now since None is 
garanteed to be a singleton, it defines it's __cmp__ (the magic method 
for '==') as an identity test. So directly using the identity test is 
faster since it yields the exact same result as the equality test 
without the overhead of the additional method call.


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


Re: How to find out which functions exist?

2007-10-24 Thread Diez B. Roggisch
mrstephengross wrote:

>> import module
>> from inspect import getmembers, isclass
>> classes = getmembers(module, isclass)
> 
> Ok, this makes sense. How can I do it inside the .py file I'm working
> on? That is, consider this:
> 
>   class A:
> pass
>   class B:
> pass
>   import inspect
>   print inspect.getmembers(, inspect.isclass) # how can I
> express  ?

Then you can use globals(), like this:

classes = [v for v in globals().values() if isclass(v)]

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


Re: win32com.client documentation?

2007-10-24 Thread Matimus
On Oct 24, 7:35 am, Mark Morss <[EMAIL PROTECTED]> wrote:
> I am a unix person, not new to Python, but new to Python programming
> on windows.  Does anyone know where to find documentation on
> win32com.client?  I have successfully installed this module and
> implemented some example code.  But a comprehensive explanation of the
> objects and methods available is nowhere to be found.  I have been
> able to find a somewhat out-of-date O'Reilly book, nothing more.
>
> I want to be able to script the creation of Excel spreadsheets and
> Word documents, interract with Access data bases, and so forth.

That book, if you are talking about "Python Programming on Win32" by
Mark Hamond and Andy Robinson, is the best resource that I know of.
There are a few other places for help, and two of those the help files
installed on your computer with win32com and the source code. You may
be able to find other tutorials and such online. What helped me though
was not a better understanding of these packages, but a better
understanding of COM in general. Once I had a fair understanding of
COM I had a much better experience. I found "Inside COM" by Dale
Rogerson to be a good general resource on learning COM, although there
are many books on the subject to choose from. I can't really help you
any more unless you come up with a specific example of what you are
trying to do.

Matt

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


Re: Speed of Nested Functions & Lambda Expressions

2007-10-24 Thread beginner
On Oct 24, 2:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> beginner <[EMAIL PROTECTED]> wrote:
> > It is really convenient to use nested functions and lambda
> > expressions. What I'd like to know is if Python compiles fn_inner()
> > only once and change the binding of v every time fn_outer() is called
> > or if Python compile and generate a new function object every time. If
> > it is the latter, will there be a huge performance hit? Would someone
> > give some hint about how exactly Python does this internally?
>
> You can use Python's bytecode disassembler to see what actually gets
> executed here:
>
> >>> def fn_outer(v):
>
> a=v*2
> def fn_inner():
> print "V:%d,%d" % (v,a)
>
> fn_inner()
>
> >>> import dis
> >>> dis.dis(fn_outer)
>
>   2   0 LOAD_DEREF   1 (v)
>   3 LOAD_CONST   1 (2)
>   6 BINARY_MULTIPLY
>   7 STORE_DEREF  0 (a)
>
>   3  10 LOAD_CLOSURE 0 (a)
>  13 LOAD_CLOSURE 1 (v)
>  16 BUILD_TUPLE  2
>  19 LOAD_CONST   2 ( 01177218, file "", line 3>)
>  22 MAKE_CLOSURE 0
>  25 STORE_FAST   1 (fn_inner)
>
>   6  28 LOAD_FAST1 (fn_inner)
>  31 CALL_FUNCTION0
>  34 POP_TOP
>  35 LOAD_CONST   0 (None)
>  38 RETURN_VALUE
>
>
>
> When you execute the 'def' statement, the two scoped variables a and v
> are built into a tuple on the stack, the compiled code object for the
> inner function is also pushed onto the stack and then the function is
> created by the 'MAKE_CLOSURE' instruction. This is then stored in a
> local variable (STORE_FAST) which is then loaded and called.
>
> So the function definition is pretty fast, BUT notice how fn_inner is
> referenced by STORE_FAST/LOAD_FAST whereas a and v are referenced by
> LOAD_DEREF/STORE_DEREF and LOAD_CLOSURE.
>
> The code for fn_inner also uses LOAD_DEREF to get at the scoped
> variables:
>
>   4   0 LOAD_CONST   1 ('V:%d,%d')
>   3 LOAD_DEREF   1 (v)
>   6 LOAD_DEREF   0 (a)
>   9 BUILD_TUPLE  2
>  12 BINARY_MODULO  
>  13 PRINT_ITEM  
>  14 PRINT_NEWLINE  
>  15 LOAD_CONST   0 (None)
>  18 RETURN_VALUE
>
> (its a bit harder to disassemble that one, I stuck a call to dis.dis
> inside fn_outer to get that)
>
> If you do some timings you'll find that LOAD_DEREF/STORE_DEREF are
> rather slower than LOAD_FAST/STORE_FAST, so while the overhead for
> creating the function is minimal you could find that if you access the
> variables a lot (even in fn_outer) there may be a measurable slow-down.
>
> If timings show that it is a code hotspot then you might find it better
> to nest the function but pass any required values in as parameters (but
> if you don't have evidence for this just write whatever is clearest).


Thanks for the detailed analysis, Duncan. Also thanks for showing how
the disassembler can be used to figure this out. I was just looking
for a tool like this. This is great. Thanks again.

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


Re: How to find out which functions exist?

2007-10-24 Thread Marc 'BlackJack' Rintsch
On Wed, 24 Oct 2007 15:09:02 +, mrstephengross wrote:

>> import module
>> from inspect import getmembers, isclass
>> classes = getmembers(module, isclass)
> 
> Ok, this makes sense. How can I do it inside the .py file I'm working
> on? That is, consider this:
> 
>   class A:
> pass
>   class B:
> pass
>   import inspect
>   print inspect.getmembers(, inspect.isclass) # how can I
> express  ?

If you want the objects from the current module you can simply look at the
`globals()` dictionary.

from inspect import isclass
from itertools import ifilter

classes = set(ifilter(isclass, globals().itervalues()))

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


optparse help output

2007-10-24 Thread Dan
I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:

parser.add_option("-a", "--action",
  help=\
"""Current supported actions: create, build, import, exp_cmd and
interact.

create   -- Vaguely depreciated, should create a new project, but it
is
not currently suppored. First create a project in SVN,
then
use import.

build-- Build the project (invoking make usually).

import   -- Put the project under metaman control. Assumes that
the current working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does analysis
to determine dependencies and the metadata to be
collected.

interact -- Creates a MetaMan object and starts the python interactive
interpreter. Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier 'mm'. Only
use this option if you know what you're doing.

exp_cmd --  add an experiment for strataman.
""")

Unfortunately, when I run the script with --help, this is what I get
for the -a option:
  -aACTION, --action=ACTION
Current supported actions: create, build,
import,
exp_cmd and interact.  create   -- Vaguely
depreciated,
should create a new project, but it
is not
currently suppored. First create a project in
SVN, then
use import.  build-- Build the project
(invoking
make usually).  import   -- Put the project
under
metaman control. Assumes that the
current
working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does
analysis
to determine dependencies and the metadata to
be
collected.  interact -- Creates a MetaMan
object and
starts the python interactive
interpreter.
Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier
'mm'.
Only use this option if you know
what
you're doing.  exp_cmd --  add an experiment
for
strataman.

Is there any way to get the formatting I want?

-Dan

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


Re: Better writing in python

2007-10-24 Thread Marc 'BlackJack' Rintsch
On Wed, 24 Oct 2007 16:04:28 +0200, A.T.Hofkamp wrote:

>> On 2007-10-24, Alexandre Badez <[EMAIL PROTECTED]> wrote:
>> I'm just wondering, if I could write a in a "better" way this
>> code
>>
>> lMandatory = []
>> lOptional = []
>> for arg in cls.dArguments:
>>   if arg is True:
>> lMandatory.append(arg)
>>   else:
>> lOptional.append(arg)
>> return (lMandatory, lOptional)
>>
>> I think there is a better way, but I can't see how...
> 
> You can do it shorter, not sure that it also qualifies as better
> 
> d = { True : [] , False : [] }
> for arg in cls.arguments:
>   d[arg == True].append(arg)
> 
> return d[True], d[False]
> 
> One potential problem here is that 'arg == True' may not be the same as 'if
> arg:'. I couldn't come up with a better equivalent expression, maybe one of 
> the
> other readers knows more about this?

With ``if arg:`` the interpreter asks `arg` for its "boolean value".  So a
better way would be:

d[bool(arg)].append(arg)

As `True` and `False` are instances of `int` with the values 1 and 0 it's
possible to replace the dictionary by a list:

tmp = [[], []]
for arg in cls.arguments:
tmp[bool(arg)].append(arg)
return tmp[1], tmp[0]

Maybe that's nicer.  Maybe not.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optparse help output

2007-10-24 Thread Tim Chase
> I've been using optparse for a while, and I have an option with a
> number of sub-actions I want to describe in the help section:
> 
> parser.add_option("-a", "--action",
>   help=\
[snipped formatted help]
> """)
> 
> Unfortunately, when I run the script with --help, this is what I get
> for the -a option:
[snipped munged formatting of help]
> Is there any way to get the formatting I want?

I had the same issue:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6df6e6b541a15bc2/09f28e26af0699b1?#09f28e26af0699b1

and was directed by Ben Finney to check out a custom formatter. 
I got it working to my satisfaction and posted it in that thread:

http://groups.google.com/group/comp.lang.python/msg/09f28e26af0699b1

It may be a little more kind in what it does with your help-text. 
  If you need variant behavior you can take my code and mung it 
even further.

The changes are basically a copy&paste (including the comments, 
which Steven D'Aprano suggested might be better made into 
docstrings) of the format_description() and format_option() calls 
from the standard-library's source, and changing a few small 
lines to alter the behavior of calls to textwrap.*

Hope this helps,

-tkc




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


Re: Anagrams

2007-10-24 Thread sandipm
hi,
 Is "all" inbuilt function in python? what it does?


> from itertools import ifilter, count
>
> def anagram_finder():
>  primes = ifilter(lambda p: all(p % k for k in xrange(2, p)), count(2))
  
>  primeAlpha = dict(zip(string.lowercase, primes))
>  ...


--
sandip

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


Re: basic web auth and verification

2007-10-24 Thread [EMAIL PROTECTED]
On Oct 23, 12:55 am, Ralf Schönian <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
>
>
>
>
> > Trying to figure out how to add login verfication. I believe it is
> > logging me in, but theres no way to really tell..any ideas? or
> > tutorials out there that can exaplain this to me?
>
> > Thanks
>
> > import urllib,urllib2,cookielib
>
> > passlst = open(passfile, 'r').readlines()
> > url="http://somesite";
> > cj = cookielib.LWPCookieJar()
> > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
> > urllib2.install_opener(opener)
> > TheForm = urllib.urlencode({"username":"myid","password":"mypas"})
> > request = urllib2.Request(url, TheForm)
> > result = urllib2.urlopen(request)
> > html=result.read()
> > result.close()
>
> I had the same trouble. There was a redirect after login a had to
> follow. Look at the following code.
>
>  def login(self):
>  ''' Log into web site. '''
>
>  self._br.set_handle_redirect(True)
>  cj = CookieJar()
>  self._br.set_cookiejar(cj)
>  self._br.open(Config.urlLogin)
>  self._br.select_form(name='login')
>
>  self._br['session_key'] = Config.username
>  self._br['session_password'] = Config.password
>  response=self._br.submit()
>  self._br.set_response(response)
>  for link in self._br.links(url_regex="www.somesite.com"):
>  self._br.follow_link(link)
>  if 'Sign In' in self._br.title():
>  raise ValueError('Wrong password')
>
> Regards,
> Ralf Schoenian- Hide quoted text -
>
> - Show quoted text -

Thank you very much, ill look into it..

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

Re: Better writing in python

2007-10-24 Thread Bruno Desthuilliers
Bjoern Schliessmann a écrit :
> Alexandre Badez wrote:
>> I'm just wondering, if I could write a in a "better" way this code
>> [...]
>> I think there is a better way, but I can't see how...
> 
> What's "better" for you? Shorter? More performant? More readable?
> Complying with best practice? Closely following a specific
> programming paradigm?

I think the OP meant "more pythonic".

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


Re: Anagrams

2007-10-24 Thread Paul Hankin
On Oct 24, 5:03 pm, sandipm <[EMAIL PROTECTED]> wrote:
>  Is "all" inbuilt function in python? what it does?

>>> help(all)
Help on built-in function all in module __builtin__:

all(...)
all(iterable) -> bool

Return True if bool(x) is True for all values x in the iterable.

--
Paul Hankin

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


Re: TeX pestilence (was Distributed RVS, Darcs, tech love)

2007-10-24 Thread Byung-Hee HWANG
On Mon, 2007-10-22 at 12:19 -0400, Lew wrote:
> Xah Lee <[EMAIL PROTECTED]> wrote:
> >> 4. Inargurated a massive collection of documents that are invalid
> >> HTML. (due to the programing moron's ingorance and need to idolize a
> >> leader, and TeX's inherent problem of being a typesetting system that
> >> is unsuitable of representing any structure or semantics)
> 
> There's something a little fey about someone calling out a "programing [sic] 
> moron's ingorance [sic]" and then devolving right into blue speech.
> 
> I think Xah Lee should look into:
> 

Well, you are making a personal attack, it's dangerous. I wish to see
only discussions about TeX ;;

-- 
Byung-Hee HWANG * مجاهدين * InZealBomb 
"I'll reason with him."
-- Vito Corleone, "Chapter 14", page 200
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Anagrams

2007-10-24 Thread Tim Chase
>>  Is "all" inbuilt function in python? what it does?
> 
 help(all)
> Help on built-in function all in module __builtin__:
> 
> all(...)
> all(iterable) -> bool
> 
> Return True if bool(x) is True for all values x in the iterable.

It may be helpful to know that any() and all() were added in 
Python 2.5

http://docs.python.org/lib/built-in-funcs.html#l2h-9

-tkc




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


Re: Better writing in python

2007-10-24 Thread beginner
On Oct 24, 9:04 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> > On 2007-10-24, Alexandre Badez <[EMAIL PROTECTED]> wrote:
> > I'm just wondering, if I could write a in a "better" way this
> > code
>
> > lMandatory = []
> > lOptional = []
> > for arg in cls.dArguments:
> >   if arg is True:
> > lMandatory.append(arg)
> >   else:
> > lOptional.append(arg)
> > return (lMandatory, lOptional)
>
> > I think there is a better way, but I can't see how...
>
> You can do it shorter, not sure that it also qualifies as better
>
> d = { True : [] , False : [] }
> for arg in cls.arguments:
>   d[arg == True].append(arg)
>
> return d[True], d[False]
>
> One potential problem here is that 'arg == True' may not be the same as 'if
> arg:'. I couldn't come up with a better equivalent expression, maybe one of 
> the
> other readers knows more about this?
>
> Albert

d[bool(arg)].append(arg) resolves your concern?

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


How to best send email to a low volume list?

2007-10-24 Thread chris
I need to maintain a list of subscribers to an email list for a
"newsletter" that will be sent via a web form probably once a month.
I anticipate low numbers--tens to maybe one hundred subscribers at the
most.  Just curious what the best way to code this is.  Should I just
loop through the addresses and send one-off emails to each, or is it
better to somehow send to every recipient in one shot?  One thing I
would like to avoid in the latter scenario is each recipient being
able to see the entire list of recipients.  Also don't want to trigger
any kind of spam thing on my web host by sending out too many emails.

Anyway, any tips appreciated.

Thanks,
Chris

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


Re: How to best send email to a low volume list?

2007-10-24 Thread Adam Lanier
On Wed, 2007-10-24 at 16:54 +, chris wrote:
> I need to maintain a list of subscribers to an email list for a
> "newsletter" that will be sent via a web form probably once a month.
> I anticipate low numbers--tens to maybe one hundred subscribers at the
> most.  Just curious what the best way to code this is.  Should I just
> loop through the addresses and send one-off emails to each, or is it
> better to somehow send to every recipient in one shot?  One thing I
> would like to avoid in the latter scenario is each recipient being
> able to see the entire list of recipients.  Also don't want to trigger
> any kind of spam thing on my web host by sending out too many emails.
> 
> Anyway, any tips appreciated.
> 
> Thanks,
> Chris
> 

Before you reinvent the wheel, you should look into using a mailing list
manager, Mailman for example:

http://www.gnu.org/software/mailman/index.html

Regardless, confirmed double-opt-in should be a requirement as should a
mechanism for subscribers to unsubscribe themselves.

Using a 'list address' as the from address and using bcc addressing will
prevent your recipients from being able to see all the other recipient
addresses.

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


Re: optparse help output

2007-10-24 Thread Dan
On Oct 24, 12:06 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I've been using optparse for a while, and I have an option with a
> > number of sub-actions I want to describe in the help section:
>
> > parser.add_option("-a", "--action",
> >   help=\
>
> [snipped formatted help]> """)
>
> > Unfortunately, when I run the script with --help, this is what I get
> > for the -a option:
>
> [snipped munged formatting of help]
>
> > Is there any way to get the formatting I want?
>
> I had the same issue:
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> and was directed by Ben Finney to check out a custom formatter.
> I got it working to my satisfaction and posted it in that thread:
>
> http://groups.google.com/group/comp.lang.python/msg/09f28e26af0699b1
>
> It may be a little more kind in what it does with your help-text.
>   If you need variant behavior you can take my code and mung it
> even further.
>
> The changes are basically a copy&paste (including the comments,
> which Steven D'Aprano suggested might be better made into
> docstrings) of the format_description() and format_option() calls
> from the standard-library's source, and changing a few small
> lines to alter the behavior of calls to textwrap.*
>
> Hope this helps,
>
> -tkc

Thanks, Tim!

That was incredibly helpful. I did alter it to format paragraphs, but
maintain the double newlines. Also, I made a few changes to work with
the 2.3 version of optparse. Posted below for anyone who might want
it. (Also to work as a standalone .py file)

-Dan


# From Tim Chase via comp.lang.python.

from optparse import IndentedHelpFormatter
import textwrap

class IndentedHelpFormatterWithNL(IndentedHelpFormatter):
  def format_description(self, description):
if not description: return ""
desc_width = self.width - self.current_indent
indent = " "*self.current_indent
# the above is still the same
bits = description.split('\n')
formatted_bits = [
  textwrap.fill(bit,
desc_width,
initial_indent=indent,
subsequent_indent=indent)
  for bit in bits]
result = "\n".join(formatted_bits) + "\n"
return result

  def format_option(self, option):
# The help for each option consists of two parts:
#   * the opt strings and metavars
#   eg. ("-x", or "-fFILENAME, --file=FILENAME")
#   * the user-supplied help string
#   eg. ("turn on expert mode", "read data from FILENAME")
#
# If possible, we write both of these on the same line:
#   -xturn on expert mode
#
# But if the opt string list is too long, we put the help
# string on a second line, indented to the same column it would
# start in if it fit on the first line.
#   -fFILENAME, --file=FILENAME
#   read data from FILENAME
result = []
opts = option.option_strings
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
  opts = "%*s%s\n" % (self.current_indent, "", opts)
  indent_first = self.help_position
else: # start help on same line as opts
  opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
  indent_first = 0
result.append(opts)
if option.help:
  help_text = option.help
# Everything is the same up through here
  help_lines = []
  help_text = "\n".join([x.strip() for x in
help_text.split("\n")])
  for para in help_text.split("\n\n"):
help_lines.extend(textwrap.wrap(para, self.help_width))
if len(help_lines):
  # for each paragraph, keep the double newlines..
  help_lines[-1] += "\n"
# Everything is the same after here
  result.append("%*s%s\n" % (
indent_first, "", help_lines[0]))
  result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
  result.append("\n")
return "".join(result)

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


Re: optparse help output

2007-10-24 Thread Steven Bethard
Dan wrote:
> On Oct 24, 12:06 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
>>> I've been using optparse for a while, and I have an option with a
>>> number of sub-actions I want to describe in the help section:
>>> parser.add_option("-a", "--action",
>>>   help=\
>> [snipped formatted help]> """)
>>
>>> Unfortunately, when I run the script with --help, this is what I get
>>> for the -a option:
>> [snipped munged formatting of help]
>>
>>> Is there any way to get the formatting I want?
>> I had the same issue:
>>
>> http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>>
>> and was directed by Ben Finney to check out a custom formatter.
>> I got it working to my satisfaction and posted it in that thread:
>>
>> http://groups.google.com/group/comp.lang.python/msg/09f28e26af0699b1
>>
> That was incredibly helpful. I did alter it to format paragraphs, but
> maintain the double newlines. Also, I made a few changes to work with
> the 2.3 version of optparse. Posted below for anyone who might want
> it. (Also to work as a standalone .py file)

You might consider posting it to the optik tracker:

 http://optik.sourceforge.net/

A lot of people have had similar requests.

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


New to Vim and Vim-Python

2007-10-24 Thread Daniel Folkes
I am new to using Vim's scripts.

I was wondering if anyone uses Vim-Python and how to use it?   This
includes things like key bindings and such.

Thanks in advance,
Daniel Folkes
[EMAIL PROTECTED]

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


Mobile Startup looking for sharp coders

2007-10-24 Thread Vangati
Plusmo is Hiring!

Plusmo's mission is to provide the ultimate mobile experience for
users by bringing together advanced technologies and easy to use
services for mobile phones. Plusmo's innovative widget service lets
users run cool "widgets" on their mobile phones. There are over 20,000
widgets and mobile mash-ups on Plusmo, most of them created and shared
by end users and publishers with no coding knowledge.

Join us in tackling the challenges of a rapidly growing service with
millions of mobile page views. Plusmo's founding team has a successful
track record with two mobile startups and extensive experience working
with mobile web standards.  Plusmo is well-funded and looking for
sharp coders and smart business minds to expand our team. If you want
to join a small company trying to change the world, then this is the
place for you!

Top 5 reasons to join Plusmo -
1.  You wanted a specific service for your mobile phone but it is not
available out there.
 Why not write it and get paid for it?
2.  You think small screen is not a challenge but an opportunity if
used correctly
3.  You want to define the next generation mobile web standards
4.  You get a kick out of building cool web and mobile mash-ups
overnight
5.  You constantly experience that nagging feeling that your phone is
under-utilized

Plusmo is based in Santa Clara, California and is looking to fill
these full-time positions immediately. You must be a legal US resident
and be based in the San Francisco Bay Area to apply.

Senior Mobile Developers: Several Positions Available. You must be an
experienced developer with deep hands-on working knowledge on these
mobile technologies: Symbian, Windows Mobile, BREW, J2ME, Blackberry,
Mobile Linux and Flash, mobile browsers and standards.

User Experience Designer - Define the next generation visual design,
Interaction design, experience with web and mobile widgets, Flash user
interfaces.

Senior Flash Developer: Design and build several web and mobile
widgets for Plusmo. Build data driven applications using Flash, Flex
and Actionscript.

Senior Web Developer - Web-site front-end development using CSS, HTML
and Javascript.  Must know XMLHTTP, Cross-browser compatibility
issues.

Send your resume to [EMAIL PROTECTED]

Recruiting Agencies: Please do not send us unsolicited resumes. Plusmo
does not consider resumes from any agencies. We are not responsible
for any charges from agencies.

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


Easiest way to get exit code from os.popen()?

2007-10-24 Thread mrstephengross
Hi folks. I'm using os.popen() to run a command; according to the
documentation, the filehandle.close() oepration is suppsoed to return
the exit code. However, when I execute something like "exit 5",
close() returns 1280. Here's the code:

  pipe = os.popen("exit 5")
  print pipe.close() # prints 1280

Am I doing something wrong? Is there an easier way to get the exit
code?

Thanks,
--Steve

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


Test for a unicode string

2007-10-24 Thread goldtech
Hi,

I have a regular expression test in a script. When a unicode character
get tested in the regex it gives an error:

UnicodeError: ASCII decoding error: ordinal not in range(128)

Question: Is there a way to test a string for unicode chars (ie. test
if a string will throw the error cited above).

Like:
 if  unicode string:
  print  'string's line #'
 else:
  process the string

How do I do "if unicode string" cited in pseudo-code above?

Thanks, still using Python 2.1

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


crontab library

2007-10-24 Thread Martin Marcher
Hello,

is anyone aware of a crontab library.

Possibly even more complete, something that will let me
create/manipulate/delete crontab entries in a nice way and install the
new crontab accordingly.

I had a look at the crontab docs and never realized how complex it
actually is. So before I spend time in creating such a thing maybe
someone did it already :)

thanks
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: crontab library

2007-10-24 Thread Guilherme Polo
2007/10/24, Martin Marcher <[EMAIL PROTECTED]>:
> Hello,
>
> is anyone aware of a crontab library.
>
> Possibly even more complete, something that will let me
> create/manipulate/delete crontab entries in a nice way and install the
> new crontab accordingly.
>
> I had a look at the crontab docs and never realized how complex it
> actually is. So before I spend time in creating such a thing maybe
> someone did it already :)
>

When you say complex, are you talking about the possible ways to
define when your job runs ? You could use a parser for the time format
it uses, like this:
http://umit.svn.sourceforge.net/viewvc/umit/branch/ggpolo/umitCore/CronParser.py?revision=1175&view=markup

I believe using this parser or some other would cut all the
difficulty, then it is all about creating a gui/cli/etc based on it or
extend it.. it is up to you =)

> thanks
> martin
>
> --
> http://noneisyours.marcher.name
> http://feeds.feedburner.com/NoneIsYours
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Socket communication problem

2007-10-24 Thread Sandy Dunlop
Hi,
I'm new here, and fairly new to Python. I have been playing around with
Python and started having a look at socket IO. I have written a script
that communicates over a network to a server which is written in C.
While trying to get this working, I have been running into a problem
where the Python client appears to hang when it should be receiving data
back from the server.

After a few successful exchanges of data, the server sends 3605 bytes to
the client, which the client receives. The server then sends 2 bytes to
the client, and the client doesn't get them. A client program written in
C# does not have this problem.

I have narrowed the problem down as far as I can, and have two small
scripts, client and server, and a data file they read from to know what
they should be sending and receiving. The problem can be replicated
using them within a few milliseconds of running them.

At first, I thought this may be caused by Nagel's algorithm, so I
disabled it explicitly using:

 s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

This made no difference.
Can anyone point out what I'm doing wrong here?

You can get the scripts and the 7K data file here:
http://www.sorn.net/~sandyd/python/problem/

Or all together in a zip file here:
http://www.sorn.net/~sandyd/python/problem.zip


Thanks in advance,
Sandy

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


Re: Socket communication problem

2007-10-24 Thread Sandy Dunlop
Sandy Dunlop wrote:

> Hi,
> I'm new here, and fairly new to Python. I have been playing around with
> Python and started having a look at socket IO. I have written a script
> that communicates over a network to a server which is written in C.
> While trying to get this working, I have been running into a problem
> where the Python client appears to hang when it should be receiving data
> back from the server.


I forgot to add, I'm using Python 2.5.1 on OS X, and have also tried my 
program under Python 2.5.1 on Solaris 9.


Cheers,
Sandy

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


Re: Socket communication problem

2007-10-24 Thread Jean-Paul Calderone
On Wed, 24 Oct 2007 20:42:49 +0100, Sandy Dunlop <[EMAIL PROTECTED]> wrote:
>Hi,
>I'm new here, and fairly new to Python. I have been playing around with
>Python and started having a look at socket IO. I have written a script
>that communicates over a network to a server which is written in C.
>While trying to get this working, I have been running into a problem
>where the Python client appears to hang when it should be receiving data
>back from the server.
>
>After a few successful exchanges of data, the server sends 3605 bytes to
>the client, which the client receives. The server then sends 2 bytes to
>the client, and the client doesn't get them. A client program written in
>C# does not have this problem.

Neither the server nor client Python programs you linked to uses the socket
API correctly.  The most obvious mistake is that the code does not check the
return value of socket.send(), which you must do.

Twisted is a third-party library which abstracts many of the low-level
details of the BSD socket API away from you.  You might want to take a
look at it.

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


Re: Better writing in python

2007-10-24 Thread Alexandre Badez
On Oct 24, 3:46 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> For a 'python like' look lose the Hungarian notation (even Microsoft
> have largely stopped using it)

I wish I could.
But my corporation do not want to apply python.org coding rules

> increase the indentation to 4 spaces,

Well, it is in my python file.
I do not do it here, because I'm a bit lazy.

> and also get rid of the spurious parentheses around the result.

Thanks

> Otherwise it is fine: clear and to the point.

Thanks

>
> If you really wanted you could write something like:
>
> m, o = [], []
> for arg in cls.dArguments:
> (m if cls.dArguments[arg]['mandatory'] else o).append(arg)
> return m, o
>
> Or even:
> m, o = [], []
> action = [o.append, m.append]
> for arg in cls.dArguments:
> action[bool(cls.dArguments[arg]['mandatory'])](arg)
> return m, o
>
> but it just makes the code less clear, so why bother?

And finally thanks again ;)

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


Re: Easiest way to get exit code from os.popen()?

2007-10-24 Thread Jean-Paul Calderone
On Wed, 24 Oct 2007 19:07:44 -, mrstephengross <[EMAIL PROTECTED]> wrote:
>Hi folks. I'm using os.popen() to run a command; according to the
>documentation, the filehandle.close() oepration is suppsoed to return
>the exit code. However, when I execute something like "exit 5",
>close() returns 1280. Here's the code:
>
>  pipe = os.popen("exit 5")
>  print pipe.close() # prints 1280
>
>Am I doing something wrong? Is there an easier way to get the exit
>code?

  >>> import os
  >>> os.WEXITSTATUS(1280)
  5
  >>>

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


Re: TeX pestilence (was Distributed RVS, Darcs, tech love)

2007-10-24 Thread J�rgen Exner
Lew wrote:
> Xah Lee wrote:
>> i have written ... No coherent argument,

Actually the modified title is wrong. It should be

The Xah Lee pestilence

Please see his posting history of off-topic random rambling for details.



Oh, and PLEASE


 +---+ .:\:\:/:/:.
 |   PLEASE DO NOT   |:.:\:\:/:/:.:
 |  FEED THE TROLLS  |   :=.' -   - '.=:
 |   |   '=(\ 9   9 /)='
 |   Thank you,  |  (  (_)  )
 |   Management  |  /`-vvv-'\
 +---+ / \
 |  |@@@  / /|,|\ \
 |  |@@@ /_//  /^\  \\_\
   @x@@x@|  | |/ WW(  (   )  )WW
   \/|  |\|   __\,,\ /,,/__
\||/ |  | |  jgs (__Y__)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
==

jue 


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


Re: Easiest way to get exit code from os.popen()?

2007-10-24 Thread Karthik Gurusamy
On Oct 24, 12:07 pm, mrstephengross <[EMAIL PROTECTED]>
wrote:
> Hi folks. I'm using os.popen() to run a command; according to the
> documentation, the filehandle.close() oepration is suppsoed to return
> the exit code. However, when I execute something like "exit 5",
> close() returns 1280. Here's the code:
>
>   pipe = os.popen("exit 5")
>   print pipe.close() # prints 1280
>
> Am I doing something wrong? Is there an easier way to get the exit
> code?

>>> print "%#x" % 1280
0x500 # first byte is your exit code; second gives signal info if
any
>>>

In any case, the best approach is to use the os module to interpret it
as given in other post (os.WEXITSTATUS(1280))

Karthik

>
> Thanks,
> --Steve


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


Re: crontab library

2007-10-24 Thread Martin Marcher
2007/10/24, Guilherme Polo <[EMAIL PROTECTED]>:
> 2007/10/24, Martin Marcher <[EMAIL PROTECTED]>:
> > I had a look at the crontab docs and never realized how complex it
> > actually is. So before I spend time in creating such a thing maybe
> > someone did it already :)
> >
>
> When you say complex, are you talking about the possible ways to
> define when your job runs ? You could use a parser for the time format
> it uses, like this:
> http://umit.svn.sourceforge.net/viewvc/umit/branch/ggpolo/umitCore/CronParser.py?revision=1175&view=markup

This looks nice for starters. But the crontab(5) manpage has a lot
more - that's what I meant by complex. I guess it's just quite some
typing work :)

 * lists
  * 1,2,4
 * ranges
  * 1-3
 * steps
  * 1-12/2
  * "*/3"
 * specials
  * @annually
  * @weekly
  * @daily
  * ...
 * mixes there of
  * 1-4,6,16-22/3
(this actually depends on which cron you use, the
lowest common denominator would be to use either lists or ranges
(or ranges with steps))

Then there is the difference of roots crontab where whe have a line
like this:

# minute hour dom month dow user command
0 * * * * nobody echo foo

A users crontab
# minute hour dom month dow command
0 * * * * echo foo

and all the variables one could use. with a few of them being
mandatory (LOGNAME, or USER depending on the OS), some of them being
standard variables (SHELL,
PATH) and of course custom variables.


-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: crontab library

2007-10-24 Thread Guilherme Polo
2007/10/24, Martin Marcher <[EMAIL PROTECTED]>:
> 2007/10/24, Guilherme Polo <[EMAIL PROTECTED]>:
> > 2007/10/24, Martin Marcher <[EMAIL PROTECTED]>:
> > > I had a look at the crontab docs and never realized how complex it
> > > actually is. So before I spend time in creating such a thing maybe
> > > someone did it already :)
> > >
> >
> > When you say complex, are you talking about the possible ways to
> > define when your job runs ? You could use a parser for the time format
> > it uses, like this:
> > http://umit.svn.sourceforge.net/viewvc/umit/branch/ggpolo/umitCore/CronParser.py?revision=1175&view=markup
>
> This looks nice for starters. But the crontab(5) manpage has a lot
> more - that's what I meant by complex. I guess it's just quite some
> typing work :)
>
>  * lists
>   * 1,2,4
>  * ranges
>   * 1-3
>  * steps
>   * 1-12/2
>   * "*/3"

It supports all these, so your "complex" argument was cut down again.

>  * specials
>   * @annually
>   * @weekly
>   * @daily
>   * ...

These specials aren't really complex, it is just some pre-sets

>  * mixes there of
>   * 1-4,6,16-22/3

Supports too, complexity is over again

> (this actually depends on which cron you use, the
> lowest common denominator would be to use either lists or ranges
> (or ranges with steps))
>
> Then there is the difference of roots crontab where whe have a line
> like this:
>
> # minute hour dom month dow user command
> 0 * * * * nobody echo foo
>
> A users crontab
> # minute hour dom month dow command
> 0 * * * * echo foo
>

For this you basically check how many fields it has, so you can
determine if there is an user especified or not.

> and all the variables one could use. with a few of them being
> mandatory (LOGNAME, or USER depending on the OS), some of them being
> standard variables (SHELL,
> PATH) and of course custom variables.
>

If you need to use these you should know how to use these, just write
them and let the crontab app handle it.

>
> --
> http://noneisyours.marcher.name
> http://feeds.feedburner.com/NoneIsYours
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration for Factorials

2007-10-24 Thread Nick Craig-Wood
Py-Fun <[EMAIL PROTECTED]> wrote:
>  I'm stuck trying to write a function that generates a factorial of a
>  number using iteration and not recursion.  Any simple ideas would be
>  appreciated.

Here is the math geek answer ;-)

import math

def factorial(i):
n = i + 1
return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n + 
1./288/n**2 - 139./51840/n**3)

Works for non integer factorials also...

See here for background

  http://mathworld.wolfram.com/StirlingsSeries.html

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socket communication problem

2007-10-24 Thread Sandy Dunlop
Jean-Paul Calderone wrote:

> Neither the server nor client Python programs you linked to uses the socket
> API correctly.  The most obvious mistake is that the code does not check the
> return value of socket.send(), which you must do.
> 
> Twisted is a third-party library which abstracts many of the low-level
> details of the BSD socket API away from you.  You might want to take a
> look at it.


Thankyou. I've managed to get it working now that I'm using the socket 
API correctly. In case anyone else has the same issue in the future, 
I'll leave my solution here:

 http://sorn.net/~sandyd/python/solution

I'll have a look at Twisted - sounds good.

Thanks,
Sandy


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


Re: Iteration for Factorials

2007-10-24 Thread Lou Pecora
In article <[EMAIL PROTECTED]>,
 Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

> Py-Fun <[EMAIL PROTECTED]> wrote:
> >  I'm stuck trying to write a function that generates a factorial of a
> >  number using iteration and not recursion.  Any simple ideas would be
> >  appreciated.
> 
> Here is the math geek answer ;-)
> 
> import math
> 
> def factorial(i):
> n = i + 1
> return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n + 
> 1./288/n**2 - 139./51840/n**3)
> 
> Works for non integer factorials also...
> 
> See here for background
> 
>   http://mathworld.wolfram.com/StirlingsSeries.html


Well, that's Sterling's formula.  You do have to worry about 
convergence/accuracy.

How about (for intergers - simple-minded version):

def factorial(i):
   fact=1.0
   for n in xrange(i):
  fact=n*fact
   return fact

There might even be an array method that can be adapted to get the 
product.  Is there a product method? (analogous to a sum method)

Then you could use,

   arr=arange(i)+1
   fact=arr.product()  # or something like that

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


Re: building a linux executable

2007-10-24 Thread Prateek
On Oct 24, 5:25 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 24 Okt, 14:20, Bjoern Schliessmann 
> [EMAIL PROTECTED]> wrote:
>
> > I'm sorry I cannot help, but how many linux distros have no python
> > installed or no packages of it?
>
> It's not usually the absence of Python that's the problem. What if
> your application uses various extension modules which in turn rely on
> various libraries (of the .so or .a kind)? It may be more convenient
> to bundle all these libraries instead of working out the package
> dependencies for all the target distributions, even if you know them
> all.
>
> Paul

Thanks Paul,

So I've bundled all the extension modules (cx_Freeze helped me out
with that). Here is what I did:

if sys.platform.startswith("linux"):
import [add a bunch of imports here]

This import statement immediately imports all modules which will be
required. Hence, cx_Freeze is easily able to find them and I can put
all the .so files with the distro.

The problem is that some of these .so files (_hashlib.so) are hard-
linked to /lib/libssl.so and /lib/libcrypto.so. I cannot simply just
copy those (libssl/libcrypto) files into the distribution folder (and
cx_Freeze won't do anything about them because they are not Python
modules). I need a way to figure out how to get _hashlib.so to refer
to a libssl.so which is in the same directory (I would have thunk that
it should use the PATH environment variable - apparently not).

This seems to be a simple enough problem, doesn't it??

NB: Has the community come up with a better way to distribute Python
executables on linux? I'd also like to hear from folks who've got
linux distributables of medium to large scale python programs...

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


Re: Iteration for Factorials

2007-10-24 Thread [EMAIL PROTECTED]
On Oct 24, 4:05 pm, Lou Pecora <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Py-Fun <[EMAIL PROTECTED]> wrote:
> > >  I'm stuck trying to write a function that generates a factorial of a
> > >  number using iteration and not recursion.  Any simple ideas would be
> > >  appreciated.
>
> > Here is the math geek answer ;-)
>
> > import math
>
> > def factorial(i):
> > n = i + 1
> > return math.exp(-n)*(n**(n-0.5))*math.sqrt(2*math.pi)*(1. + 1./12/n +
> > 1./288/n**2 - 139./51840/n**3)
>
> > Works for non integer factorials also...
>
> > See here for background
>
> >  http://mathworld.wolfram.com/StirlingsSeries.html
>
> Well, that's Sterling's formula.  You do have to worry about
> convergence/accuracy.
>
> How about (for intergers - simple-minded version):
>
> def factorial(i):
>fact=1.0
>for n in xrange(i):
>   fact=n*fact
>return fact

Simple minded indeed.

>>> factorial(3)
0.0

>
> There might even be an array method that can be adapted to get the
> product.  Is there a product method? (analogous to a sum method)
>
> Then you could use,
>
>arr=arange(i)+1
>fact=arr.product()  # or something like that
>
> --
> -- Lou Pecora- Hide quoted text -
>
> - Show quoted text -


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


Re: Test for a unicode string

2007-10-24 Thread Martin Marcher
2007/10/24, goldtech <[EMAIL PROTECTED]>:
> Question: Is there a way to test a string for unicode chars (ie. test
> if a string will throw the error cited above).

yes there ist :)

>>> isinstance(u"a", basestring)
True
>>> isinstance(u"a", unicode)
True
>>> isinstance("a", unicode)
False
>>> isinstance("a", str)
True
>>> isinstance(u"a", str)
False


-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Vim and Vim-Python

2007-10-24 Thread Martin Marcher
Hello,

2007/10/24, Daniel Folkes <[EMAIL PROTECTED]>:
> I am new to using Vim's scripts.
> I was wondering if anyone uses Vim-Python and how to use it?   This
> includes things like key bindings and such.

are you talking about

* how to use vim?
 * http://www.vi-improved.org/tutorial.php
* how to create vim scripts?
 * sorry can't help (but vim.sf.net has a couple of scripts you might
want to look at)
* how to use vim to create python scripts?
 1. http://www.vi-improved.org/tutorial.php
 2. http://docs.python.org/tut/tut.html

Personally I just left vim in favor of emacs - there's just a lot more
available that is ready to use vim emacs than with vim (in my case,
your use case may vary)

hth
martin


-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameters in context manager's __enter__ method?

2007-10-24 Thread Matimus
On Oct 24, 7:06 am, [EMAIL PROTECTED] wrote:
> I am working on a file locking class which I'd like to work with Python
> 2.5's context managers.  The acquire method takes an optional timeout
> argument:
>
> class FileLock:
> ...
> def acquire(self, timeout=None):
> ...
>
> def __enter__(self):
> self.acquire()
> return self
>
> Can that optional timeout be somehow accommodated by the with statement?
> (I'm thinking no, which may not be a big shortcoming anyway.)
>
> Thx,
>
> Skip

I think a better solution might be to create a locking class, and a
seperate context manager class. That way you can pass the timeout as a
parameter to the context managers constructor:

[code]
fl = FileLock(...)
with FileLockContext(filelock=fl, timeout=1000):
   # do stuff
[/code]

But another option along the same line might be to have the acquire
method return the context instance. Then you could write:

[code]
class FileLockContext(fl, timeout):
...

class FileLock:
...
def acquire(self, timeout=None):
# do acquiring
return FileLockContext(self, timeout)

fl = FileLock(...)
with fl.acquire(1000):
  #do stuff
[/code]

Or, you could go the same path you are already, using a hybrid, and
pass timeout to the FileLock constructor.

Matt

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


ANN: Wing IDE 3.0.1 Released

2007-10-24 Thread Wingware
Hi,

We're happy to announce version 3.0.1 of Wing IDE, an advanced development
environment for the Python programming language. It is available from:

http://wingware.com/downloads

This release focuses on fixing minor usability issues found in Wing 3.0 and
improves and expands the VI keyboard personality.  It is a free upgrade
for all Wing 3.0 users.

See the change log for details:

http://wingware.com/pub/wingide/3.0.1/CHANGELOG.txt

*About Wing IDE*

Wing IDE is an integrated development environment for the Python programming
language.  It provides powerful debugging, editing, code intelligence,
testing, and search capabilities that reduce development and debugging
time, cut down on coding errors, and make it easier to understand
and navigate Python code.

New features added in Wing 3.0 include:

* Multi-threaded debugger
* Debug value tooltips in editor, debug probe, and interactive shell
* Autocompletion and call tips in debug probe and interactive shell
* Automatically updating project directories
* Testing tool, currently supporting unittest derived tests (*)
* OS Commands tool for executing and interacting with external commands (*)
* Rewritten indentation analysis and conversion (*)
* Introduction of Wing IDE 101, a free edition for beginning programmers
* Available as a .deb package for Debian and Ubuntu
* Support for Stackless Python
* Support for 64 bit Python on Windows and Linux

(*)'d items are available in Wing IDE Professional only.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).

*Purchasing & Upgrading*

Wing IDE Professional & Wing IDE Personal are commercial software and require
a license  to run.  To upgrade a 2.x license or purchase a new 3.x license:

Upgradehttps://wingware.com/store/upgrade
Purchase   https://wingware.com/store/purchase

Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost
1/2 the normal price to upgrade.

-- 

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com


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


Re: win32com.client documentation?

2007-10-24 Thread Colin J. Williams
Mark Morss wrote:
> I am a unix person, not new to Python, but new to Python programming
> on windows.  Does anyone know where to find documentation on
> win32com.client?  I have successfully installed this module and
> implemented some example code.  But a comprehensive explanation of the
> objects and methods available is nowhere to be found.  I have been
> able to find a somewhat out-of-date O'Reilly book, nothing more.
> 
> I want to be able to script the creation of Excel spreadsheets and
> Word documents, interract with Access data bases, and so forth.
> 
You might download  and install Mark 
Hammond's PythonWin.

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


Re: Hiding tracebacks from end-users

2007-10-24 Thread Matthew Woodcraft
Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
> I'm writing a command-line application that is meant to be relatively 
> user friendly to non-technical users.

> Consequently, I'd like to suppress Python's tracebacks if an error does 
> occur, replacing it with a more friendly error message. I'm doing 
> something like this:

>try:
>setup()
>do_something_useful()
>except KeyboardInterrupt:
>print >>sys.stderr, "User cancelled"
>sys.exit(2)
>except Exception, e:
>if expert_mode:
># experts get the full traceback with no hand-holding.
>raise
>else:
># print a more friendly error message
>if isinstance(e, AssertionError):
>msg = "An unexpected program state occurred"
>elif isinstance(e, urllib2.HTTPError):
>msg = "An Internet error occurred"
>else:
># catch-all for any other exception
>msg = "An error occurred"
>print>>sys.stderr, msg
>print>>sys.stderr, e
>sys.exit(1)
>else:
>sys.exit(0)

> Is this a good approach? Is there another way to suppress the traceback 
> and just print the error message?

There's traceback.format_exception_only().

If the exception value is a unicode object containing characters which
can't be encoded by sys.stderr's encoding, the code above will fail
(give an ugly traceback and fail to display the error message).

format_exception_only() would be less ugly, but it would still fail to
display the error message. So it's safest to check for this case
explicitly and encode with backslashreplace or similar.

In this situation I use bare except and sys.exc_info, rather than
'except Exception', because there are still libraries out there which
raise objects which aren't instances of Exception.

-M-

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


Re: Iteration for Factorials

2007-10-24 Thread marek . rocki
Tim Golden napisa (a):

> It's only a moment before the metaclass and
> the Twisted solution come along. :)

I couldn't resist. It's not as elegant as I hoped, but hey, at least
it memoizes the intermediate classes :-)


class fact_0(object):
value = 1

class fact_meta(object):
def __new__(cls, name, bases, attrs):
n = attrs['n']
class_name = 'fact_%i' % n
try:
return globals()[class_name]
except KeyError:
new_class = type(class_name, bases, {})
new_class.value = n * fact(n - 1).value
new_class.__str__ = lambda self: str(self.value)
globals()[class_name] = new_class
return new_class

class fact(object):
def __new__(self, n_):
class spanish_inquisition(object):
__metaclass__ = fact_meta
n = n_
return spanish_inquisition()

print fact(5)
print fact(3)
print fact(1)

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


Python and Combinatorics

2007-10-24 Thread none
Hello,

Is there some package to calculate combinatorical stuff like (n over 
k), i.e., n!/(k!(n - k!) ?

I know it can be written in about 3 lines of code, but still...

Thanks,

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


Re: for loop

2007-10-24 Thread Shawn Minisall
I agree, but if I want to get a A on the program, thats how my professor 
wants the output.

:)

[EMAIL PROTECTED] wrote:
> On Oct 22, 9:12?pm, Shawn Minisall <[EMAIL PROTECTED]> wrote:
>   
>> Thanks, everyone!  Using everyone's suggestions and points, the program
>> is working great now.  
>> 
>
> Actually, it's not. I assume not printing the population
> was a copy error.
>
> But, by adding the "if (p>1):", you have now made
> day 1 the initial population, so if you ask for
> 8 days of multiplication, you actually only get 7.
>
> Although your code is working, it's not giving you
> the correct answer. Most of the time in these kinds
> of problems, days means elapsed days. That means for
> 100 organisms @ 25% growth/day, there will be 125
> after 1 elapsed day. But that "if (p>1):" means you
> show 100 at day 1, which is wrong. You have 100 after
> 0 elapsed days (or day 0).
>
>
>   
>> Here's the updated code.
>>
>> :)
>>
>> import math
>>
>> def main():
>> #Declare and initialize variables
>> #starting number of organisms
>> organisms = 0
>> #average daily population increase as %
>> increase = 0.0
>> #number of days they will multiply
>> days = 0
>> #population prediction
>> population = 0.0
>>
>> #Intro
>> print "*"
>> print  "WELCOME TO THE POPULATION GROWTH CALCULATOR"
>> print "*"
>>
>> print "This program will predict the size of a population of organisms."
>> print
>> print
>> while organisms <=1:
>> organisms=input("Please enter the starting number of organisms: ")
>> if organisms <=1:
>> print "Error. Population must be at least two."
>>
>> while increase <=0:
>> increase=input("Please enter the average daily population
>> increase as a percentage (20% = .20): ")
>> if increase <=0:
>> print "The percent of increase must be positive."
>>
>> while days <=0:
>> days=input("Please enter the number of days that they will
>> multiply: ")
>> if days <=0:
>> print "The number of days must be positive."
>>
>> print " DayPopulation"
>> print "--"
>> population = organisms
>>
>> for p in range (1,days+1):
>> if(  p > 1 ):
>> population = population + ( population * increase )
>>
>> print "\t",p,
>>
>>
>>
>> [EMAIL PROTECTED] wrote:
>> 
>>> On Oct 22, 5:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>>>   
 On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
 
> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote:
>   
>> #Intro
>> print "*"
>> print  "WELCOME TO THE POPULATION GROWTH CALCULATOR"
>> print "*"
>> 
>> print "This program will predict the size of a population of 
>> organisms."
>> print
>> print
>> organisms=input("Please enter the starting number of organisms: ")
>> 
>> increase=input("Please enter the average daily population increase
>> as a percentage (20% = .20): ")
>> 
>> days=input("Please enter the number of days that they will multiply: 
>> ")
>> 
>> print " DayPopulation"
>> print "--"
>> 
>> for p in range (days):
>> 
>> population = organisms * population * increase
>> 
>> print days,
>> 
>> print "\t\t\t\t",population
>> 
>> I'm having problems with my for loop here to calculate estimated
>> population output to a table.  Instead of knowing how much I want to
>> loop it, the loop index is going to be whatever number of days the user
>> enters.  When I run my program, it asks the 3 questions above but then
>> just dead stops at a prompt which leads me to believe there's something
>> wrong with my loop.
>> 
> It should not run at all as it is indented inconsistently.  If that
> problem is corrected it will stop with a `NameError` because you try to
> read `population` before anything was assigned to it.
>   
> Ciao,
> Marc 'BlackJack' Rintsch
>   
 Also, I would guess that you want to print p, not days
 
>>> Oh, and your calculation is incorrect. You don't multiply by
>>> organisms in every loop iteration, organisms is the initial
>>> value of population, so you can solve the "Name" error by doing
>>> population = organisms before the for..loop.
>>>   
>>> And sin

Re: TeX pestilence (was Distributed RVS, Darcs, tech love)

2007-10-24 Thread Wildemar Wildenburger
Joachim Durchholz wrote:
> And yes, it sucks in major ways.
> 
Oh my God, I don't want to, but I just have to ask: Why?

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


Re: name space problem

2007-10-24 Thread BBands
Thank you.

jab

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


  1   2   >