Re: importing modules question

2007-10-17 Thread warhero
got it figured out. nevermind.

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


importing modules question

2007-10-17 Thread warhero
Hey all, sorry for the totally newb question. I recently switched over
to python from ruby. I'm having problems figuring out how module
importing works.. as a simple example I've got these files:

/example/loader.py
/example/loadee.py

loadee.py
class loadee(object):
def __init__(self):
print "loadee"

loader.py
import loadee
if __name__ == "__main__":
l = loadee()


When I run the loader file I get a TypeError: TypeError: 'module'
object is not callable

hm. Sorry, this is totally newb, this is the only switching pains I've
had.

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


Re: Best Python Linux distribution

2007-10-17 Thread James Matthews
Redhat and now Oracle's Linux installer is written in python! They are all
very good but watch for some programs that require legacy versions of
library's like wx

On 17 Oct 2007 23:10:33 -0700, Devraj <[EMAIL PROTECTED]> wrote:
>
> I would recommend a Debian based distribution like Ubuntu or Debian
> itself :)
>
> On Oct 17, 10:29 pm, Anthony Perkins <[EMAIL PROTECTED]> wrote:
> > Hi everyone,
> >
> > What is the best GNU/Linux distribution (or the most preferred) for
> > developing Python applications?  Ideally I would like one with both
> > Python *and* IDLE included on the install media (neither Ubuntu nor SUSE
> > have IDLE on the CDs), so that I can use it on machines without a
> > network connection.
> >
> > Thanks,
> >
> > -Anthony
> >
> > --
> > Anthony Perkins
> > muzz.be
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

Re: Last iteration?

2007-10-17 Thread Hendrik van Rooyen
"Raymond Hettinger"  wrote:

> More straight-forward version:
> 
> def lastdetecter(iterable):
> t, lookahead = tee(iterable)
> lookahead.next()
> return izip(chain(imap(itemgetter(0), izip(repeat(False),
> lookahead)), repeat(True)), t)

If this is what you call straightforward - heaven forfend
that I ever clap my orbs on something you call convoluted!

:-)

Faced with this problem, I would probably have used
enumerate with a look ahead and the IndexError would
have told me I am at the end...

- Hendrik

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


Re: Best Python Linux distribution

2007-10-17 Thread Devraj
I would recommend a Debian based distribution like Ubuntu or Debian
itself :)

On Oct 17, 10:29 pm, Anthony Perkins <[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
> What is the best GNU/Linux distribution (or the most preferred) for
> developing Python applications?  Ideally I would like one with both
> Python *and* IDLE included on the install media (neither Ubuntu nor SUSE
> have IDLE on the CDs), so that I can use it on machines without a
> network connection.
>
> Thanks,
>
> -Anthony
>
> --
> Anthony Perkins
> muzz.be


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


Re: Noob questions about Python

2007-10-17 Thread Ixiaus
> Right idea: now to remove all those intermediate lists you construct.
> 1. reversed(val) creates an iterator that runs over the elements (here
> of a string) in reverse order.
> 2. enumerate() is usually better than using an explicit list index.
> 3. You can use a generator in your sum to avoid constructing the final
> list.
>
> Applying these to your function, and noting that n << k is nicer than
> n * 2 ** k, we get a one-liner:
>
> def bin2dec(val):
> return sum(int(i) << k for k, i in enumerate(reversed(val)))
>
> Or a slightly nicer alternative is to filter the generator using 'if':
>
> def bin2dec(val):
> return sum(1 << k for k, i in enumerate(reversed(val)) if int(i))
>
> --
> Paul Hankin

Thank you for this reply, I only wish I could come up with functions
so elegantly refined!

I know '<<' is shifting x over by n bits; but could you point me to
some literature that would explain why it is the same as "x*2**n"?
(Googling only returns bit shift, but doesn't necessarily explain the
manner in which you are using it)

I will have to read up more on Generators, but maybe you can give me a
lowdown on why
sum([1 << k for k, i in enumerate(reversed(val)) if int(i)]) is less
efficient than using a Generator (is the generator a 'temporary'
list?)
sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

-- Parnell Springmeyer

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


Re: Noob questions about Python

2007-10-17 Thread Michele Simionato
On Oct 17, 5:58 pm, Ixiaus <[EMAIL PROTECTED]> wrote:

> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> print sum(res)
>
> It basically does the same thing int(string, 2) does.
>
> Thank you for the responses!

BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)

def baseN(number, N=2):
"""
>>> baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0
b = []
while number:
b.append(str(number % N))
number /= N
return ''.join(reversed(b))

   Michele Simionato

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


Embedded Boost.Python Enum

2007-10-17 Thread Cory
Hi,

I have a hopefully quick question about how to use Boost.Python to
export an Enum.
I am embedding python in C++ and am currently exporting my classes in
the following way:

nameSpace["OBJECT"] = class_("OBJECT")
.def("getType", &OBJECT::getType)
.def("setSprite", &OBJECT::setSprite);

So following this, I assumed that when exporting an enum the following
should work:

nameSpace["OBJECT_TYPE"] = enum_("OBJECT_TYPE")
.value("GENERIC_OBJECT",GENERIC_OBJECT)
.value("MAP_OBJECT",MAP_OBJECT)
.value("TOTAL_OBJECT_TYPES",TOTAL_OBJECT_TYPES)
.export_values();

while the above compiles, it causes the following run time exception:

AttributeError: 'NoneType' object has no attribute 'OBJECT_TYPE'

I took a look at the documentation and the only explanation I found
for enum appeared to be for extending python with modules. using the
following form:

BOOST_PYTHON_MODULE(enums)
{
enum_("color")
.value("red", red)
.value("green", green)
.export_values()
.value("blue", blue)
;

}

I COULD do the above, I would prefer the first method if possible. I
however do not know how to import the module if it is statically
linked because doing a simple import does not work and I am not
familiar enough with the boost.python library, Python C API, or Python
itself to know how to set it up. So My question is this:

How can I either make the first method of adding an enum work and not
throw the exception, OR once I create the BOOST_PYTHON_MODULE in an
embedded python c++ program how to I then import that module into my
embedded python?

Thanks in advance for any help

-Cory

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


Re: urlgrabber cookie handling?

2007-10-17 Thread Devraj
Hi John,

Thanks for getting back to me. I did find the ASPN article. If I
figure this out then I will make sure I post the code somewhere for
public consumption.

On Oct 18, 6:13 am, [EMAIL PROTECTED] (John J. Lee) wrote:
> Devraj <[EMAIL PROTECTED]> writes:
> > Hi everyone,
>
> > I have been battling to make my code work with a HTTPS proxy, current
> > my code uses urllib2 to to most things and works well, except that
> > urllib2 doesn't handle HTTPS proxies.
>
> > Urlgrabber (http://linux.duke.edu/projects/urlgrabber/help/
> > urlgrabber.grabber.html) looks very promising except that I can find a
> > way to handle cookies in urlgrabber. Is there a way urlgrabber can use
> > a HTTPCookieProcess or cookielib.CookieJar object to handle cookies?
>
> I don't see a nice way.  But then I don't see any HTTPS proxy support
> in urlgrabber... (I looked at version 3.1.0).
>
> There is a recipe or two on ASPN showing how to support HTTPS proxies
> with urllib2, which gives an idea how to do it, though the code is a
> bit rough (I'd post some code myself, but I did it for work).
>
> John


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


Re: Strange behaviour with reversed()

2007-10-17 Thread Andreas Kraemer
On Oct 17, 9:31 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I don't understand how reversed() is operating. I've read the description
> in the docs:
>
> reversed(seq)
> Return a reverse iterator. seq must be an object which supports the
> sequence protocol (the __len__() method and the __getitem__() method with
> integer arguments starting at 0). New in version 2.4.
>
> and help(reversed) but neither gives any insight to what happens when you
> use reversed() on a sequence, then modify the sequence.
>
> This works as I expected:
>
> >>> L = list("abc")
> >>> RL = reversed(L)
> >>> del L
> >>> list(RL)
>
> ['c', 'b', 'a']
>
> This suggests that reversed() makes a copy of the list:
>
> >>> L = list("abc")
> >>> RL = reversed(L)
> >>> L.append("d")
> >>> list(RL)
>
> ['c', 'b', 'a']
>
> This suggests that reversed() uses a reference to the original list:
>
> >>> RL = reversed(L)
> >>> L[0] = 'e'
> >>> list(RL)
>
> ['d', 'c', 'b', 'e']
>
> And these examples suggests that reversed() is confused, or at least
> confusing:
>
> >>> RL = reversed(L)
> >>> del L[2]
> >>> list(RL)
>
> []
>
> >>> L = list("abc")
> >>> RL = reversed(L)
> >>> L.insert(0, "d")
> >>> L
>
> ['d', 'a', 'b', 'c']>>> list(RL)
>
> ['b', 'a', 'd']
>
> Does anyone know what reversed() is actually doing?
>
> --
> Steven.

Without knowing the internals, it seems reversed() does exactly the
same as the following class:


class Reversed(object):
  def __init__(self,seq):
self.seq = seq
self.i = len(seq)
  def __iter__(self):
return self
  def next(self):
self.i -= 1
if self.i < 0:
  raise StopIteration
else:
  return self.seq[self.i]

so it doesn't copy anything, just book-keeping of indexes. I guess one
would call this kind of object a (special) "view" of the sequence.

Cheers,

Andreas

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


Re: Strange behaviour with reversed()

2007-10-17 Thread Gabriel Genellina
En Thu, 18 Oct 2007 01:31:13 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:

> I don't understand how reversed() is operating. I've read the description
> in the docs:
>
> reversed(seq)
> Return a reverse iterator. seq must be an object which supports the
> sequence protocol (the __len__() method and the __getitem__() method with
> integer arguments starting at 0). New in version 2.4.
>
> and help(reversed) but neither gives any insight to what happens when you
> use reversed() on a sequence, then modify the sequence.

A reversed object is rather simple: it stores the original sequence (a  
reference, as usual, not a copy!) and the next index to use, starting at  
len-1. Each time the next() method is called, the index is decremented  
until it goes below 0.
This is more or less the equivalent Python code:

class Reversed:
 def __init__(self, seq):
 n = len(seq)
 self.index = n-1
 self.seq = seq

 def __iter__(self):
 return self

 def next(self):
 index = self.index
 if index>=0:
 try: item = self.seq[index]
 except (IndexError,StopIteration): pass
 else:
 self.index -= 1
 return item
 self.index = -1
 self.seq = None
 raise StopIteration

Note that the starting index is determined at creation time, not when the  
iteration begins. So, if you create a reversed object over a list  
containing 3 elements, the first returned element will be seq[2], then  
seq[1], then seq[0]. It doesn't matter if you modify the list after  
creating the reversed object but before starting the iteration: it will  
start at seq[2] even if it's not the last item, and will silently stop if  
seq[2] is not a valid index anymore.

-- 
Gabriel Genellina

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


Re: Noob questions about Python

2007-10-17 Thread George Sakkis
On Oct 17, 6:23 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 17, 10:58 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
>
>
>
> > Thank you for the quick responses.
>
> > I did not know that about integer literals beginning with a '0', so
> > thank you for the explanation. I never really use PHP except for
> > handling basic forms and silly web stuff, this is why I picked up
> > Python because I want to teach myself a more powerful and broad
> > programming language.
>
> > With regard to why I asked: I wanted to learn about Binary math in
> > conjunction with Python, so I wrote a small function that would return
> > a base 10 number from a binary number. It is nice to know about the
> > int() function now.
>
> > Just for the sake of it, this was the function I came up with:
>
> > def bin2dec(val):
> > li = list(val)
> > li.reverse()
> > res = [int(li[x])*2**x for x in range(len(li))]
> > res.reverse()
> > print sum(res)
>
> > Now that I look at it, I probably don't need that last reverse()
> > because addition is commutative...
>
> > def bin2dec(val):
> > li = list(val)
> > li.reverse()
> > res = [int(li[x])*2**x for x in range(len(li))]
> > print sum(res)
>
> Right idea: now to remove all those intermediate lists you construct.
> 1. reversed(val) creates an iterator that runs over the elements (here
> of a string) in reverse order.
> 2. enumerate() is usually better than using an explicit list index.
> 3. You can use a generator in your sum to avoid constructing the final
> list.
>
> Applying these to your function, and noting that n << k is nicer than
> n * 2 ** k, we get a one-liner:
>
> def bin2dec(val):
> return sum(int(i) << k for k, i in enumerate(reversed(val)))
>
> Or a slightly nicer alternative is to filter the generator using 'if':
>
> def bin2dec(val):
> return sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

Changing the condition to if i=='1' makes it than twice faster.
There's also a small improvement by looping forward rather than
reversed:

def bin2dec_2(val):
n = len(val)-1
return sum(1<>= 1
if bit == '1':
s += p
return s

And here's the benchmark:

if __name__ == '__main__':
# uncomment for Psyco
# import psyco; psyco.full()
import timeit
setup = 'import __main__; bin="101001010001001010"'
for func in bin2dec, bin2dec_2, bin2dec_3:
name = func.__name__
timer = timeit.Timer('__main__.%s(bin)' % name, setup)
print '%s: %s' % (name, timer.timeit())

### Without Psyco 
bin2dec: 17.6126108206
bin2dec_2: 7.57195732977
bin2dec_3: 5.46163297291

### With Psyco 
bin2dec: 17.6995679618
bin2dec_2: 8.60846224869
bin2dec_3: 0.16031255369

George

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


Re: Strange behaviour with reversed()

2007-10-17 Thread Ben Finney
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> and help(reversed) but neither gives any insight to what happens
> when you use reversed() on a sequence, then modify the sequence.

I would think the answer is the same for any question about modifying
sequences while iterating: "undefined, therefore don't do that".

In other words, if you think you'll be modifying the sequence during
iteration (even if you're iterating indirectly via something like
reversed()), iterate over a copy instead.

-- 
 \   "Professionalism has no place in art, and hacking is art. |
  `\  Software Engineering might be science; but that's not what I |
_o__)do. I'm a hacker, not an engineer."  -- Jamie W. Zawinski |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-17 Thread Ben Finney
Xah Lee <[EMAIL PROTECTED]> writes:

> Elisp Tutorial: HTML Syntax Coloring Code Block

Utterly irrelevant to most of the groups in the Newsgroups field.

Followups set to comp.lang.lisp and comp.emacs only, please.

-- 
 \ "[The RIAA] have the patience to keep stomping. They're playing |
  `\  whack-a-mole with an infinite supply of tokens."  -- kennon, |
_o__) http://kuro5hin.org/ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Script to Download Ubuntu Gutsy ASAP

2007-10-17 Thread danfolkes
I thought I would post the source to a program that I made that will
download the http://ubuntu.media.mit.edu/ubuntu-releases/gutsy/
as soon as its posted.

It checks the site every 10 min time.sleep(600)

This is mostly untested so I would appreciate comments, and if you use
it, post that too! :)


import time
import urllib

mysock = urllib.urlopen("http://ubuntu.media.mit.edu/ubuntu-releases/
gutsy/ubunt
u-7.10-desktop-i386.iso")
#print mysock
while 1:
image = mysock.read()
if image[0:1]!='<':
oFile = open(r"image.iso",'wb')
oFile.write(image)
oFile.close
break
exit
print "Wait ", time.localtime()
time.sleep(600)




enjoy,
Daniel Folkes
[EMAIL PROTECTED]
http://danfolkes.com

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


Re: Last iteration?

2007-10-17 Thread Paul Rubin
Raymond Hettinger <[EMAIL PROTECTED]> writes:
> We need a C-speed verion of the lambda function, something like a K
> combinator that consumes arguments and emits constants.

Some discussion of this is at .
I had suggested implementing K through an optional second arg for a
proposed identity function but everyone hated that.  I'm amused.  I
had suggested it because I thought that it would be easier than
getting two separate functions accepted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Labs Move

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 19:46:47 -0300, Bill Garey <[EMAIL PROTECTED]>  
escribió:

> What is PYTHON 2.2.1   and what does it do? I see  the Program on my  
> list of programs but don't know how to use it ,  or what it is!

See this FAQ entry: http://www.python.org/doc/faq/installed/

-- 
Gabriel Genellina

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


Re: Bidirectional communication over unix socket (named pipe)

2007-10-17 Thread Raúl Gómez C.
This is the code I'm running (just the server):

#!/usr/bin/python
import socket
import os, os.path
import time

if os.path.exists("hpcd_sock"):
os.remove("hpcd_sock")

server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind("hpcd_sock")

while True:
datagram = server.recv(1024)
if not datagram:
break
print datagram
# the preceding works, and I see the TEST TEST TEST statement the client
sent

time.sleep(2)
# it dies on the next statement.
server.send("Thank you\n")

server.close()
if os.path.exists("hpcd_sock"):
os.remove("hpcd_sock")


And this is the error that its giving me:

Traceback (most recent call last):
  File "server_socket.py", line 13, in 
datagram = server.recv(1024)
socket.error: (22, 'Invalid argument')
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: if instance exists problem ..

2007-10-17 Thread Gabriel Genellina
En Thu, 18 Oct 2007 00:07:34 -0300, Steven D'Aprano  
<[EMAIL PROTECTED]> escribió:

> On Thu, 18 Oct 2007 03:00:56 +, Steven D'Aprano wrote:
>
>> On Wed, 17 Oct 2007 23:12:15 +, Paul Hankin wrote:
>>
>>> 'if x' doesn't test if x exists, it tests if x when cast to a bool is
>>> True.
>>
>> To be pedantic:
>>
>> Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
>> creates a brand new Boolean object from x.
>
> Actually, to be even more pedantic, True and False are both singletons,
> and so bool() doesn't actually create a new Boolean object but reuses the
> existing ones.

To be even more pedantic, 'if x' does not invoke the builtin bool(),  
instead it uses PyObject_IsTrue, which returns a plain C integer, not a  
Python bool object.

-- 
Gabriel Genellina

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


Re: Bidirectional communication over unix socket (named pipe)

2007-10-17 Thread Raúl Gómez C.
Nop, it doesn't work, at least for me (python 2.5)...

On 10/18/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>
>
> As I understand the OP's own response, changing SOCK_DGRAM to SOCK_STREAM
> here solved the issue.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Bidirectional communication over unix socket (named pipe)

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 18:20:06 -0300, Raúl Gómez C. <[EMAIL PROTECTED]>  
escribió:

> BTW: This is the original post:
>
>
> server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

As I understand the OP's own response, changing SOCK_DGRAM to SOCK_STREAM  
here solved the issue.

-- 
Gabriel Genellina

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


Strange behaviour with reversed()

2007-10-17 Thread Steven D'Aprano
I don't understand how reversed() is operating. I've read the description 
in the docs:

reversed(seq)
Return a reverse iterator. seq must be an object which supports the 
sequence protocol (the __len__() method and the __getitem__() method with 
integer arguments starting at 0). New in version 2.4. 

and help(reversed) but neither gives any insight to what happens when you 
use reversed() on a sequence, then modify the sequence.


This works as I expected:

>>> L = list("abc")
>>> RL = reversed(L)
>>> del L
>>> list(RL)
['c', 'b', 'a']

This suggests that reversed() makes a copy of the list:

>>> L = list("abc")
>>> RL = reversed(L)
>>> L.append("d")
>>> list(RL)
['c', 'b', 'a']

This suggests that reversed() uses a reference to the original list:

>>> RL = reversed(L)
>>> L[0] = 'e'
>>> list(RL)
['d', 'c', 'b', 'e']

And these examples suggests that reversed() is confused, or at least 
confusing:

>>> RL = reversed(L)
>>> del L[2]
>>> list(RL)
[]

>>> L = list("abc")
>>> RL = reversed(L)
>>> L.insert(0, "d")
>>> L
['d', 'a', 'b', 'c']
>>> list(RL)
['b', 'a', 'd']


Does anyone know what reversed() is actually doing?



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


Re: Pull Last 3 Months

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 21:47:50 -0300, Tim Chase  
<[EMAIL PROTECTED]> escribió:

> In the event that you need them in whatever your locale is, you
> can use the '%b' formatting to produce them:

I prefer the calendar module in that case:

py> import locale
py> locale.setlocale(locale.LC_ALL, '')
'Spanish_Argentina.1252'
py>
py> import calendar
py> calendar.month_abbr[12]
'Dic'
py> def prev_months(since, howmany):
...   return [calendar.month_abbr[(since.month-i-2) % 12 + 1] for i in  
range(how
many)]
...
py> import datetime
py> prev_months(datetime.datetime(2005,2,10), 4)
['Ene', 'Dic', 'Nov', 'Oct']
py> prev_months(datetime.datetime(2005,10,17), 3)
['Sep', 'Ago', 'Jul']

-- 
Gabriel Genellina

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


Re: Simple Text Processing Help

2007-10-17 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>And now for something completely different...
>
>I've been reading up a bit about Python and Excel and I quickly told
>the program to output to Excel quite easily.  However, what if the
>input file were a Word document?  I can't seem to find much
>information about parsing Word files.  What could I add to make the
>same program work for a Word file?

Word files are not human-readable.  You parse them using
Dispatch("Word.Application"), just the way you wrote the Excel file.

I believe there are some third-party modules that will read a Word file a
little more directly.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-17 Thread Xah Lee
Elisp Tutorial: HTML Syntax Coloring Code Block

Xah Lee, 2007-10

This page shows a example of writing a emacs lisp function that
process a block of text to syntax color it by HTML tags. If you don't
know elisp, first take a gander at Emacs Lisp Basics.

HTML version with color and links is at:
http://xahlee.org/emacs/elisp_htmlize.html

---
THE PROBLEM

SUMMARY

I want to write a elisp function, such that when invoked, the block of
text the cursor is on, will have various HTML style tags wrapped
around them. This is for the purpose of publishing programing language
code in HTML on the web.

DETAIL

I write a lot computer programing tutorials for several computer
languages. For example: Perl and Python tutorial, Java tutorial, Emacs
Lisp tutorial, Javascript tutorial. In these tutorials, often there
are code snippets. These code need to be syntax colored in HTML.

For example, here's a elisp code snippet:

(if (< 3 2)  (message "yes") )

Here's what i actually want as raw HTML:

(if (< 3 2)  (message "yes") )

Which should looks like this in a web browser:

(if (< 3 2)  (message "yes") )

There is a emacs package that turns a syntax-colored text in emacs to
HTML form. This is extremely nice. The package is called htmlize.el
and is written (1997,...,2006) by Hrvoje Niksic, available at
http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.

This program provides you with a few new emacs commands. Primarily, it
has htmlize-region, htmlize-buffer, htmlize-file. The region and
buffer commands will output HTML code in a new buffer, and the htmlize-
file version will take a input file name and output into a file.

When i need to include a code snippet in my tutorial, typically, i
write the code in a separate file (e.g. “temp.java”, “temp.py”), run
it to make sure the code is correct (compile, if necessary), then,
copy the file into the HTML tutorial page, inside a «pre» block. In
this scheme, the best way for me to utilize htmlize.el program is to
use the “html-buffer” command on my temp.java, then copy the htmlized
output and paste that into my HTML tutorial file inside a «pre» block.
Since many of my tutorials are written haphazardly over the years
before seeing the need for syntax coloration, most exist inside «pre»
tags already without a temp code file. So, in most cases, what i do is
to select the text inside the «pre» tag, paste into a temp buffer and
invoke the right mode for the language (so the text will be fontified
correctly), then do htmlize-buffer, then copy the html output, then
paste back to replace the selected text.

This process is tedious. A tutorial page will have several code
blocks. For each, i will need to select text, create a buffer, switch
mode, do htmlize, select again, switch buffer, then paste. Many of the
steps are not pure push-buttons operations but involves eye-balling.
There are few hundred such pages.

It would be better, if i can place the cursor on a code block in a
existing HTML page, then press a button, and have emacs magically
replace the code block with htmlized version colorized for the code
block's language. We proceed to write this function.

---
SOLUTION

For a elisp expert who knows how fontification works in emacs, the
solution would be writing a elisp code that maps emacs's string's
fontification info into html tags. This is what htmlize.el do exactly.
Since it is already written, a elisp expert might find the essential
code in htmlize.el. (the code is licensed under GPL) .

Unfortunately, my lisp experience isn't so great. I spent maybe 30
minutes tried to look in htmlize.html in hope to find a function
something like htmlize-str that is the essence, but wasn't successful.
I figured, it is actually faster if i took the dumb and inefficient
approach, by writing a elisp code that extracts the output from
htmlize-buffer. Here's the outline of the plan of my function:

* 1. Grab the text inside a ... tag.
* 2. Create a new buffer. Paste the code in.
* 3. Make the new buffer «lang» mode (and fontify it)
* 4. Call htmlize-buffer
* 5. Grab the (htmlized) text inside «pre» tag in the htmlize
created output buffer.
* 6. Kill the htmlize buffer and my temp buffer.
* 7. Delete the original text, paste in the new text.

To achieve the above, i decided on 2 steps. A: Write a function
“htmlize-string” that takes a string and mode name, and returns the
htmlized string. B: Write a function “htmlize-block” that does the
steps of grabbing text and pasting, and calls “htmlize-string” for the
actual htmlization.

Here's the code of my htmlize-string function:

(defun htmlize-string (ccode mn)
"Take string ccode and return htmlized code, using mode mn.\n
This function requries the htmlize-mode.el by Hrvoje Niksic, 2006"
(let (cur-buf temp-buf temp-buf2 x1 x2 resultS)
(setq cur-buf (buffer-name))
(setq temp-buf "xout-weewee")
(setq temp-buf2 "*html*") ;; the buffer that htmlize-b

Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 18:03:56 -0300, Debajit Adhikary <[EMAIL PROTECTED]>  
escribió:

> What in general is a good way to learn about little things like these?
> (I'm fairly new to the language)
>
> A google search for 'python list methods" did not turn up the +
> operator anywhere for me. Where could I find the official
> documentation for built in structures like the list?

Operators are hard to find... For the available list methods, see  
http://docs.python.org/lib/typesseq.html and  
http://docs.python.org/lib/typesseq-mutable.html
 From the Library Reference, you should read at least section 2 (Built-in  
Objects) and section 3 (Built-in types), and the remaining section titles  
so you know they exist at least.

-- 
Gabriel Genellina

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


Re: Need recommendations on mock object packages

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 13:42:25 -0300, Matthew Wilson <[EMAIL PROTECTED]>  
escribió:

> What are the most popular, easiest to use, and most powerful mock
> object packages out there?

mock libraries were discussed recently on this list, search the archives.
I like minimock: http://blog.ianbicking.org/minimock.html

-- 
Gabriel Genellina

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


Re: Noob questions about Python

2007-10-17 Thread hg
Ixiaus wrote:

> I have recently (today) just started learning/playing with Python. So
> far I am excited and impressed (coming from PHP background).
> 
> I have a few questions regarding Python behavior...
> 
> val = 'string'
> li = list(val)
> print li.reverse()
> 
> returns nothing, but,
> 
> val = 'string'
> li = list(val)
> li.reverse()
> print li
> 
> returns what I want. Why does Python do that?
> 
> Also I have been playing around with Binary math and noticed that
> Python treats:
> 
> val = 00110
> 
> as the integer 72 instead of returning 00110, why does Python do that?
> (and how can I get around it?)
> 
> Grateful for any replies!

li.reverse does not return a list but reverses the list itself and return
Noe

0xxx tells python that you work in octal.

hg




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


Re: if instance exists problem ..

2007-10-17 Thread Steven D'Aprano
On Thu, 18 Oct 2007 03:00:56 +, Steven D'Aprano wrote:

> On Wed, 17 Oct 2007 23:12:15 +, Paul Hankin wrote:
> 
>> 'if x' doesn't test if x exists, it tests if x when cast to a bool is
>> True.
> 
> To be pedantic:
> 
> Python doesn't have type casts. bool(x) doesn't cast x as a bool, it
> creates a brand new Boolean object from x.

Actually, to be even more pedantic, True and False are both singletons, 
and so bool() doesn't actually create a new Boolean object but reuses the 
existing ones.


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


Re: Write by logging.FileHandler to one file by many processess

2007-10-17 Thread Gabriel Genellina
En Wed, 17 Oct 2007 11:10:55 -0300, Diez B. Roggisch <[EMAIL PROTECTED]>  
escribió:

>> On Oct 17, 3:33 pm, Rafa  Zawadzki <[EMAIL PROTECTED]> wrote:
>>>
>>> As I saw in logging source - there is no lock per file during making
>>> emit() (only lock per thread).
>>>
>>> So, my question is - is it safe to log into one file using many
>>> processess uses logging logger?
>
> I presume things get messed up... but I don't know for sure.

Yes, output from several processes comes horribly mixed...
I've avoided it using separate log files for each process; but if that's  
not possible, one could try using syslog or a SocketHandler and a separate  
listening process.

-- 
Gabriel Genellina

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Steven D'Aprano
On Wed, 17 Oct 2007 21:40:40 +, Paul Hankin wrote:

> On Oct 17, 10:03 pm, Debajit Adhikary <[EMAIL PROTECTED]> wrote:
>> How does "a.extend(b)" compare with "a += b" when it comes to
>> performance? Does a + b create a completely new list that it assigns
>> back to a? If so, a.extend(b) would seem to be faster. How could I
>> verify things like these?
> 
> Use a += b rather than a.extend(b): I'm not sure what I was thinking.

Neither am I. Why do you say that?


> Anyway, look at 'timeit' to see how to measure things like this, but my
> advice would be not to worry and to write the most readable code - and
> only optimise if your code's runnign too slowly.

Always good advice, but of course what a person considers "the most 
readable code" changes with their experience.

 
> To answer your question though: a += b is *not* the same as a = a + b.


It might be. It depends on what a and b are.



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


Re: if instance exists problem ..

2007-10-17 Thread Steven D'Aprano
On Wed, 17 Oct 2007 23:12:15 +, Paul Hankin wrote:

> 'if x' doesn't test if x exists, it tests if x when cast to a bool is
> True.

To be pedantic:

Python doesn't have type casts. bool(x) doesn't cast x as a bool, it 
creates a brand new Boolean object from x.

Also, the "if x" test looks at x.__nonzero__() first, and if that method 
doesn't exist, it looks to see if x.__len__() returns 0 or not. See

http://docs.python.org/ref/customization.html


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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Steven D'Aprano
On Wed, 17 Oct 2007 23:46:25 +, Debajit Adhikary wrote:

> On Oct 17, 5:40 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>> To answer your question though: a += b is *not* the same as a = a + b.
>> The latter would create a new list and assign it to a, whereas a += b
>> updates a in-place.
> 
> I know I'm being a little finicky here, but how would someone know that
> a+=b is not the same as a=a+b?
> Any documentation or reference that mentions this?

Have you Read The Fine Manual at the Fine Website?

Try typing "Python documentation" into your favourite search engine, or 
try going to http://www.python.org/ which links directly to
http://www.python.org/doc/

Unfortunately, searching for operators is always tricky (try searching 
for "*" some day...) but the section you want is here:

http://docs.python.org/ref/augassign.html


Also, it isn't always true that a += b is not the same as a = a+b. It 
depends on what a and b are.


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


[Fwd: Re: why doesn't have this list a "reply-to" ?]

2007-10-17 Thread Colin J. Williams


 Original Message 
Subject: Re: why doesn't have this list 
a "reply-to" ?
Date: Wed, 17 Oct 2007 11:13:49 +0900
From: Byung-Hee HWANG <[EMAIL PROTECTED]>
Reply-To: [EMAIL PROTECTED]
Organisation: InZealBomb
To: python-list@python.org
Newsgroups: gmane.comp.python.general
References: <[EMAIL PROTECTED]>

On Tue, 2007-10-16 at 23:45 +0200, stef 
mientki wrote:
> hello,
> 
> I'm always have great difficulties, replying to this beautiful and 
> helpful list.
> 
> When I hit the reply button,
> the message is sent personally to the sender and not to the list.
> I've subscribed to dozen's of lists,
> and all have an "reply-to" address, that points to list and not to the 
> individual.

Just click "Ctrl-L", then you can reply 
to lists directly if you use
good mailer like mutt or thunderbird or 
evolution ;;


^L doesn't work for me with Thunderbird 
2.0.0.6

With some lists, Reply goes to the 
sender.  ReplyAll goes to the sender, 
the list and anyone with a cc:

With Python on news.gmane.org, Reply 
goes to the list and ReplyAll is as above.

Colin W.
-- 
Byung-Hee HWANG <[EMAIL PROTECTED]>

"I need a guy I can trust."
"Yeah, OK, let me think about it."
-- Johnny Fontane and Nino Valenti, 
"Chapter 12", page 177
-- 
http://mail.python.org/mailman/listinfo/python-list

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


Re: Noob questions about Python

2007-10-17 Thread [EMAIL PROTECTED]
On Oct 17, 4:58 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
> Thank you for the quick responses.
>
> I did not know that about integer literals beginning with a '0', so
> thank you for the explanation. I never really use PHP except for
> handling basic forms and silly web stuff, this is why I picked up
> Python because I want to teach myself a more powerful and broad
> programming language.
>
> With regard to why I asked: I wanted to learn about Binary math in
> conjunction with Python, so I wrote a small function that would return
> a base 10 number from a binary number. It is nice to know about the
> int() function now.
>
> Just for the sake of it, this was the function I came up with:
>
> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> res.reverse()
> print sum(res)
>
> Now that I look at it, I probably don't need that last reverse()
> because addition is commutative...
>
> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> print sum(res)
>
> It basically does the same thing int(string, 2) does.
>
> Thank you for the responses!

You could also get ahold of the gmpy module. You get conversion
to binary and also some useful other binary functions as shown
below:

# the Collatz Conjecture in binary

import gmpy

n = 27
print '%4d %s' % (n,gmpy.digits(n,2).zfill(16))

sv = []  # sequence vector, blocks of contiguous LS 0's

while n != 1:
  old_n = n
  n = 3*n + 1  # result always even
  f = gmpy.scan1(n,0)  # find least significant 1 bit
  n >>= f  # remove LS 0's in one fell swoop
  sv.append(f) # record f sequence
  PopC = gmpy.popcount(n)  # count of 1 bits
  HamD = gmpy.hamdist(n,old_n) # bits changed
  print '%4d %s' % (n,gmpy.digits(n,2).zfill(16)),
  print 'PopC:%2d  HamD:%2d' % (PopC,HamD)

print sv

##  27 00011011
##  41 00101001 PopC: 3  HamD: 3
##  31 0001 PopC: 5  HamD: 4
##  47 0010 PopC: 5  HamD: 2
##  71 01000111 PopC: 4  HamD: 3
## 107 01101011 PopC: 5  HamD: 3
## 161 1011 PopC: 3  HamD: 4
## 121 0001 PopC: 5  HamD: 4
##  91 01011011 PopC: 5  HamD: 2
## 137 10001001 PopC: 3  HamD: 4
## 103 01100111 PopC: 5  HamD: 6
## 155 10011011 PopC: 5  HamD: 6
## 233 11101001 PopC: 5  HamD: 4
## 175 1010 PopC: 6  HamD: 3
## 263 00010111 PopC: 4  HamD: 4
## 395 000110001011 PopC: 5  HamD: 3
## 593 001001010001 PopC: 4  HamD: 7
## 445 00011001 PopC: 7  HamD: 7
## 167 10100111 PopC: 5  HamD: 4
## 251 1011 PopC: 7  HamD: 4
## 377 00010001 PopC: 6  HamD: 3
## 283 000100011011 PopC: 5  HamD: 3
## 425 000110101001 PopC: 5  HamD: 4
## 319 00010011 PopC: 7  HamD: 4
## 479 00011101 PopC: 8  HamD: 3
## 719 00101100 PopC: 7  HamD: 3
##1079 01110111 PopC: 6  HamD: 7
##1619 011001010011 PopC: 6  HamD: 4
##2429 10010101 PopC: 8  HamD: 8
## 911 00111000 PopC: 7  HamD: 7
##1367 010101010111 PopC: 7  HamD: 6
##2051 1011 PopC: 3  HamD: 6
##3077 11000101 PopC: 4  HamD: 3
## 577 00100101 PopC: 3  HamD: 5
## 433 000110110001 PopC: 5  HamD: 6
## 325 000101000101 PopC: 4  HamD: 5
##  61 0001 PopC: 5  HamD: 5
##  23 00010111 PopC: 4  HamD: 3
##  35 00100011 PopC: 3  HamD: 3
##  53 00110101 PopC: 4  HamD: 3
##   5 0101 PopC: 2  HamD: 2
##   1 0001 PopC: 1  HamD: 1
##[1, 2, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2,
## 1, 1, 1, 2, 3, 1, 1, 2, 1, 2, 1, 1, 1,
## 1, 1, 3, 1, 1, 1, 4, 2, 2, 4, 3, 1, 1,
## 5, 4]

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


Re: Pull Last 3 Months

2007-10-17 Thread Ben Finney
John Machin <[EMAIL PROTECTED]> writes:

> It's a bit hard to see how anybody could imagine that in the expression
> [months[(month - i - 1) % 12] for i in range(n)]
> the number 12 referred to anything but the number of months in a year.

Exactly, that's what people *will* assume. But what if they're wrong,
and you're using the number 12 for some other semantic purpose? If the
programmer has encountered this type of betrayed assumption before,
they'll never be entirely sure that a bare '12' in the code means what
they think it means. And the code doesn't say anything about why the
number was used, so they're left to guess.

Of course, in such a trivial example, it is almost unthinkable that
the number 12 would mean anything else; but the entire point of the
principle of not using magic numbers is that you don't have to wonder
about when that line is crossed.

Better to be explicit about it, in every case, IMO.

-- 
 \ "Money is always to be found when men are to be sent to the |
  `\   frontiers to be destroyed: when the object is to preserve them, |
_o__)  it is no longer so."  -- Voltaire, _Dictionnaire Philosophique_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Labs Move

2007-10-17 Thread Terry Reedy

"Bill Garey" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|What is PYTHON 2.2.1   and what does it do?

It is the interpreter for the 2.2 version of the Python language.
See the tutorial at python.org.

| I see  the Program on my list of programs but don't know how to use it , 
or what it is!

If you have a windows machine, the maker probably is using it for some of 
their 'value added' administrative scripts.

tjr



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


Re: Pull Last 3 Months

2007-10-17 Thread John Machin
On 18/10/2007 10:33 AM, Ben Finney wrote:
> Paul Hankin <[EMAIL PROTECTED]> writes:
> 
>> import datetime
>>
>> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
>>
>> def last_months(n):
>> month = datetime.date.today().month
>> return [months[(month - i - 1) % 12] for i in range(n)]
>>
>> print last_months(3)
> 
> Heck you don't even need the magic number 12 in there.
> 
> import datetime
> 
> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()

Heck if you really want to be anal, you could even guard against a typo 
(or one of those spaces actually being '\xA0' [seen it happen]) by 
adding in here:
   MONTHS_IN_YEAR = 12
   assert len(months) == MONTHS_IN_YEAR

> def last_months(n):
> month = datetime.date.today().month
> return [months[(month - i - 1) % len(months)
> for i in range(n)]
> 
> In general I try to avoid magic numbers: always be explicit about the
> semantic purpose of the number, either by binding a meaningful name to
> it and only using that reference thereafter, or showing how that value
> is derived.
> 

It's a bit hard to see how anybody could imagine that in the expression
 [months[(month - i - 1) % 12] for i in range(n)]
the number 12 referred to anything but the number of months in a year.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to generate alternate toggling values in a loop?

2007-10-17 Thread Grant Edwards
On 2007-10-17, Debajit Adhikary <[EMAIL PROTECTED]> wrote:

> # Start of Code
>
> def evenOdd():
> values = ["Even", "Odd"]
> state = 0
> while True:
> yield values[state]
> state = (state + 1) % 2

I'd replace the last line with
 
  state ^= 1

to save a couple instructions, but I spend too much time
working with micoroprocessors running on clocks measured in the
KHz.

There are probably other more Pythonic ways...

-- 
Grant Edwards   grante Yow!  My EARS are GONE!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why doesn't have this list a "reply-to" ?

2007-10-17 Thread Robert Kern
[david] wrote:
> Steve Lamb wrote:
>> On 2007-10-17, Byung-Hee HWANG <[EMAIL PROTECTED]> wrote:
>>> Just click "Ctrl-L", then you can reply to lists directly if you use
>>> good mailer like mutt or thunderbird or evolution ;; 
>> Thunderbird only if it has the list-reply patch, has either enigmail or
>> mhengy installed and has the reply-to-list addon installed.  Otherwise, no,
>> Thunderbird still, years later, lacks that feature.  Part of the reason why I
>> am test driving gmane in slrn right now.  :)
> 
> I'm using Thunderbird 2.0.0.0: I use the right-click menu.

And click what? I have Thunderbird 2.0.0.6 on OS X and only see "Reply to Sender
Only" and "Reply to All".

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Pull Last 3 Months

2007-10-17 Thread John Machin
On Oct 18, 8:56 am, Shane Geiger <[EMAIL PROTECTED]> wrote:
> A simpler way, imho:
>
> import datetime
> m = {
> 1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
>
> month = datetime.date.today().month
> if month == 1:
> ans = [m[11], m[12], m[1]]
> elif month == 2:
> ans = [m[11], m[12], m[1]]
> else:
> ans = [m[month-2], m[month-1], m[month]]
> print ans
>

1. Why use a dict?
2. The if-elif-else caper doesn't scale well; suppose the OP want to
"pull" the previous 6 months. The % operator is your friend.
Try this:

>>> m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
>>> 'Nov', 'Dec']
>>> for mo in range(1, 13):
...print mo, [m[(mo - x - 2) % 12] for x in range(3)]
...
1 ['Dec', 'Nov', 'Oct']
2 ['Jan', 'Dec', 'Nov']
3 ['Feb', 'Jan', 'Dec']
4 ['Mar', 'Feb', 'Jan']
5 ['Apr', 'Mar', 'Feb']
6 ['May', 'Apr', 'Mar']
7 ['Jun', 'May', 'Apr']
8 ['Jul', 'Jun', 'May']
9 ['Aug', 'Jul', 'Jun']
10 ['Sep', 'Aug', 'Jul']
11 ['Oct', 'Sep', 'Aug']
12 ['Nov', 'Oct', 'Sep']
>>> for mo in range(1, 13):
...print mo, [m[(mo - x - 2) % 12] for x in range(6)]
...
1 ['Dec', 'Nov', 'Oct', 'Sep', 'Aug', 'Jul']
2 ['Jan', 'Dec', 'Nov', 'Oct', 'Sep', 'Aug']
...snip...
11 ['Oct', 'Sep', 'Aug', 'Jul', 'Jun', 'May']
12 ['Nov', 'Oct', 'Sep', 'Aug', 'Jul', 'Jun']
>>>

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


Re: why doesn't have this list a "reply-to" ?

2007-10-17 Thread [david]
Steve Lamb wrote:
> On 2007-10-17, Byung-Hee HWANG <[EMAIL PROTECTED]> wrote:
>> Just click "Ctrl-L", then you can reply to lists directly if you use
>> good mailer like mutt or thunderbird or evolution ;; 
> 
> Thunderbird only if it has the list-reply patch, has either enigmail or
> mhengy installed and has the reply-to-list addon installed.  Otherwise, no,
> Thunderbird still, years later, lacks that feature.  Part of the reason why I
> am test driving gmane in slrn right now.  :)
> 

I'm using Thunderbird 2.0.0.0: I use the right-click menu.

[david]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI and external JavaScript nightmare

2007-10-17 Thread IamIan
Thank you for the replies. After a lot of research I tracked down the
issue. I was using the CGI to build all of the pages for the site,
then filling in content with .innerHTML= as users clicked on tabs.
Since I wanted to place the Google Ads in different parts of each
page, the Google Ads JavaScript was in each page chunk being
dynamically placed with .innerHTML.

It turns out that JavaScript isn't executed when it is placed in a
page via .innerHTML. I tried some tricks to execute it after it was
added to the page (eval, appendChild) but it still didn't work. The
Google Ads JavaScript is very touchy and their agreement is very
strict; it wasn't even clear that what I was doing was in line with
it, so I broke the site up into multiple CGI pages and now it works
fine.

One CGI question - since all of my CGIs are spitting out HTML is their
source code safe? wget and linking to the source deliver the output
HTML. Are there any other methods of trying to steal the source CGI I
need to protect against?

Thank you.

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


Re: Pull Last 3 Months

2007-10-17 Thread Ben Finney
Paul Hankin <[EMAIL PROTECTED]> writes:

> import datetime
> 
> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
> 
> def last_months(n):
> month = datetime.date.today().month
> return [months[(month - i - 1) % 12] for i in range(n)]
> 
> print last_months(3)

Heck you don't even need the magic number 12 in there.

import datetime

months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
def last_months(n):
month = datetime.date.today().month
return [months[(month - i - 1) % len(months)
for i in range(n)]

In general I try to avoid magic numbers: always be explicit about the
semantic purpose of the number, either by binding a meaningful name to
it and only using that reference thereafter, or showing how that value
is derived.

-- 
 \  "I hope some animal never bores a hole in my head and lays its |
  `\   eggs in my brain, because later you might think you're having a |
_o__)  good idea but it's just eggs hatching."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pull Last 3 Months

2007-10-17 Thread Tim Chase
> It looks like you copied the month 2 case from the month 1 case
> because you forgot to edit it afterwards. Anyway, a bit of modulo-12
> arithmetic avoids special cases, and allows the number of months to be
> generalised:

nice...

> import datetime
> 
> months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()
> 
> def last_months(n):
> month = datetime.date.today().month
> return [months[(month - i - 1) % 12] for i in range(n)]
> 
> print last_months(3)

In the event that you need them in whatever your locale is, you
can use the '%b' formatting to produce them:

import datetime

month_map = dict(
  (n, datetime.date(2000,n+1,1).strftime('%b'))
  for n in xrange(12)
  )

The function can then be written as either a generator:

def last_months(months):
  this_month = datetime.date.today().month - 1
  for i in xrange(months):
yield month_map[(this_month-i) % 12]

or as a function returning a list/tuple:

def last_months(months):
  this_month = datetime.date.today().month - 1
  return [month_map[(this_month - i) % 12]
for i in xrange(months)]

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Robert Kern
Debajit Adhikary wrote:
> On Oct 17, 5:40 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>> To answer your question though: a += b is *not* the same as a = a + b.
>> The latter would create a new list and assign it to a, whereas a += b
>> updates a in-place.
> 
> I know I'm being a little finicky here, but how would someone know
> that a+=b is not the same as a=a+b?
> Any documentation or reference that mentions this?

http://docs.python.org/ref/augassign.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Best way to generate alternate toggling values in a loop?

2007-10-17 Thread Carsten Haese
On Wed, 2007-10-17 at 23:55 +, Debajit Adhikary wrote:
> I'm writing this little Python program which will pull values from a
> database and generate some XHTML.
> 
> I'm generating a  where I would like the alternate 's to be
> 
> 
> and
> 
> 
> What is the best way to do this?
> 
> I wrote a little generator (code snippet follows). Is there a better
> (more "Pythonic") way to do this?
> 
> 
> # Start of Code
> 
> def evenOdd():
> values = ["Even", "Odd"]
> state = 0
> while True:
> yield values[state]
> state = (state + 1) % 2
> 
> 
> # Snippet
> 
> trClass = evenOdd()
> stringBuffer = cStringIO.StringIO()
> 
> for id, name in result:
> stringBuffer.write('''
> 
> %d
> %s
> 
> '''
> %
> (trClass.next(), id, name))

This is a respectable first attempt, but I recommend you familiarize
yourself with the itertools module. It has lots of useful tools for
making your code more elegant and concise.

Rather than spelling out the final result, I'll give you hints: Look at
itertools.cycle and itertools.izip.
 
HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Best Python Linux distribution

2007-10-17 Thread Anthony Perkins
- Original Message - 
From: "Anthony Perkins" <[EMAIL PROTECTED]>


> What is the best GNU/Linux distribution (or the most preferred) for
> developing Python applications?

Thanks for your advice guys, the Debian 4.0r1 DVD (suggested off-list) seems 
to fit my needs best.

-- 
Anthony Perkins
muzz.be 

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


Best way to generate alternate toggling values in a loop?

2007-10-17 Thread Debajit Adhikary
I'm writing this little Python program which will pull values from a
database and generate some XHTML.

I'm generating a  where I would like the alternate 's to be


and


What is the best way to do this?

I wrote a little generator (code snippet follows). Is there a better
(more "Pythonic") way to do this?


# Start of Code

def evenOdd():
values = ["Even", "Odd"]
state = 0
while True:
yield values[state]
state = (state + 1) % 2


# Snippet

trClass = evenOdd()
stringBuffer = cStringIO.StringIO()

for id, name in result:
stringBuffer.write('''

%d
%s

'''
%
(trClass.next(), id, name))


# End of Code

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


Re: if instance exists problem ..

2007-10-17 Thread Ben Finney
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:

> stef mientki schrieb:
> > What should I do to the same simple test for existance ?
> 
> Use isinstance(obj, type).

No, that's *far* more specific than "does it exist", and will give
false negatives.

Much better is::

foo = None
foo = do_something_to_get_instance()
# ...
if foo is not None:
# foo was bound to an instance correctly

Even better is just to use the object, and if it's not what was
expected, catch the exception at a level that knows what to do about
it.

-- 
 \  "At my lemonade stand I used to give the first glass away free |
  `\  and charge five dollars for the second glass. The refill |
_o__) contained the antidote."  -- Emo Philips |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pull Last 3 Months

2007-10-17 Thread Paul Hankin
On Oct 17, 11:56 pm, Shane Geiger <[EMAIL PROTECTED]> wrote:
> A simpler way, imho:
>
> import datetime
> m = {
> 1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
>
> month = datetime.date.today().month
> if month == 1:
> ans = [m[11], m[12], m[1]]
> elif month == 2:
> ans = [m[11], m[12], m[1]]
> else:
> ans = [m[month-2], m[month-1], m[month]]
> print ans

It looks like you copied the month 2 case from the month 1 case
because you forgot to edit it afterwards. Anyway, a bit of modulo-12
arithmetic avoids special cases, and allows the number of months to be
generalised:

import datetime

months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()

def last_months(n):
month = datetime.date.today().month
return [months[(month - i - 1) % 12] for i in range(n)]

print last_months(3)

--
Paul Hankin

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


Re: Async XMLRPC and job processing

2007-10-17 Thread Adonis Vargas
Sean Davis wrote:
> I would like to set up a server that takes XMLRPC requests and
> processes them asynchronously.  The XMLRPC server part is trivial in
> python.  The job processing part is the part that I am having trouble
> with.  I have been looking at how to use threadpool, but I can't see
> how to get that working.  I would like to have the XMLRPC part of
> things do something like:
> 
> def method1(a,b,c):
> jobid=workRequest(long_method1,[a,b,c])
> return(jobid)
> 
> def method2(a,b,c):
> jobid=workRequest(long_method2,[a,b,c])
> return(jobid)
> 
> def long_method1(a,b,c)
> do lots of heavy computation, etc.
> store results in files in a given directory, etc
> return result
> 
>  for any number of methods
> 
> Again, pretty straightforward.  However, I run into problems with the
> threadpool and xmlrpc server both waiting.  In particular, if I do
> something like:
> 
> server = SimpleXMLRPCServer.SimpleXMLRPCServer(.)
> server.serve_forever()
> 
> Where can tell the threadpool that I have set up to wait
> indefinitely?  Both are blocking.
> 
> Thanks,
> Sean
> 

This site shows how to make it multi-threaded:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425043

But now you have to contend with the integrity of your data, provided 
your going be storing data through these processes. You may want to look 
into the Queue module to create a sort of message queue so your data can 
be properly synchronized.

Hope this helps.

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Debajit Adhikary
On Oct 17, 5:40 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
> To answer your question though: a += b is *not* the same as a = a + b.
> The latter would create a new list and assign it to a, whereas a += b
> updates a in-place.

I know I'm being a little finicky here, but how would someone know
that a+=b is not the same as a=a+b?
Any documentation or reference that mentions this?


> Use a += b rather than a.extend(b): I'm not sure what I was thinking.
> Anyway, look at 'timeit' to see how to measure things like this, but
> my advice would be not to worry and to write the most readable code -
> and only optimise if your code's runnign too slowly.

I understand. Thanks :)
At the same time, however, as someone new learning the language, I
feel it always helps to know what the best practices and patterns are
at the very outset (at least for someone who chooses to become a good
programmer in that language). I mean, for me it's like this, I just
don't want to get the work done, I would really want to know why I do
something a certain way and not some other way :)

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


Re: if instance exists problem ..

2007-10-17 Thread Diez B. Roggisch
stef mientki schrieb:
> hello,
> 
> I've written a convenience wrapper around ConfigObj (which is a imporved 
> ConfigParser).
> 
> Now if I use an instance of the base class, I can easily test is the 
> instance exists by " if ini:",
> like in this example
> 
>ini = None
>if ini:
>print 'ok',type(ini)
>else:
>print 'wrong',type(ini)
>ini = ConfigObj (filename)
>if ini:
>print 'ok',type(ini)
>else:
>print 'wrong',type(ini)
> 
> Now if I derive a new class form this:
> class inifile (ConfigObj):
>def __init__ (self, filename):
>self.ini = ConfigObj ( filename , list_values = False, 
> write_empty_values = True )
>self.ini.newlines = '\r\n'   # not strictly necessary
>self.Section = ''
>self.Modified = False
> 
> 
> the test if an instance exists, always returns false.
>ini = inifile (filename)
>if ini:
>print 'ok',type(ini)
>else:
>print 'wrong',type(ini)
> 
> Why is that ?
> What should I do to the same simple test for existance ?

Use isinstance(obj, type).

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


Re: if instance exists problem ..

2007-10-17 Thread Paul Hankin
On Oct 17, 11:39 pm, stef mientki <[EMAIL PROTECTED]> wrote:
> the test if an instance exists, always returns false.
> ini = inifile (filename)
> if ini:
> print 'ok',type(ini)
> else:
> print 'wrong',type(ini)
>
> Why is that ?
> What should I do to the same simple test for existance ?

First, object construction always gives you an object or raises an
exception, so you don't have to test for existence. If you don't know
if an object has been created, you should initialise ini to None, and
test with 'if ini is not None:'.

'if x' doesn't test if x exists, it tests if x when cast to a bool is
True. ConfigParser acts like a container, and returns False if it's
empty. Your class is (indirectly) a subclass of ConfigParser, but is
never initialised as such, and so is empty. So 'if ini' returns False,
and you get your confused result.

You need to decide if inifile is a subclass of ConfigObj, or is a
wrapper round a ConfigObj. Probably you want the former and your init
method should be something like:
  def __init__(self, filename):
ConfigObj.__init__(self, filename, list_values=False,
  write_empty_values=True)
self.newlines = '\r\n'
self.Section = ''
self.Modified = False

--
Paul Hankin

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


Re: CGI and external JavaScript nightmare

2007-10-17 Thread allen.fowler

>
> One CGI question - since all of my CGIs are spitting out HTML is their
> source code safe? wget and linking to the source deliver the output
> HTML. Are there any other methods of trying to steal the source CGI I
> need to protect against?
>
> Thank you.

Not sure I fully understand the question.

Can you post the CGI code here?

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


Re: Pull Last 3 Months

2007-10-17 Thread Shane Geiger
A simpler way, imho:

import datetime
m = {
1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'
}
month = datetime.date.today().month
if month == 1:
ans = [m[11], m[12], m[1]]
elif month == 2:
ans = [m[11], m[12], m[1]]
else:
ans = [m[month-2], m[month-1], m[month]]
print ans


Tim Chase wrote:
>> Is there a module that can pull str values for say the last 3 months?
>> Something like:
>>
>> print lastMonths(3)
>>
>> ['Sep', 'Aug', 'Jul']
>> 
>
> I don't think there's anything inbuilt.  It's slightly 
> frustrating that timedelta doesn't accept a "months" parameter 
> when it would be rather helpful (but how many days are in a 
> month-delta is something that changes from month-to-month).
>
> It's somewhat inelegant, but this works for me:
>
>import datetime
>
>def last_months(months):
>  assert months > 0
>  d = datetime.date.today()
>  m = d.strftime('%b')
>  yield m
>  while months > 1:
>d -= datetime.timedelta(days=28)
>m2 = d.strftime('%b')
>if m2 <> m:
>  m = m2
>  months -= 1
>  yield m
>
>print list(last_months(3))
>for month in last_months(24): print month
>
> The alternative would likely be to do something like subtract one 
> from the current month, and if it drops below 1, decrement the 
> year and reset the month to 12.  Equally fuzzy:
>
>def lastN(months):
>  assert months > 0
>  d = datetime.date.today()
>  for _ in xrange(months):
>yield d.strftime('%b')
>y,m = d.year, d.month
>if m > 1:
>  m -= 1
>else:
>  m = 12
>  y -= 1
>d = datetime.date(y,m,1)
>
> Use whichever you prefer.
>
> -tkc
>
>
>
>
>
>   

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: Last iteration?

2007-10-17 Thread Raymond Hettinger
[Paul Hankin]
> def lastdetector(iterable):
> t, u = tee(iterable)
> return izip(chain(imap(lambda x: False, islice(u, 1, None)),
> [True]), t)

Sweet!  Nice, clean piece of iterator algebra.

We need a C-speed verion of the lambda function, something like a K
combinator that consumes arguments and emits constants.


Raymond



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


Python Labs Move

2007-10-17 Thread Bill Garey
What is PYTHON 2.2.1   and what does it do? I see  the Program on my list of 
programs but don't know how to use it ,  or what it is! [EMAIL PROTECTED]-- 
http://mail.python.org/mailman/listinfo/python-list

if instance exists problem ..

2007-10-17 Thread stef mientki
hello,

I've written a convenience wrapper around ConfigObj (which is a imporved 
ConfigParser).

Now if I use an instance of the base class, I can easily test is the 
instance exists by " if ini:",
like in this example

ini = None
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(ini)
ini = ConfigObj (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(ini)

Now if I derive a new class form this:
class inifile (ConfigObj):
def __init__ (self, filename):
self.ini = ConfigObj ( filename , list_values = False, 
write_empty_values = True )
self.ini.newlines = '\r\n'   # not strictly necessary
self.Section = ''
self.Modified = False


the test if an instance exists, always returns false.
ini = inifile (filename)
if ini:
print 'ok',type(ini)
else:
print 'wrong',type(ini)

Why is that ?
What should I do to the same simple test for existance ?

thanks,
Stef Mientki

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


Re: Noob questions about Python

2007-10-17 Thread Paul Hankin
On Oct 17, 10:58 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
> Thank you for the quick responses.
>
> I did not know that about integer literals beginning with a '0', so
> thank you for the explanation. I never really use PHP except for
> handling basic forms and silly web stuff, this is why I picked up
> Python because I want to teach myself a more powerful and broad
> programming language.
>
> With regard to why I asked: I wanted to learn about Binary math in
> conjunction with Python, so I wrote a small function that would return
> a base 10 number from a binary number. It is nice to know about the
> int() function now.
>
> Just for the sake of it, this was the function I came up with:
>
> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> res.reverse()
> print sum(res)
>
> Now that I look at it, I probably don't need that last reverse()
> because addition is commutative...
>
> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> print sum(res)

Right idea: now to remove all those intermediate lists you construct.
1. reversed(val) creates an iterator that runs over the elements (here
of a string) in reverse order.
2. enumerate() is usually better than using an explicit list index.
3. You can use a generator in your sum to avoid constructing the final
list.

Applying these to your function, and noting that n << k is nicer than
n * 2 ** k, we get a one-liner:

def bin2dec(val):
return sum(int(i) << k for k, i in enumerate(reversed(val)))

Or a slightly nicer alternative is to filter the generator using 'if':

def bin2dec(val):
return sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

--
Paul Hankin

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


Re: negative base raised to fractional exponent

2007-10-17 Thread Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:

> Thank you for this. Now I need to somehow express this as a real
> number. For example, I can transform the real and imaginary parts
> into a polar coordinate giving me the value I want:
> 
> z = sqrt( real_part**2 + imaj_part**2 )
> 
> but this is an absolute terms. 

Not really. It is just the "absolute value" which is a property of
the complex number; it is (as already stated) by definition always
positive. There doesn't exist any underlying "real" value from
which a sign is stripped to yield the absolute value of z.

> How does one determine the correct sign for this value?

In this case, the background (what you model using this complex
number) is of great importance. 

Consider learning more about complex numbers; especially about how
they can be represented as a point on the complex plane
(), understanding this
makes understanding and dealing with complex numbers much easier. 

Regards,


Björn

-- 
BOFH excuse #31:

cellular telephone interference

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


Re: Problem of Readability of Python

2007-10-17 Thread kiilerix
On Oct 17, 9:11 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> On 10/17/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > >>> o = object()
> > >>> o.foo = 7
>
> What makes you think it can't be instantiated directly? You just did
> it. It's not, however, suitable for use as an arbitrary thing to stick
> attributes on.
>
> Which is a little sad, but a necessary requirement for things like
> int() and str() to be small and fast.

So it's an optimization with side effects, giving a special case where
the simple and otherwise "right" way to do it doesn't work? Too bad :-
(

Ok; I'll continue to create dummy classes inheriting from object. And
hope that one day it will be simpler.

Thanks,
Mads

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


Re: Noob questions about Python

2007-10-17 Thread Ixiaus
Thank you for the quick responses.

I did not know that about integer literals beginning with a '0', so
thank you for the explanation. I never really use PHP except for
handling basic forms and silly web stuff, this is why I picked up
Python because I want to teach myself a more powerful and broad
programming language.

With regard to why I asked: I wanted to learn about Binary math in
conjunction with Python, so I wrote a small function that would return
a base 10 number from a binary number. It is nice to know about the
int() function now.

Just for the sake of it, this was the function I came up with:

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
res.reverse()
print sum(res)

Now that I look at it, I probably don't need that last reverse()
because addition is commutative...

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)

It basically does the same thing int(string, 2) does.

Thank you for the responses!

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


* Pedophile Al-Qaida Brown Muslim Kills 6 Devout Christian Policement for Enjoying a Party - Atom Bomb his country to stone age *

2007-10-17 Thread thermate
http://www.cnn.com/2007/US/10/08/wisconsin.shooting/?iref=mpstoryview

updated 8:39 p.m. EDT, Mon October 8, 2007

Deputy fired 30 shots from rifle in killing 6, officials say

CRANDON, Wisconsin (CNN) -- An off-duty sheriff's deputy used a police-
style AR-15 rifle to kill six people at an early morning party in a
small Wisconsin town, officials said Monday.
art.peterson.wtmj.jpg

Tyler Peterson, a sheriff's deputy, shot and killed six people, police
said.

Twenty-year-old Tyler Peterson had gone to the party early Sunday to
make amends with his ex-girlfriend, a friend of Peterson's told The
Milwaukee Journal Sentinel.

Peterson lost control after people called him a "worthless pig," Mike
Kegley told the paper.

Peterson left and got a police-style AR-15 rifle from his truck,
forced his way back into the apartment and fired about 30 rounds at
about 2:45 a.m. (3:45 a.m. ET). Six people were killed; one person
survived and is hospitalized, Attorney General J.B. Van Hollen said at
a Monday news conference.

Peterson was killed in a shootout with law officers Sunday afternoon
after negotiations for his surrender failed, officials said. The
town's mayor said Tyler was killed by a SWAT team sniper.

The dead and wounded were all students or graduates of Crandon High
School, and Peterson was a graduate of the school, which has a little
more than 300 students.

Witnesses said the victims ranged in age from 14 to 20, and one was
apparently Peterson's former girlfriend.

Peterson's family, in a statement read by Bill Farr, a pastor,
expressed condolences to the victim's relatives and said they could
not find any reason for the killings.

"We are grieving for your losses. We are very sorry for what has
happened. This huge tragedy has deeply affected everyone, including
us. We also feel a tremendous amount of guilt and shame for the
horrible acts Tyler committed. This is not the Tyler we knew and
loved," the statement read.
Don't Miss

* Victims include high school freshman who loved animals

Jenny Stahl said her daughter, Lindsey, was the youngest victim. Video
Watch the victim's mom describe her grief »

"I don't want to believe it. I'm waiting for somebody to wake me up,"
she said. "She's only 14 -- she'll be 15 next month; she's just
starting to live. And the sad thing is who killed her -- a cop. Cops
are supposed to always protect you, I thought, and it's one who took
my daughter and how many other people's lives."

It was the high school's homecoming weekend.

Friends of the victims said Peterson also worked part time as a
Crandon police officer.

Residents near the scene of the shooting told the Associated Press it
was hard to accept that a police officer was the shooter.

"The first statement we said to each other was, 'How did he get
through the system?' " David Franz told the AP. "How do they know
somebody's background, especially that young? It is disturbing, to say
the least."

The town's schools were closed Monday, with grief counselors available
to students, said Superintendent Richard Peters.

"This was the kind of scenario where every small town in the USA says,
'This could never happen here,' " Peters said.

Crandon, a town of about 2,000 people, is 220 miles north of
Milwaukee, Wisconsin.

Crandon Mayor Gary Bradley said the town will work together to get
over the tragedy.

"There's a lot of people weeping and gnashing their teeth and the
emotions are very raw right now," Bradley said. "But we'll rebuild
brick by brick."

Forest County Sheriff Keith Van Cleve called the situation "very
difficult" for his deputies and the community.

Karly Johnson, 16, told the AP she knew the shooter.

"He was nice. He was an average guy -- normal. You wouldn't think he
could do that," Johnson said, adding that Peterson had helped her in a
class and had graduated with her brother, according to the AP.
advertisement

The state attorney general's office will investigate the case, Van
Cleve said.

Kevin St. John, a spokesman for the state Department of Justice, said
the agency's criminal investigation unit routinely investigates cases
of a "statewide or significant nature." E-mail to a friend E-mail to a
friend

CNN's Susan Roesgen and Katherine Wojtecki contributed to this report.

Copyright 2007 CNN. All rights reserved.This material may not be
published, broadcast, rewritten, or redistributed. Associated Press
contributed to this report.

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Paul Hankin
On Oct 17, 10:03 pm, Debajit Adhikary <[EMAIL PROTECTED]> wrote:
> How does "a.extend(b)" compare with "a += b" when it comes to
> performance? Does a + b create a completely new list that it assigns
> back to a? If so, a.extend(b) would seem to be faster. How could I
> verify things like these?

Use a += b rather than a.extend(b): I'm not sure what I was thinking.
Anyway, look at 'timeit' to see how to measure things like this, but
my advice would be not to worry and to write the most readable code -
and only optimise if your code's runnign too slowly.

To answer your question though: a += b is *not* the same as a = a + b.
The latter would create a new list and assign it to a, whereas a += b
updates a in-place.

--
Paul Hankin

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


Re: Noob questions about Python

2007-10-17 Thread Bjoern Schliessmann
Ixiaus wrote:

> val = 'string'
> li = list(val)
> print li.reverse()
> 
> returns nothing, but,

Yes -- li.reverse() returns None. "print None" prints nothing.
 
> val = 'string'
> li = list(val)
> li.reverse()
> print li
> 
> returns what I want. 

I'm afraid not. li.reverse() still returns None, but this time you
print li, and this shows the reversed list.

As already explained, li.reverse() modifies the existing list. What
to use here depends on what you want to achieve:

If you really want to reverse the list (i. e. re-sort the list in
memory, and perhaps work with it afterwards), use "li.reverse()". 

If you just want to have all its members in reverse order, use the
builtin reversed(li) (which is an iterator giving you li's members
from back to front when iterating over it).

Regards,


Björn

-- 
BOFH excuse #243:

The computer fleetly, mouse and all.

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


Re: Pull Last 3 Months

2007-10-17 Thread Paul Hankin
On Oct 17, 9:59 pm, Harlin Seritt <[EMAIL PROTECTED]> wrote:
> Is there a module that can pull str values for say the last 3 months?
> Something like:
>
> print lastMonths(3)
>
> ['Sep', 'Aug', 'Jul']

You should take a look at the 'datetime' module.

You can get the current month:
datetime.datetime.now().month

And a list of all abbreviated month names:
[datetime.datetime(1900, i + 1, 1).strftime('%b') for i in range(12)]

>From there, it shouldn't be too tricky to construct the list of months
you want.

--
Paul Hankin

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


Re: Pull Last 3 Months

2007-10-17 Thread Tim Chase
> Is there a module that can pull str values for say the last 3 months?
> Something like:
> 
> print lastMonths(3)
> 
> ['Sep', 'Aug', 'Jul']

I don't think there's anything inbuilt.  It's slightly 
frustrating that timedelta doesn't accept a "months" parameter 
when it would be rather helpful (but how many days are in a 
month-delta is something that changes from month-to-month).

It's somewhat inelegant, but this works for me:

   import datetime

   def last_months(months):
 assert months > 0
 d = datetime.date.today()
 m = d.strftime('%b')
 yield m
 while months > 1:
   d -= datetime.timedelta(days=28)
   m2 = d.strftime('%b')
   if m2 <> m:
 m = m2
 months -= 1
 yield m

   print list(last_months(3))
   for month in last_months(24): print month

The alternative would likely be to do something like subtract one 
from the current month, and if it drops below 1, decrement the 
year and reset the month to 12.  Equally fuzzy:

   def lastN(months):
 assert months > 0
 d = datetime.date.today()
 for _ in xrange(months):
   yield d.strftime('%b')
   y,m = d.year, d.month
   if m > 1:
 m -= 1
   else:
 m = 12
 y -= 1
   d = datetime.date(y,m,1)

Use whichever you prefer.

-tkc





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


Re: Bidirectional communication over unix socket (named pipe)

2007-10-17 Thread Raúl Gómez C.
BTW: This is the original post:

Hi, I feel like I should apologize in advance because I must be missing
something fairly basic and fundamental here.  I don't have a book on
Python network programming (yet) and I haven't been able to find an
answer on the net so far.

I am trying to create a pair of programs, one (the client) will be
short-lived (fairly) and the second (server) will act as a cache for
the client. Both will run on the same machine, so I think a simple file
socket is the easiest and most reliable method.

The problem I have is that the client can send to the server, but the
server can't send back to the client because it gets this error:

socket.error: (107, 'Transport endpoint is not connected')

This is despite the client waiting on a socket.recv() statement.  Is
the client really not connected, or is the server unaware of the
connection?  And how do I fix this?

I was able to get this working by switching to AF_INET, but that is not
what I want.

Unix sockets are bidirectional, correct?  I have never programmed one,
but I know that programs like clamav use a socket to receive an email
to scan and return the result.

Any help would be greatly appreciated!

Jeff

*** server.py ***
#!/usr/bin/python
import socket
import os, os.path
import time

if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock")

server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
server.bind("/tmp/mysock")

while True:
datagram = server.recv(1024)
if not datagram:
break
print datagram
# the preceeding works, and I see the TEST TEST TEST statement the
client sent

time.sleep(2)
# it dies on the next statement.
server.send("Thank you\n")


server.close()
if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock")


 *** client.py: ***
#!/usr/bin/python

import socket

client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
client.connect("/tmp/mysock")


TX = "TEST TEST TEST"
TX_sent = client.send(TX)

if TX_sent <> len(TX):  print "TX incomplete"

while True:
print "Waiting..."
datagram = client.recv(1024)
# the client sits here forever, I see the "waiting appear" but
it doesn't advance beyond
#   the recv statement.
if not datagram:
break
print "Received: ",datagram

client.close()



On 10/17/07, Raúl Gómez C. <[EMAIL PROTECTED]> wrote:
>
> Hi Jeffrey,
>
> I've been reading the Python mailing list and I've found a post of you
> about Unix socket with Python, you've found the answer to you're problem by
> your self, but I wonder if you still has the working code and if you would
> share it?
>
> Thanks!...
>
> Raul
>
>
> On *Wed Mar 8 18:11:11 CET 2006, **J Rice* rice.jeffrey at 
> gmail.comwrote:
>
> > OK, never fails that I find a solution once I post a problem.
> > If I use a stream rather than a datagram, it seems to work fine.
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Bidirectional communication over unix socket (named pipe)

2007-10-17 Thread Raúl Gómez C.
Hi Jeffrey,

I've been reading the Python mailing list and I've found a post of you about
Unix socket with Python, you've found the answer to you're problem by your
self, but I wonder if you still has the working code and if you would share
it?

Thanks!...

Raul


On *Wed Mar 8 18:11:11 CET 2006, **J Rice* rice.jeffrey at
gmail.comwrote:

> OK, never fails that I find a solution once I post a problem.
> If I use a stream rather than a datagram, it seems to work fine.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: CGI and external JavaScript nightmare

2007-10-17 Thread IamIan
Thank you for the replies. After a lot of research I tracked down the
issue. I was using the CGI to build all of the pages for the site,
then filling in content with .innerHTML= as users clicked on tabs.
Since I wanted to place the Google Ads in different parts of each
page, the Google Ads JavaScript was in each page chunk being
dynamically placed with .innerHTML.

It turns out that JavaScript isn't executed when it is placed in a
page via .innerHTML. I tried some tricks to execute it after it was
added to the page (eval, appendChild) but it still didn't work. The
Google Ads JavaScript is very touchy and their agreement is very
strict; it wasn't even clear that what I was doing was in line with
it, so I broke the site up into multiple CGI pages and now it works
fine.

One CGI question - since all of my CGIs are spitting out HTML is their
source code safe? wget and linking to the source deliver the output
HTML. Are there any other methods of trying to steal the source CGI I
need to protect against?

Thank you.

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


Re: Need help in updating a global variable by a thread

2007-10-17 Thread Paul Hankin
On Oct 17, 7:48 pm, [EMAIL PROTECTED] wrote:
> Hello Folks,
>
> My first posting here and I am a stuck in figuring out the exact way
> to update a global variable from within a function that doesnt return
> any value (because the function is a target of the thread and I dont
> know how exactly return would work in such a case). I am sure I am
> missing something very fundamental here. The essential pieces of my
> code that cause the problem would be something like this:
> -
> lookuptab = {'1.9.7.3':'Bangkok','1.9.60.3':'Sydney'}
>
> results = {}
>
> for val in lookuptab.values():
> results[val]=0
>
> def testt(loc):
>global results
>results[loc] = 1
>return results[loc]
>
> for x in lookuptab.values():
>   thread = threading.Thread(target=testt,args=(x))
>   thread.start()
> print results

When I try to run this I get a 6-arguments-instead-of-1 error because
you wrote args=(x) instead of args=(x,). I wonder why you don't see
this error?

Apart from that the code works, except you need to wait for the
threads to finish executing before you see the updated results. Have a
look at threading.join to see how you might do that.

--
Paul Hankin

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Debajit Adhikary
On Oct 17, 4:41 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Wed, 2007-10-17 at 20:27 +, Debajit Adhikary wrote:
> > I have two lists:
>
> > a = [1, 2, 3]
> > b = [4, 5, 6]
>
> > What I'd like to do is append all of the elements of b at the end of
> > a, so that a looks like:
>
> > a = [1, 2, 3, 4, 5, 6]
>
> > I can do this using
>
> > map(a.append, b)
>
> > How do I do this using a list comprehension?
>
> You don't.
>
> > (In general, is using a list comprehension preferable (or more
> > "pythonic") as opposed to using map / filter etc.?)
>
> In general, a list comprehension is more Pythonic nowadays, but in your
> particular case the answer is neither map nor a list comprehension, it's
> this:
>
> a += b
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Thanks a ton :)

What in general is a good way to learn about little things like these?
(I'm fairly new to the language)

A google search for 'python list methods" did not turn up the +
operator anywhere for me. Where could I find the official
documentation for built in structures like the list? (I just noticed
that the + operator for lists is mentioned in Beazley's Python
Essential Reference -- in the opening pages, which I didn't look at
when I was writing the earlier code.)

How does "a.extend(b)" compare with "a += b" when it comes to
performance? Does a + b create a completely new list that it assigns
back to a? If so, a.extend(b) would seem to be faster. How could I
verify things like these?

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


Pull Last 3 Months

2007-10-17 Thread Harlin Seritt
Is there a module that can pull str values for say the last 3 months?
Something like:


print lastMonths(3)

['Sep', 'Aug', 'Jul']

Thanks

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


Re: Need help in updating a global variable by a thread

2007-10-17 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hello Folks,
> 
> My first posting here and I am a stuck in figuring out the exact way
> to update a global variable from within a function that doesnt return
> any value (because the function is a target of the thread and I dont
> know how exactly return would work in such a case). I am sure I am
> missing something very fundamental here. The essential pieces of my
> code that cause the problem would be something like this:
> -
> lookuptab = {'1.9.7.3':'Bangkok','1.9.60.3':'Sydney'}
> 
> results = {}
> 
> for val in lookuptab.values():
> results[val]=0
> 
> def testt(loc):
>global results
>results[loc] = 1
>return results[loc]
> 
> for x in lookuptab.values():
>   thread = threading.Thread(target=testt,args=(x))
>   thread.start()
> print results
> ---

"Would be" ?

I had to fix a couple problems to get your code running (namely, 
importing threading and passing correct args to threading.Thread). Do 
yourself a favour: next time, take time to post *working* code.

Anyway... Here's a (corrected) version with a couple prints here and 
there. I think the output is clear enough:

import threading
import time

lookuptab = {'1.9.7.3':'Bangkok','1.9.60.3':'Sydney'}
results = dict((val, 0) for val in lookuptab.values())

def testt(loc):
global results
print "t-%s before: %s" % (loc,results)
results[loc] = 1
print "t-%s after: %s" % (loc,results)

def main():
   for x in lookuptab.values():
 thread = threading.Thread(target=testt,args=(x,))
 thread.start()

   print "main - no sleep: %s" % results
   time.sleep(1)
   print "main - 1s later : %s" % results

if __name__ == '__main__': main()

And the output is:

main - no sleep: {'Bangkok': 0, 'Sydney': 0}
t-Bangkok before: {'Bangkok': 0, 'Sydney': 0}
t-Bangkok after: {'Bangkok': 1, 'Sydney': 0}
t-Sydney before: {'Bangkok': 1, 'Sydney': 0}
t-Sydney after: {'Bangkok': 1, 'Sydney': 1}
main - 1s later : {'Bangkok': 1, 'Sydney': 1}


Now if I may give you an advice about threads and globals (or any other 
kind of shared state): learn about semaphores. While this may not be an 
issue in this snippet, race conditions is definitively something you 
want to avoid whenever possible and cleanly handle else.

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


Re: sqlite and TemporaryFile under Windows

2007-10-17 Thread Matthieu Brucher
>
> Besides the fact that database management systems need lots of
> random file accesses?


That doesn't imply not supporting file-object.

BTW, how is it possible to close the access to the database ? I deleted the
object but Winows tells me that someone is still holding the file.

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

Pull Last 3 Months

2007-10-17 Thread Harlin Seritt
Is there a module that can pull str values for say the last 3 months?
Something like:


print lastMonths(3)

['Sep', 'Aug', 'Jul']

Thanks

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


Async XMLRPC and job processing

2007-10-17 Thread Sean Davis
I would like to set up a server that takes XMLRPC requests and
processes them asynchronously.  The XMLRPC server part is trivial in
python.  The job processing part is the part that I am having trouble
with.  I have been looking at how to use threadpool, but I can't see
how to get that working.  I would like to have the XMLRPC part of
things do something like:

def method1(a,b,c):
jobid=workRequest(long_method1,[a,b,c])
return(jobid)

def method2(a,b,c):
jobid=workRequest(long_method2,[a,b,c])
return(jobid)

def long_method1(a,b,c)
do lots of heavy computation, etc.
store results in files in a given directory, etc
return result

 for any number of methods

Again, pretty straightforward.  However, I run into problems with the
threadpool and xmlrpc server both waiting.  In particular, if I do
something like:

server = SimpleXMLRPCServer.SimpleXMLRPCServer(.)
server.serve_forever()

Where can tell the threadpool that I have set up to wait
indefinitely?  Both are blocking.

Thanks,
Sean

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Paul Hankin
On Oct 17, 9:27 pm, Debajit Adhikary <[EMAIL PROTECTED]> wrote:
> I have two lists:
>
> a = [1, 2, 3]
> b = [4, 5, 6]
>
> What I'd like to do is append all of the elements of b at the end of
> a, so that a looks like:
>
> a = [1, 2, 3, 4, 5, 6]
>
> I can do this using
>
> map(a.append, b)
>
> How do I do this using a list comprehension?
>
> (In general, is using a list comprehension preferable (or more
> "pythonic") as opposed to using map / filter etc.?)

Yes, using a list comprehension is usually more pythonic than using
map/filter. But here, the right answer is:
a.extend(b). The first thing you should always do is check the python
libraries for a function or method that does what you want. Even if
you think you know the library quite well it's still worth checking:
I've lost count of the number of times I've discovered a library
function that does exactly what I wanted.

Anyway, if extend didn't exist, the pythonic version of map(a.append,
b) would be
for x in b:
a.append(x)

Rather than
[a.append(x) for x in b]


List comprehensions and map produce a new list. That's not what you
want here: you're using the side-effect of the append method - which
modifies a. This makes using regular iteration the right idea, because
by using map or a comprehension, you're also constructing a list of
the return values of append (which is always None). You can see this
in the interpreter:

>>> map(a.append, b)
[None, None, None]

>>> a
[1, 2, 3, 4, 5, 6]

HTH

--
Paul Hankin

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


Re: pymssql - insert NULL to int

2007-10-17 Thread rc
On Oct 17, 11:07 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> rc wrote:
> > How to insert NULL values in to int field using params.
>
> > I'm trying to use pymssql.execute, passing the operation and list of
> > params.  One of the values in the params is a NULL value going to int
> > field.  The pymssql._quote() puts ' around the NULL which causes an
> > exception to be thrown, is there a way to use the params for this or
> > do I need to build the insert string myself?
>
> > pymssql.DatabaseError: internal error: SQL Server message 245,
> > severity 16, state 1, line 1:
> > Conversion failed when converting the varchar value 'NULL' to data
> > type int.
> > DB-Lib error message 10007, severity 5:
> > General SQL Server error: Check messages from the SQL Server.
>
> Can you show us the actual code you use? I doubt that such a basic thing
> isn't working.
>
> You are aware that you have to pass None, not "NULL"?
>
> Diez

I had tried None and was getting the same error as 'NULL', however, I
tried again after your post and its working now.  Not sure what I
changed but thanks for getting me to tried it again.

rc

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Carsten Haese
On Wed, 2007-10-17 at 20:27 +, Debajit Adhikary wrote:
> I have two lists:
> 
> a = [1, 2, 3]
> b = [4, 5, 6]
> 
> What I'd like to do is append all of the elements of b at the end of
> a, so that a looks like:
> 
> a = [1, 2, 3, 4, 5, 6]
> 
> I can do this using
> 
> map(a.append, b)
> 
> How do I do this using a list comprehension?

You don't.

> (In general, is using a list comprehension preferable (or more
> "pythonic") as opposed to using map / filter etc.?)

In general, a list comprehension is more Pythonic nowadays, but in your
particular case the answer is neither map nor a list comprehension, it's
this:

a += b

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: pyparsing batch file

2007-10-17 Thread Paul McGuire
On Oct 17, 4:47 pm, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:

> Unfortunately, it does not parse the whole file names with
> the underscore and I do not know yet, how I can access the
> line with 'define/boundary-conditions'. Every 'argument' of
> that command should become a separate python variable!?
> Does anyone have an idea, how I can achieve this!?
> Regards!
> Fabian

You are trying to match "keps1500_500.dat" with the expression
"Word(alphanums)".  Since the filename contains characters other than
alphas and numbers, you must add the remaining characters ("." and
"_") to the expression.  Try changing:

write= Word(alphanums)

to:

write= Word(alphanums+"._")


To help you to parse "/define/boundary-conditions in velocity-inlet 10
0.1 0.1 no 1", we would need to know just what these arguments are,
and what values they can take.  I'll take a wild guess, and propose
this:

real = Combine(integer + "." + integer)
defineBoundaryConditions = "/define/boundary-conditions" + \
oneOf("in out inout")("direction") + \
Word(alphanums+"-")("conditionName") + \
integer("magnitude") + \
real("initialX") + \
real("initialY") + \
oneOf("yes no")("optional") + \
integer("normal")

(Note I am using the new notation for setting results names,
introduced in 1.4.7 - simply follow the expression with ("name"),
instead of having to call .setResultsName.)

And here is a slight modification to your printout routine, using the
dump() method of the ParseResults class:

for tokens in defineBoundaryConditions.searchString(data):
print
print "Boundary Conditions = "+ tokens.conditionName
print tokens.dump()
print
print 50*"-"


prints:

Boundary Conditions = velocity-inlet
['/define/boundary-conditions', 'in', 'velocity-inlet', '10', '0.1',
'0.1', 'no', '1']
- conditionName: velocity-inlet
- direction: in
- initialX: 0.1
- initialY: 0.1
- magnitude: 10
- normal: 1
- optional: no



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


Re: negative base raised to fractional exponent

2007-10-17 Thread John J. Lee
[EMAIL PROTECTED] writes:
[...]
> Thank you for this. Now I need to somehow express this as a real
> number. For example, I can transform the real and imaginary parts into
> a polar coordinate giving me the value I want:
>
> z = sqrt( real_part**2 + imaj_part**2 )
>
> but this is an absolute terms. How does one determine the correct sign
> for this value?

If you mean the angle

>>> import math
>>> x = (-3 + 0j) ** (-37/9.)
>>> math.atan2(x.imag, x.real) * (180 / math.pi)
-19.95


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


Re: Noob questions about Python

2007-10-17 Thread Neil Cerutti
On 2007-10-17, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Ixiaus a écrit :
>> val = 00110
>> 
>> as the integer 72 instead of returning 00110, why does Python
>> do that?
>
> Literal integers starting with '0' (zero) are treated as octal.
> It's a pretty common convention (like 0x for hexa). FWIW, PHP
> does just the same thing.
>
>> (and how can I get around it?)
>
> You can't. Python has no literal notation for binary integers
> so far. Literal notation for binary ints is not a common
> feature anyway.

You can obtain a practical workaround using the int built-in
function.

>>> int('110', 2)
6

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Marc 'BlackJack' Rintsch
On Wed, 17 Oct 2007 20:27:14 +, Debajit Adhikary wrote:

> I have two lists:
> 
> a = [1, 2, 3]
> b = [4, 5, 6]
> 
> What I'd like to do is append all of the elements of b at the end of
> a, so that a looks like:
> 
> a = [1, 2, 3, 4, 5, 6]
> 
> I can do this using
> 
> map(a.append, b)

This is a bad idea as it creates a useless list of `None`\s, one for each
element in `b`.

> How do I do this using a list comprehension?

Not at all.  The obvious solution here is ``a.extend(b)``.

> (In general, is using a list comprehension preferable (or more
> "pythonic") as opposed to using map / filter etc.?)

Some say yes.

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


Re: Noob questions about Python

2007-10-17 Thread Paul Hankin
On Oct 17, 8:37 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
> I have a few questions regarding Python behavior...
> as the integer 72 instead of returning 00110, why does Python do that?
> (and how can I get around it?)

You can do this:

def bin(x):
return int(x, 2)

val = bin('00110')

--
Paul Hankin

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


Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Debajit Adhikary
I have two lists:

a = [1, 2, 3]
b = [4, 5, 6]

What I'd like to do is append all of the elements of b at the end of
a, so that a looks like:

a = [1, 2, 3, 4, 5, 6]

I can do this using

map(a.append, b)

How do I do this using a list comprehension?

(In general, is using a list comprehension preferable (or more
"pythonic") as opposed to using map / filter etc.?)

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


Re: urlgrabber cookie handling?

2007-10-17 Thread John J. Lee
Devraj <[EMAIL PROTECTED]> writes:

> Hi everyone,
>
> I have been battling to make my code work with a HTTPS proxy, current
> my code uses urllib2 to to most things and works well, except that
> urllib2 doesn't handle HTTPS proxies.
>
> Urlgrabber (http://linux.duke.edu/projects/urlgrabber/help/
> urlgrabber.grabber.html) looks very promising except that I can find a
> way to handle cookies in urlgrabber. Is there a way urlgrabber can use
> a HTTPCookieProcess or cookielib.CookieJar object to handle cookies?

I don't see a nice way.  But then I don't see any HTTPS proxy support
in urlgrabber... (I looked at version 3.1.0).

There is a recipe or two on ASPN showing how to support HTTPS proxies
with urllib2, which gives an idea how to do it, though the code is a
bit rough (I'd post some code myself, but I did it for work).


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


Re: Noob questions about Python

2007-10-17 Thread Bruno Desthuilliers
Ixiaus a écrit :
> I have recently (today) just started learning/playing with Python. So
> far I am excited and impressed

Welcome onboard then !-)

> (coming from PHP background).
 >
> I have a few questions regarding Python behavior...
> 
> val = 'string'
> li = list(val)
> print li.reverse()
> 
> returns nothing, but,
> 
> val = 'string'
> li = list(val)
> li.reverse()
> print li
> 
> returns what I want. Why does Python do that?

list.reverse (like list.sort) is a destructive in-place operation. Not 
returning the object is reminder of the destructive nature of the 
operation. That's a design choice, whether you agree with it or not 
(FWIW, I don't, but I live with it !-)

Note that there's also the reverse() function that returns a reverse 
iterator over any sequence, so you could also do:

li = list('allo')
print ''.join(reverse(li))

> Also I have been playing around with Binary math and noticed that
> Python treats:
> 
> val = 00110
> 
> as the integer 72 instead of returning 00110, why does Python do that?

Literal integers starting with '0' (zero) are treated as octal. It's a 
pretty common convention (like 0x for hexa). FWIW, PHP does just the 
same thing.

> (and how can I get around it?)

You can't. Python has no literal notation for binary integers so far. 
Literal notation for binary ints is not a common feature anyway.

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


Re: Noob questions about Python

2007-10-17 Thread Adam Atlas
On Oct 17, 3:37 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
> I have recently (today) just started learning/playing with Python. So
> far I am excited and impressed (coming from PHP background).
>
> I have a few questions regarding Python behavior...
>
> val = 'string'
> li = list(val)
> print li.reverse()
>
> returns nothing, but,
>
> val = 'string'
> li = list(val)
> li.reverse()
> print li
>
> returns what I want. Why does Python do that?

Because list.reverse() modifies a list, it doesn't create and return a
new one.

A common idiom for returning a reversed copy of a list is:
  li[::-1]

You can also use the builtin "reversed" -- it doesn't return a list,
but rather a reverse iterator. You can create a list from an iterator
by passing it to the list() initializer, like list(reversed(li)).

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


Re: Can you determine the sign of the polar form of a complex number?

2007-10-17 Thread Jason
On Oct 17, 7:51 am, [EMAIL PROTECTED] wrote:
> Just to clarify what I'm after:
>
> If you plot (-3)^n where n is a set of negative real numbers between 0
> and -20 for example, then you get a discontinuos line due to the
> problem mentioned above with fractional exponents. However, you can
> compute what the correct absolute value of the the missing points
> should be (see z2 above for an example), but I would like to know how
> to determine what the correct sign of z2 should be so that it fits the
> graph.

As Roy said, a math newsgroup may be able to help you better, as you
seem to be having fundamental issues with imaginary numbers.  The
imaginary part isn't an artifact of computing (-3+0j)**(-4.5), it is
an integral part of the answer.  Without the imaginary part, the
result is very, very incorrect.

Actually, the graph result of (-3)^n is not necessarily discontinuous
at the intervals you specified.  You just need to graph the result
with the proper number of dimensions.  If you want to plot the results
of (-3)^n for n=0 to -20, you need to make a three dimensional graph,
a two dimensional graph with two sets of lines, or a circular graph
with labeled values of n.

Complex numbers can be viewed as having a magnitude and a rotation in
the real/imaginary plane.  This is called polar form.  Complex numbers
can also be represented using a Cartesian form, which is how Python
displays complex numbers.

Python's complex numbers allow you to extract the real or imaginary
part separately, via the "real" and "imag" attributes.  To convert to
polar form, you'll need to use the abs built-in to retrieve the
magnitude, and math.atan2 to retrieve the angle.  (Remember that the
imaginary part is considered the Y-axis component.)

Depending on what you're doing, you might need the real part or the
magnitude.  It sounds a little bit like you're trying to represent
something as a flatlander when you should be in Spaceland.  (http://
en.wikipedia.org/wiki/Flatland)

  --Jason

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


Re: Noob questions about Python

2007-10-17 Thread Furkan Kuru
li.reverse() does not return a list it just changes the list li.

val = 00110 is evaluated in base 8 try without leading 0s



On 10/17/07, Ixiaus <[EMAIL PROTECTED]> wrote:
>
> I have recently (today) just started learning/playing with Python. So
> far I am excited and impressed (coming from PHP background).
>
> I have a few questions regarding Python behavior...
>
> val = 'string'
> li = list(val)
> print li.reverse()
>
> returns nothing, but,
>
> val = 'string'
> li = list(val)
> li.reverse()
> print li
>
> returns what I want. Why does Python do that?
>
> Also I have been playing around with Binary math and noticed that
> Python treats:
>
> val = 00110
>
> as the integer 72 instead of returning 00110, why does Python do that?
> (and how can I get around it?)
>
> Grateful for any replies!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

pyparsing batch file

2007-10-17 Thread Fabian Braennstroem
Hi,

me again :-)

I would like to parse a small batch file:

file/read-case kepstop.cas
file/read-data keps1500.dat
solve/monitors/residual/plot no
solve/monitors/residual/print yes
/define/boundary-conditions in velocity-inlet 10 0.1 0.1 no 1
it 500
wd keps1500_500.dat
yes
exit

Right now, I use this little example:

from pyparsing import *

input =
open("/home/fab/HOME/Dissertation/CFD/Fluent/Batch/fluent_batch",
'r')
data = input.read()

#
# Define Grammars
#

integer = Word(nums)
hexnums = Word(alphanums)
end = Literal("\n").suppress()
all = SkipTo(end)
#threadname = dblQuotedString
threadname_read_case = Literal("file/read-case")
threadname_read_data= Literal("file/read-data")
threadname_it = Literal("it")
write_data=Literal("wd")
cas_datei= Word(alphanums)
iteration= Word(nums)
write= Word(alphanums)
file_read_data= "file/read-data " + hexnums.setResultsName("rd")

logEntry = threadname_read_case.setResultsName("threadname")
+ cas_datei.setResultsName("cas_datei")+file_read_data
logEntry = file_read_data
logEntryNew = threadname_it.setResultsName("threadname") +
iteration.setResultsName("iteration")
logEntryWD = write_data.setResultsName("threadname") +
write.setResultsName("write")

#

for tokens in logEntryNew.searchString(data):
print
print "Iteration Command=\t "+ tokens.threadname
print "Number of Iterations=\t "+ tokens.iteration
for x in tokens.condition:
   print x
print 50*"-"

for tokens in logEntryWD.searchString(data):
print
print "Write Data Command=\t "+ tokens.threadname
print "Data File Name=\t "+ tokens.write
for x in tokens.condition:
   print x
print 50*"-"

for tokens in logEntry.searchString(data):
print
print "no idea=\t "+ tokens.threadname
print "Data File=\t "+ tokens.rd
print
for x in tokens.condition:
   print x
print 50*"-"


Unfortunately, it does not parse the whole file names with
the underscore and I do not know yet, how I can access the
line with 'define/boundary-conditions'. Every 'argument' of
that command should become a separate python variable!?
Does anyone have an idea, how I can achieve this!?
Regards!
Fabian

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

Re: Noob questions about Python

2007-10-17 Thread Grant Edwards
On 2007-10-17, Ixiaus <[EMAIL PROTECTED]> wrote:

> val = 'string'
> li = list(val)
> print li.reverse()
>
> returns nothing, but,
>
> val = 'string'
> li = list(val)
> li.reverse()
> print li
>
> returns what I want. Why does Python do that?

Because it does. :)

> Also I have been playing around with Binary math and noticed that
> Python treats:
>
> val = 00110
>
> as the integer 72 instead of returning 00110, why does Python do that?

In order to be "compatible" with the C language integer literal
convensions, integer litereals staring with a '0' are base-8,
so 00110 is

  0 * 8^0 0
 +   1  * 8^1 8
 +  1   * 8^264
 + 0* 8^3 0
 +0 * 8^4 0
   
 72   

> (and how can I get around it?)

You can't.

-- 
Grant Edwards   grante Yow! Do you guys know we
  at   just passed thru a BLACK
   visi.comHOLE in space?
-- 
http://mail.python.org/mailman/listinfo/python-list


open remote terminal

2007-10-17 Thread Fabian Braennstroem
Hi,

I would like to use python to start an terminal, e.g. xterm, and login on a
remote machine using rsh or ssh. This could be done using 'xterm -e ssh
machine', but after the login I would like to jump to a given directory.
Does anyone have an idea how to do this with python?

Regards!
Fabian

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


Re: Stopping a fucntion from printing its output on screen

2007-10-17 Thread MRAB
On Oct 17, 4:01 pm, Jeremy Sanders  wrote:
> sophie_newbie wrote:
> > Hi, in my program i need to call a couple of functions that do some
> > stuff but they always print their output on screen. But I don't want
> > them to print anything on the screen. Is there any way I can disable
> > it from doing this, like redirect the output to somewhere else? But
> > later on in the program i then need to print other stuff so i'd need
> > to re-enable printing too. Any ideas?
>
> If they are python functions, this hack should work...
>
> import sys
>
> class NullWriter(object):
> def write(self, arg):
> pass
>
> def testfunc():
> print "this is a test"
>
> nullwrite = NullWriter()
> oldstdout = sys.stdout
> sys.stdout = nullwrite  # disable output
> testfunc()
> sys.stdout = oldstdout  # enable output
> testfunc()
>
You might want to guarantee that the output is re-enabled even if
testfunc() raises an exception:

nullwrite = NullWriter()
oldstdout = sys.stdout
sys.stdout = nullwrite  # disable output
try:
testfunc()
finally:
sys.stdout = oldstdout  # enable output

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


Noob questions about Python

2007-10-17 Thread Ixiaus
I have recently (today) just started learning/playing with Python. So
far I am excited and impressed (coming from PHP background).

I have a few questions regarding Python behavior...

val = 'string'
li = list(val)
print li.reverse()

returns nothing, but,

val = 'string'
li = list(val)
li.reverse()
print li

returns what I want. Why does Python do that?

Also I have been playing around with Binary math and noticed that
Python treats:

val = 00110

as the integer 72 instead of returning 00110, why does Python do that?
(and how can I get around it?)

Grateful for any replies!

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


Noob questions about Python

2007-10-17 Thread Ixiaus
I have recently (today) just started learning/playing with Python. So
far I am excited and impressed (coming from PHP background).

I have a few questions regarding Python behavior...

val = 'string'
li = list(val)
print li.reverse()

returns nothing, but,

val = 'string'
li = list(val)
li.reverse()
print li

returns what I want. Why does Python do that?

Also I have been playing around with Binary math and noticed that
Python treats:

val = 00110

as the integer 72 instead of returning 00110, why does Python do that?
(and how can I get around it?)

Grateful for any replies!

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


Re: linear programming in Python

2007-10-17 Thread Carl Banks
On Oct 17, 11:44 am, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I'm new to this group so I don't know if this question has been posted
> before, but does anyone knows about linear/integer programming
> routines in Python that are available on the web, more specifically of
> the branch and bound method.


Sciy and Numpy


Scipy has a wrapper for the Minpack, which has a (continuous) linear
programming solver.

I don't recall if there's an integer programming solver in there,
though.  Even if there isn't, Python has some very good tools for
wrapping Fortran and some C numerical routines.  The F2PY package,
which is part of Numpy, does this.


Carl Banks

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


  1   2   3   >