Re: Directory creation

2008-09-07 Thread Fredrik Lundh

srinivasan srinivas wrote:


Can someone tell me is there any module available to create directories??

I tried os, tempfile.
I was facing some issues with os.mkdir(). The mode setting was not proper with 
this method.

I created the directory 'stdin' with '0700' mode using os.mkdir() method.

$> ls -alR stdin/
stdin/:
total 12
drwx--S---   2 munisams munisams 4096 Sep  3 02:00 .

What is that 'S' in the group permission field??


David Wright explained why this is the expected behaviour last time you 
posted about this:


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



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


unexpected class behaviour

2008-09-07 Thread Jan Schäfer
Hi all,

can anyone explain the behaviour of the following code sniplet:

---> schnipp <---
class Base(object):
def __init__( self, lst=[] ):
self.varlist = lst

def addVar( self, var ):
self.varlist.append(var)  

class Derived(Base):
def __init__( self, var ):
Base.__init__(self)
self.addVar(var)

vars = ['foo', 'bar']

for ivar in vars:
obj = Derived(ivar)
print ivar, obj, obj.varlist
---> schnapp <---

After running (Python 2.5.1), I get the following output:
foo <__main__.Derived object at 0xb7c608cc> ['foo']
bar <__main__.Derived object at 0xb7c6092c> ['foo', 'bar']

So, I get two different objects, but how does the 'foo' get into the second
varlist? I'm a little bit confused about this, any ideas?

Thanks in advance

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


tracking collection modification

2008-09-07 Thread usenet . tolomea
I'm working on a remote object system, something kinda like Pyro.
For the purposes of caching I need to be able to tell if a given
dict / list / set has been modified.
Ideally what I'd like is for them to have a modification count
variable that increments every time the particular collection is
modified. Unfortunately I can't find anything like that and since this
needs to work for the regular normal list / dict / set objects
subclassing them to add the modification count isn't useful.
I realize I could take a copy and then compare the copy to the
original, but that's a fairly heavy handed approach and I was hoping
for something light and fast.
Does anyone have any suggestions on best to approach this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected class behaviour

2008-09-07 Thread Fredrik Lundh

Jan Schäfer wrote:


can anyone explain the behaviour of the following code sniplet:


well, it *is* explained in the tutorial, the language reference, and the 
FAQ, so yes, it can be explained ;-)


for more information, see this page:

http://effbot.org/zone/default-values.htm



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


Re: unexpected class behaviour

2008-09-07 Thread kaer
On 7 sep, 12:40, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Jan Schäfer wrote:
> > can anyone explain the behaviour of the following code sniplet:
>
> well, it *is* explained in the tutorial, the language reference, and the
> FAQ, so yes, it can be explained ;-)
>
> for more information, see this page:
>
>  http://effbot.org/zone/default-values.htm
>
> 

Well, you may want replace the last line by:
print ivar, obj, obj.varlist, id(obj.varlist)

To have another behavior, you may want replace the 3 first lines by:
class Base(object):
def __init__( self, lst=None ):
if lst is None: lst=[]
self.varlist = lst

Enjoy Python !
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-09-07 Thread Gabriel Genellina
En Sat, 06 Sep 2008 17:18:55 -0300, clurker <[EMAIL PROTECTED]> escribió:

> Michele Simionato wrote:
>
>> On Aug 28, 6:21 am, ssecorp <[EMAIL PROTECTED]> wrote:
>>> Is there a way to view all the modules I have available for import
>>> from within Python?
>>> Like writing in the interpreter:
>>
>> Try:
>>
> help()
>> help> modules
>> Please wait a moment while I gather a list of all available modules...
>> 
>
> This looks like it could be a useful tool, but when I try it
> I get the following:
>
> Please wait a moment while I gather a list of all available modules...
[...]
>   File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 1342,
> in 
>
>   File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 927,
> in main
>
> UnboundLocalError: local variable 'given_files' referenced before assignment


Unfortunately the "modules" help command actually imports all the available 
packages, and a buggy one may stop the whole process with an error.

> Apparently python knows about them both, but I don't know I
> haven't introduced an incompatibility somewhere...and that PIL
> package showing up at the tail of the errors was one of my
> more recent additions...

If import of a package fails, the error reported is not accurate. In this case, 
probably some other package failed, that itself imported PIL. Line 927 in 
PIL/__init__.py does not exist.

A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with this 
one:

for importer, modname, ispkg in pkgutil.walk_packages(onerror=lambda 
name:None):

(the onerror argument makes it to ignore all errors)

-- 
Gabriel Genellina

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


Re: modules path

2008-09-07 Thread Gabriel Genellina
En Sat, 06 Sep 2008 20:26:24 -0300, Python <[EMAIL PROTECTED]> escribió:

> now one question came up, how do I make those path permanent?
> i mean, sys.path.append( adds it for the current session,
> yet when i logout of IDLE and start it again it's gone...
> how do i keep it in there?

You can add that path to the PYTHONPATH environment variable, or you can put a 
.pth file in the current Lib directory, containing the desired path.
See http://docs.python.org/inst/search-path.html and the documentation for the 
site module (although it appears not to be totally accurate).

-- 
Gabriel Genellina

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


Error importing mxTidy

2008-09-07 Thread Mike Hostetler
I built and installed mx-experimental 3.0.0 from source and it seemed to go
fine.  But when I try to import it, I get this:

localhost% python -c "import mx.Tidy"
Traceback (most recent call last):
  File "", line 1, in ?
  File "mx/Tidy/__init__.py", line 7, in ?
from Tidy import *
  File "mx/Tidy/Tidy.py", line 7, in ?
from mxTidy import *
  File "mx/Tidy/mxTidy/__init__.py", line 7, in ?
from mxTidy import *
ImportError: No module named mxTidy

This seems strange to me, since it found the mx.Tidy module but not the mxTidy
module underneath it.  But I guess I don't know how the mx-experimental classes
are put together, so I can't really guess what is happening.  Thus I am posting
here. :)
  

-- 
[EMAIL PROTECTED]
SDF Public Access UNIX System - http://sdf.lonestar.org
--
http://mail.python.org/mailman/listinfo/python-list


Python and M2Crypto question

2008-09-07 Thread Bojan Mihelac
Hi all!

I am trying to install M2Crypto to work on OSX10.5 apache
(mod_python). Error I receive:

Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-
macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image
found.  Did find:
/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg-
tmp/M2Crypto/__m2crypto.so: no matching architecture in universal
wrapper

I guess that have to do something with x64 architecture but I am
stucked and not able to find a way and to make this work. M2Crypto lib
works good stand alone.

Any help appreciated,
Bojan
--
http://mail.python.org/mailman/listinfo/python-list


doctest not seeing any of my doc tests

2008-09-07 Thread Steven D'Aprano
I have a function in my module:

def selftest(verbose=False):
import doctest
doctest.testmod(verbose=verbose)


When I run it, it fails to find any of my doc tests, including the tests 
in __main__, and in fact it looks like it can't even find my functions 
and classes:


>>> mymodule.selftest(True)
1 items had no tests:
__main__
0 tests in 1 items.
0 passed and 0 failed.
Test passed.


The second and subsequent times I call selftest, I get the same result 
except that it adds this line to the end:

*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.


I've exited from Python and restarted the interactive interpreter. I've 
deleted the module .pyc file. Neither has helped.

I've tried reading over the doctest module to see if there are any hints 
as to what's going wrong, but it's quite opaque to me. If there's anyone 
out there with a good understanding of doctest, I'd appreciate some 
pointers for where to start looking, or otherwise how to fix this problem.

For what it's worth, I'm running 

Python 2.5 (r25:51908, Apr 10 2007, 10:29:13)
[GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2




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


Re: doctest not seeing any of my doc tests

2008-09-07 Thread Fredrik Lundh

Steven D'Aprano wrote:


I have a function in my module:

def selftest(verbose=False):
import doctest
doctest.testmod(verbose=verbose)


what happens if you change the above to

  def selftest(verbose=False):
  import doctest, yourmodule
  doctest.testmod(yourmodule, verbose=verbose)

(where yourmodule is the name of your module, obviously)



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


[ANN] The Python Papers Vol 3 Iss 2 in one PDF

2008-09-07 Thread [EMAIL PROTECTED]
Hi everyone

Our original release of TPP Volume 3 Issue 2 is in the form of one PDF
per article. A number of readers had kindly requested for a parallel
release for the entire issue in a single PDF for easy transport.

Despite prevalent "industrial standards" for one PDF per article such
as IEEE and ACM, we can understand our readers' point of view. We can
see mutually exclusive advantages of both system - one PDF per article
allows for tracking of view counts for each article whereas one PDF
per issue allows for easy transport and offline browsing. Therefore,
we had chose to released the entire volume as a single PDF in parallel
and will continue to do so in future.

The entire Volume 2  Issue 3 can be accessed from http://www.pythonpapers.org.

We look forward to your continued support and contributions.

Regards
Maurice Ling
Co-EIC, TPPA
--
http://mail.python.org/mailman/listinfo/python-list


Re: doctest not seeing any of my doc tests

2008-09-07 Thread bearophileHUGS
Steven D'Aprano, first of all you can try to run a minimal module, to
see if your doctesting works, like:

"""
>>> 1 + 1
3
"""
def foo():
"""
>>> foo()
1
"""
return 0
import doctest
doctest.testmod()

If that works correctly, then you can show us some more of the code
and tests.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Not fully understanding the role of Queue.task_done()

2008-09-07 Thread Aahz
In article <[EMAIL PROTECTED]>,
Fredrik Lundh  <[EMAIL PROTECTED]> wrote:
>Martin DeMello wrote:
>>
>> In the interests of not hammering the db unnecessarily, I'm
>> considering the following
>> 1. A series of independent "monitor" threads that collect information
>> over TCP from the cluster of machines, and write it to a queue
>> 2. A "logger" thread that empties the queue every second or so and
>> inserts the collected information to the db via a single insert
>> statement
>
>why are you using a queue for this case, btw?  why not just use a plain list
>
> L = []
> lock = threading.Lock()
>
>and add stuff using append in the monitor threads
>
> with lock:
> L.append(item)

Because using a queue requires less thinking.  I certainly would use a
queue in this case instead of rolling my own.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach
--
http://mail.python.org/mailman/listinfo/python-list


Re: Not fully understanding the role of Queue.task_done()

2008-09-07 Thread Fredrik Lundh

Aahz wrote:


why are you using a queue for this case, btw?  why not just use a plain list

L = []
lock = threading.Lock()

and add stuff using append in the monitor threads

with lock:
L.append(item)


Because using a queue requires less thinking.


given that the whole reason for this thread was that Queue API didn't 
fit the OP:s problem, that's a rather dubious statement.


(btw, I've always thought that Python was all about making it easy to 
express the solution to a given problem in code, not to let you write 
programs without using your brain.  when did that change?)




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


Re: atomic section in code

2008-09-07 Thread Diez B. Roggisch

Hendrik van Rooyen schrieb:

Fredrik Lundh  wrote:


sounds like he wants/needs non-cooperative, mandatory locking.


Could one get there using ctypes to disable interrupts?


Not as such, ctypes can't execute arbitrary machine code. But of course 
you can create a C-lib that does what you want (IF it can be done, that 
is..), and wrap that.



Cross Platform?


Certainly not.


I can think of lots of hassles, starting with permissions
to use the privileged instructions.



I don't think there is a chance for this without major system tinkering. 
Under Linux, you could create a real time thread so highly prioritized 
that it won't yield any time to any other scheduler. And in a 
kernel-module, you can call cli (or whatever the needed call is). But 
this will most probably break your system.


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


firefox timestamp

2008-09-07 Thread abhilash pp
hi all,
--
http://mail.python.org/mailman/listinfo/python-list

Re: modules path

2008-09-07 Thread Python


On 7 sep 2008, at 13:50, Gabriel Genellina wrote:


En Sat, 06 Sep 2008 20:26:24 -0300, Python <[EMAIL PROTECTED]> escribió:


now one question came up, how do I make those path permanent?
i mean, sys.path.append( adds it for the current session,
yet when i logout of IDLE and start it again it's gone...
how do i keep it in there?


You can add that path to the PYTHONPATH environment variable, or you  
can put a .pth file in the current Lib directory, containing the  
desired path.
See http://docs.python.org/inst/search-path.html and the  
documentation for the site module (although it appears not to be  
totally accurate).


--
Gabriel Genellina




i read that but was wondering why some modules installed by macports  
did show up

in the path and some didn't
the PYTHONPATH wasn't set anywhere in my shell

I did add it and now it works!

Thanks John & Gabriel!

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


Re: [ANN] pysqlite 2.5.0 released

2008-09-07 Thread Matthias Huening

Hi,



- - Connection.enable_load_extension(enabled) to allow/disallow extension
  loading. Allows you to use fulltext search extension, for example ;-)


The following code (from the docs) produces an error:

from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
# Load the fulltext search extension
con.enable_load_extension(True)
con.execute("select load_extension('./fts3.so')")
con.enable_load_extension(False)


Error is:

con.execute("select load_extension('./fts3.so')")
pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht gefunden.

Where should I look for the module?

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


formatting a string with thousands separators

2008-09-07 Thread SimonPalmer
anyone recommend a way of formatting floats with comma separators?

e.g. 50.00 -> 500,000.00
--
http://mail.python.org/mailman/listinfo/python-list


__builtins__ magic behavior

2008-09-07 Thread Patrick Maupin
__builtins__ in 2.5.2 doesn't seem to behave like I remember it did
the last time I did some custom stuff with it, a very long time ago.

This isn't surprising, because of ongoing optimization, but it's hard
to google for '__builtins__' so I didn't really find any documentation
on the current CPython behavior, which in some cases seems quite
strange to me.

The documentation node at http://docs.python.org/ref/naming.html has a
"here be dragons" note on __builtins__, which is nice as far as it
goes, but doesn't provide any help for people wanting to abuse the
current CPython implementation.  Additionally, the sentence
immediately above the note, "__builtins__ can be set to a user-created
dictionary to create a weak form of restricted execution" not only
contradicts the note, but in some cases appears not to be true.

When the code below is run, either standalone or by importing it, the
builtins used are different depending on whether exec is used with
globals() or with a copy of globals().  Any explanations for this
behavior would be much appreciated.

Thanks,
Pat

Executing:
{{{
original = __builtins__
if hasattr(original, '__dict__'): original = original.__dict__
copy = original.copy()

# Make the dictionaries different and use new one
copy['foo'] = 'bar'
del copy['len']
del original['chr']
__builtins__ = copy

testcode = '''
try: print foo
except: print "foo not found"
try: print len
except: print "len not found"
try: print chr
except: print "chr not found"
print
'''

x = globals()
assert type(x) is dict
y = {}
y.update(x)
assert y == x

print 'Executing in globals()'
exec testcode in x

print 'Executing in copy'
exec testcode in y
}}}

results in:

Executing in globals()
foo not found

chr not found

Executing in copy
bar
len not found

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


Re: max(), sum(), next()

2008-09-07 Thread Mensanator
On Sep 6, 11:05�pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote:
>
> [...]
>
> >> They could have decided that sum must take at least two arguments,
> >> because addition requires two arguments and it's meaningless to talk
> >> about adding a single number without talking about adding it to
> >> something else. But they didn't.
>
> > Ok. But the problem is they DID in SQL: x + Null = Null.
>
> Sheesh. That's not a problem, because Python is not trying to be a
> dialect of SQL.

And yet, they added a Sqlite3 module.

>
> If you want a NULL object, then there are recipes on the web that will
> give you one. Then all you need to do is call sum(alist or [NULL]) and it
> will give you the behaviour you want.

Actualy, I already get the behaviour I want. sum([1,None])
throws an exception. I don't see why sum([]) doesn't throw
an exception also (I understand that behaviour is by design,
I'm merely pointing out that the design doesn't cover every
situation).

>
> [...]
>
> > Here's a real world example (no ivory tower stuff):
>
> > An oil refinery client has just excavated a big pile of dirt to lay a
> > new pipeline.
> [snip details]
> > Can't I just use a sum of 0 to tell me when data is missing? No, because
> > in some cases the reporting limit of undetected compounds is set to 0.
>
> You can't use a sum of 0 to indicate when data is missing, full stop.

Exactly. That's why I would prefer sum([]) to raise an
exception instead of giving a false positive.

> The
> data may require 15 tests when only 3 have actually been done:
>
> sum([1.2e-7, 9.34e-6, 2.06e-8])

Biggest problem here is that it is often unknown just
how many records you're supposed to get from the query,
so we can't tell that a count of 3 is supposed to be 15.

>
> Missing data and a non-zero sum. How should sum() deal with that?

That's a seperate issue and I'm not saying it should as
long as the list contains actual numbers to sum.
sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an
exception, as it should. But what types are contained
in []?

>
> The answer is that sum() can't deal with that. You can't expect sum() to
> read your mind, know that there should be 15 items instead of 3, and
> raise an error. So why do you expect sum() to read your mind and
> magically know that zero items is an error, especially when for many
> applications it is NOT an error?

For the simple reason it doesn't have to read your mind,
a mechanism has already been built into the function: start
value. For those situations where an empty list is desired
to sum to 0, you could use sum(alist,0) and use sum(alist) for
those cases where summing an empty list is meaningless.
Shouldn't you have to explicitly tell sum() how deal with
situations like empty lists rather than have it implicitly
assume a starting value of 0 when you didn't ask for it?

>
> The behaviour you want for this specific application is unwanted,
> unnecessary and even undesirable for many other applications. The
> solution is for *you* to write application-specific code to do what your
> application needs, instead of relying on a general purpose function
> magically knowing what you want.

Does division magically know what you want? No, it raises an
exception when you do something like divide by 0. Isn't it
Pythonic to not write a litany of tests to cover every
possible case, but instead use try:except?

But try:except only works if the errors are recognized.
And sum() says that summing an empty list is NEVER an error
under ANY circumstance. That may be true in MOST cases, but
it certainly isn't true in ALL cases.

>
> --
> Steven

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

Re: max(), sum(), next()

2008-09-07 Thread Patrick Maupin
On Sep 7, 12:30 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Sep 6, 11:05 pm, Steven D'Aprano <[EMAIL PROTECTED]
> > Sheesh. That's not a problem, because Python is not trying to be a
> > dialect of SQL.
>
> And yet, they added a Sqlite3 module.

Does that mean that, because there is an 'os' module, Python is trying
to compete with Linux and Windows?

This is starting to feel like a troll, but JUST IN CASE you are really
serious about wanting to get work done with Python, rather than
complaining about how it is not perfect, I offer the following snippet
which will show you how you can test the results of a sum() to see if
there were any items in the list:

>>> class MyZero(int):
... pass
...
>>> zero = MyZero()
>>> x=sum([], zero)
>>> isinstance(x,MyZero)
True
>>> x = sum([1,2,3], zero)
>>> isinstance(x,MyZero)
False
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: formatting a string with thousands separators

2008-09-07 Thread Alan G Isaac

On 9/7/2008 12:22 PM SimonPalmer apparently wrote:

anyone recommend a way of formatting floats with comma separators?



http://code.activestate.com/recipes/498181/

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


Re: __builtins__ magic behavior

2008-09-07 Thread Gabriel Genellina
En Sun, 07 Sep 2008 14:00:48 -0300, Patrick Maupin <[EMAIL PROTECTED]> escribió:

> __builtins__ in 2.5.2 doesn't seem to behave like I remember it did
> the last time I did some custom stuff with it, a very long time ago.
>
> This isn't surprising, because of ongoing optimization, but it's hard
> to google for '__builtins__' so I didn't really find any documentation
> on the current CPython behavior, which in some cases seems quite
> strange to me.
>
> The documentation node at http://docs.python.org/ref/naming.html has a
> "here be dragons" note on __builtins__, which is nice as far as it
> goes, but doesn't provide any help for people wanting to abuse the
> current CPython implementation.  Additionally, the sentence
> immediately above the note, "__builtins__ can be set to a user-created
> dictionary to create a weak form of restricted execution" not only
> contradicts the note, but in some cases appears not to be true.
>
> When the code below is run, either standalone or by importing it, the
> builtins used are different depending on whether exec is used with
> globals() or with a copy of globals().  Any explanations for this
> behavior would be much appreciated.

Python takes some shortcuts when dealing with builtins. I'll just describe what 
happens (I won't say whether it is "right" or "wrong"). 
The exec statement, when given a string source, compiles it and eventually 
calls PyEval_EvalCodeEx, which creates a new frame using PyFrame_New and 
finally executes it.
A frame object contains a pointer to the previous frame, the code to be 
executed, a pointer to the current globals *and* a separate pointer to the 
current builtins. 
Inside PyFrame_New, there is a shortcut: if the new frame and the previous one 
share the same globals, then the previous builtins are copied into the new 
frame. Only if the globals differ the builtins are searched in globals. From 
frameobject.c: /* If we share the globals, we share the builtins. Save a lookup 
and a call. */ 
It is this assumption that fails in your code.

If you want to execute some code with modified builtins, do not change 
__builtins__ in the *calling* code, but in the globals that you pass to the 
exec call. That appears to be the most logical approach, and the way the 
developers appear to have expected.

-- 
Gabriel Genellina

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


Re: max(), sum(), next()

2008-09-07 Thread Gabriel Genellina
En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator <[EMAIL PROTECTED]> escribió:

> Actualy, I already get the behaviour I want. sum([1,None])
> throws an exception. I don't see why sum([]) doesn't throw
> an exception also (I understand that behaviour is by design,
> I'm merely pointing out that the design doesn't cover every
> situation).
[...]
> Exactly. That's why I would prefer sum([]) to raise an
> exception instead of giving a false positive.

The built in behavior can't be good for every usage. Nobody prevents you from 
defining yoru own function tailored to your own specs, like this:

def strict_sum(items):
items = iter(items)
try:
first = items.next()
except StopIteration:
raise ValueError, "strict_sum with empty argument"
return sum(items, first)

Tweak as needed. Based on other posts I believe your Python skills are enough 
to write it on your own, so I don't see why you're complaining so hard about 
the current behavior.

-- 
Gabriel Genellina

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


Re: __builtins__ magic behavior

2008-09-07 Thread Patrick Maupin
On Sep 7, 2:50 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> Inside PyFrame_New, there is a shortcut: if the new frame and
> the previous one share the same globals, then the previous
> builtins are copied into the new frame. Only if the globals
> differ the builtins are searched in globals. From frameobject.c:
>  /* If we share the globals, we share the builtins. Save a
> lookup and a call. */

That was exactly my problem.  Thank you for the cogent explanation.

> If you want to execute some code with modified builtins, do not
> change __builtins__ in the *calling* code, but in the globals that
> you pass to the exec call. That appears to be the most logical
> approach, and the way the developers appear to have expected.

Actually, my use-case is a tiny bit different than this.  I am
dynamically creating module objects, and was going nuts trying
to comprehend the inner workings of behind-the-scenes __builtins__
magic in the module object, not realizing that the magic was
actually in the execution frames.

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


problem with permutations

2008-09-07 Thread cnb
I am trying to translate this elegant Erlang-code for finding all the
permutations of a list.
I think it is the same function as is but it doesn't work in Python.
-- is upd in Python. It works as it should.

perms([]) -> [[]];
perms(L)  -> [[H|T] || H <- L, T <- perms(L--[H])].

def perms(lista):
if lista == []:
return [[]]
else:
for h in lista:
return [([h]+[t]) for t in perms(upd(lista, h))]

def upd(lista, elem, acc=tuple([])):
lista = tuple(lista)
if lista == ():
return list(acc)
if lista[0] == elem:
return list(acc + tuple(lista[1:]))
else:
return upd(lista[1:], elem, acc + tuple([lista[0]]))
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-09-07 Thread sc
Gabriel Genellina wrote:

> En Sat, 06 Sep 2008 17:18:55 -0300, clurker <[EMAIL PROTECTED]>
> escribió:
> 
>> Michele Simionato wrote:
>>
>>> On Aug 28, 6:21 am, ssecorp <[EMAIL PROTECTED]> wrote:
 Is there a way to view all the modules I have available for import
 from within Python?
 Like writing in the interpreter:
>>>
>>> Try:
>>>
>> help()
>>> help> modules
>>> Please wait a moment while I gather a list of all available modules...
>>> 
>>
>> This looks like it could be a useful tool, but when I try it
>> I get the following:
>>
>> Please wait a moment while I gather a list of all available modules...
> [...]
>>   File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line
>>   1342,
>> in 
>>
>>   File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line
>>   927,
>> in main
>>
>> UnboundLocalError: local variable 'given_files' referenced before
>> assignment
>
> 
> Unfortunately the "modules" help command actually imports all the
> available packages, and a buggy one may stop the whole process with an
> error.
> 
>> Apparently python knows about them both, but I don't know I
>> haven't introduced an incompatibility somewhere...and that PIL
>> package showing up at the tail of the errors was one of my
>> more recent additions...
> 
> If import of a package fails, the error reported is not accurate. In this
> case, probably some other package failed, that itself imported PIL. Line
> 927 in PIL/__init__.py does not exist.
> 
> A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with
> this one:
> 
> for importer, modname, ispkg in
> pkgutil.walk_packages(onerror=lambda name:None):
> 
> (the onerror argument makes it to ignore all errors)
> 

nice Gabriel, thanx!  At least now "help(); modules" gives me a beautiful
list -- I guess I'll find out what the buggy module is if/when I try
to use it...(all PIL/__init__.py is is about 15 lines of comments 
(referencing a README I can't find))

sc

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

lacking follow-through

2008-09-07 Thread castironpi
I am concerned by the lack of follow-through on some responses to
recent ideas I have described.  Do I merely have a wrong understanding
of group policy?  Is it a good policy (defined with respect to the
future of Python and the welfare of humans at large) if so?  Is there
a serious lack of diligence, or should I merely take more initiative,
and ignore charges of 'pestering'?  (Warning, moderately deep outside
social issues on table too.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread James Mills
Hi,

This is the strangest post I've seen
since I've joined this list (only
recently). What the ?

cheers
James

On Mon, Sep 8, 2008 at 7:00 AM, castironpi <[EMAIL PROTECTED]> wrote:
> I am concerned by the lack of follow-through on some responses to
> recent ideas I have described.  Do I merely have a wrong understanding
> of group policy?  Is it a good policy (defined with respect to the
> future of Python and the welfare of humans at large) if so?  Is there
> a serious lack of diligence, or should I merely take more initiative,
> and ignore charges of 'pestering'?  (Warning, moderately deep outside
> social issues on table too.)
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-07 Thread James Mills
Can we stop this thread now? :)

I think we've all seen what the intended
behavior of sum(), max() and other
similar functions.

cheers
James

On Mon, Sep 8, 2008 at 3:30 AM, Mensanator <[EMAIL PROTECTED]> wrote:
> On Sep 6, 11:05�pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote:
>>
>> [...]
>>
>> >> They could have decided that sum must take at least two arguments,
>> >> because addition requires two arguments and it's meaningless to talk
>> >> about adding a single number without talking about adding it to
>> >> something else. But they didn't.
>>
>> > Ok. But the problem is they DID in SQL: x + Null = Null.
>>
>> Sheesh. That's not a problem, because Python is not trying to be a
>> dialect of SQL.
>
> And yet, they added a Sqlite3 module.
>
>>
>> If you want a NULL object, then there are recipes on the web that will
>> give you one. Then all you need to do is call sum(alist or [NULL]) and it
>> will give you the behaviour you want.
>
> Actualy, I already get the behaviour I want. sum([1,None])
> throws an exception. I don't see why sum([]) doesn't throw
> an exception also (I understand that behaviour is by design,
> I'm merely pointing out that the design doesn't cover every
> situation).
>
>>
>> [...]
>>
>> > Here's a real world example (no ivory tower stuff):
>>
>> > An oil refinery client has just excavated a big pile of dirt to lay a
>> > new pipeline.
>> [snip details]
>> > Can't I just use a sum of 0 to tell me when data is missing? No, because
>> > in some cases the reporting limit of undetected compounds is set to 0.
>>
>> You can't use a sum of 0 to indicate when data is missing, full stop.
>
> Exactly. That's why I would prefer sum([]) to raise an
> exception instead of giving a false positive.
>
>> The
>> data may require 15 tests when only 3 have actually been done:
>>
>> sum([1.2e-7, 9.34e-6, 2.06e-8])
>
> Biggest problem here is that it is often unknown just
> how many records you're supposed to get from the query,
> so we can't tell that a count of 3 is supposed to be 15.
>
>>
>> Missing data and a non-zero sum. How should sum() deal with that?
>
> That's a seperate issue and I'm not saying it should as
> long as the list contains actual numbers to sum.
> sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an
> exception, as it should. But what types are contained
> in []?
>
>>
>> The answer is that sum() can't deal with that. You can't expect sum() to
>> read your mind, know that there should be 15 items instead of 3, and
>> raise an error. So why do you expect sum() to read your mind and
>> magically know that zero items is an error, especially when for many
>> applications it is NOT an error?
>
> For the simple reason it doesn't have to read your mind,
> a mechanism has already been built into the function: start
> value. For those situations where an empty list is desired
> to sum to 0, you could use sum(alist,0) and use sum(alist) for
> those cases where summing an empty list is meaningless.
> Shouldn't you have to explicitly tell sum() how deal with
> situations like empty lists rather than have it implicitly
> assume a starting value of 0 when you didn't ask for it?
>
>>
>> The behaviour you want for this specific application is unwanted,
>> unnecessary and even undesirable for many other applications. The
>> solution is for *you* to write application-specific code to do what your
>> application needs, instead of relying on a general purpose function
>> magically knowing what you want.
>
> Does division magically know what you want? No, it raises an
> exception when you do something like divide by 0. Isn't it
> Pythonic to not write a litany of tests to cover every
> possible case, but instead use try:except?
>
> But try:except only works if the errors are recognized.
> And sum() says that summing an empty list is NEVER an error
> under ANY circumstance. That may be true in MOST cases, but
> it certainly isn't true in ALL cases.
>
>>
>> --
>> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list

Re: problem with permutations

2008-09-07 Thread James Mills
Hi,

Here's a (better?) function:

def permutate(seq):
if not seq:
return [seq]
else:
temp = []
for k in range(len(seq)):
part = seq[:k] + seq[k+1:]
for m in permutate(part):
temp.append(seq[k:k+1] + m)
return temp

cheers
James

On Mon, Sep 8, 2008 at 6:47 AM, cnb <[EMAIL PROTECTED]> wrote:
> I am trying to translate this elegant Erlang-code for finding all the
> permutations of a list.
> I think it is the same function as is but it doesn't work in Python.
> -- is upd in Python. It works as it should.
>
> perms([]) -> [[]];
> perms(L)  -> [[H|T] || H <- L, T <- perms(L--[H])].
>
> def perms(lista):
>if lista == []:
>return [[]]
>else:
>for h in lista:
>return [([h]+[t]) for t in perms(upd(lista, h))]
>
> def upd(lista, elem, acc=tuple([])):
>lista = tuple(lista)
>if lista == ():
>return list(acc)
>if lista[0] == elem:
>return list(acc + tuple(lista[1:]))
>else:
>return upd(lista[1:], elem, acc + tuple([lista[0]]))
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: formatting a string with thousands separators

2008-09-07 Thread James Mills
Hi,

There is a much easier more consistent way:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8")
'en_AU.UTF-8'
>>> locale.format("%0.2f", 500, True)
'5,000,000.00'
>>>

cheers
James

On Mon, Sep 8, 2008 at 5:24 AM, Alan G Isaac <[EMAIL PROTECTED]> wrote:
> On 9/7/2008 12:22 PM SimonPalmer apparently wrote:
>>
>> anyone recommend a way of formatting floats with comma separators?
>
>
> http://code.activestate.com/recipes/498181/
>
> Alan Isaac
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Updating python dictionary

2008-09-07 Thread [EMAIL PROTECTED]
Hello...

I have a dict of key/values and I want to change the keys in it, based
on another mapping dictionary. An example follows:

MAPPING_DICT = {
'a': 'A',
'b': 'B',
}

my_dict = {
'a': '1',
'b': '2'
}

I want the finished my_dict to look like:

my_dict = {
'A': '1',
'B': '2'
}

Whereby the keys in the original my_dict have been swapped out for the
keys mapped in MAPPING_DICT.

Is there a clever way to do this, or should I loop through both,
essentially creating a brand new dict?

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


Re: formatting a string with thousands separators

2008-09-07 Thread Fredrik Lundh

James Mills wrote:


There is a much easier more consistent way:


import locale
locale.setlocale(locale.LC_ALL, "en_AU.UTF-8")

'en_AU.UTF-8'


doesn't work on all Python platforms, though:

>>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8")
Traceback (most recent call last):
  File "", line 1, in 
  File "c:\python25\lib\locale.py", line 478, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

and is likely to give you somewhat unpredictable output if you use the 
machine's actual locale:


>>> import os
>>> locale.setlocale(locale.LC_ALL, os.environ["LANG"])
'sv_SE.UTF-8'
>>> locale.format("%0.2f", 500, True)
'500,00'



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


Re: lacking follow-through

2008-09-07 Thread Gabriel Genellina
En Sun, 07 Sep 2008 18:00:30 -0300, castironpi <[EMAIL PROTECTED]> escribió:

> I am concerned by the lack of follow-through on some responses to
> recent ideas I have described.  Do I merely have a wrong understanding
> of group policy?  Is it a good policy (defined with respect to the
> future of Python and the welfare of humans at large) if so?  Is there
> a serious lack of diligence, or should I merely take more initiative,
> and ignore charges of 'pestering'?  (Warning, moderately deep outside
> social issues on table too.)

Maybe people just doesn't have anything to say?
Last thing I remember from you, is some mmap-based tree, and I'm not interested.

-- 
Gabriel Genellina

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


Re: Updating python dictionary

2008-09-07 Thread Marc 'BlackJack' Rintsch
On Sun, 07 Sep 2008 14:51:32 -0700, [EMAIL PROTECTED] wrote:

> MAPPING_DICT = {
> 'a': 'A',
> 'b': 'B',
> }
> 
> my_dict = {
> 'a': '1',
> 'b': '2'
> }
> 
> I want the finished my_dict to look like:
> 
> my_dict = {
> 'A': '1',
> 'B': '2'
> }
> 
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
> 
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?

You only have to loop through `my_dict`:

In [187]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:MAPPING_DICT = {
:'a': 'A',
:'b': 'B',
:}
:
:my_dict = {
:'a': '1',
:'b': '2'
:}
:--

In [188]: dict((MAPPING_DICT[k], v) for k, v in my_dict.iteritems())
Out[188]: {'A': '1', 'B': '2'}

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


Re: lacking follow-through

2008-09-07 Thread Marc 'BlackJack' Rintsch
On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:

> This is the strangest post I've seen
> since I've joined this list (only
> recently). What the ?

Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a 
bot!?  :-)

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


Re: Updating python dictionary

2008-09-07 Thread MK Bernard
On Sep 7, 2:51 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hello...
>
> I have a dict of key/values and I want to change the keys in it, based
> on another mapping dictionary. An example follows:
>
> MAPPING_DICT = {
>     'a': 'A',
>     'b': 'B',
>
> }
>
> my_dict = {
>     'a': '1',
>     'b': '2'
>
> }
>
> I want the finished my_dict to look like:
>
> my_dict = {
>     'A': '1',
>     'B': '2'
>
> }
>
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
>
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?
>
> Cheers,
> Andy.

You could accomplish this with something similar to the following:
new_dict = {}
for x in MAPPING_DICT.keys():
if x in my_dict.keys():
new_dict[MAPPING_DICT[x]] = my_dict[x]

Although there is probably a better solution to the problem your
having. Perhaps more details could help us lead in you the right
direction?

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


Re: Updating python dictionary

2008-09-07 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


Is there a clever way to do this, or should I loop through both,
essentially creating a brand new dict?


since none of your dictionaries contain the keys you want in the final 
dictionary, creating a brand new dict sounds pretty clever to me.




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


Re: Updating python dictionary

2008-09-07 Thread James Mills
Hi,

There is "never" a "clever" way
of doing anything, but:

$ cat test.py
MAPPING_DICT = {'a': 'A','b': 'B',}
my_dict = {'a': '1','b': '2'}
my_dict = dict((MAPPING_DICT[k], my_dict[k]) for k in my_dict)
print my_dict
$ python test.py
{'A': '1', 'B': '2'}
$

That should do the trick.

cheers
James

On Mon, Sep 8, 2008 at 7:51 AM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello...
>
> I have a dict of key/values and I want to change the keys in it, based
> on another mapping dictionary. An example follows:
>
> MAPPING_DICT = {
>'a': 'A',
>'b': 'B',
> }
>
> my_dict = {
>'a': '1',
>'b': '2'
> }
>
> I want the finished my_dict to look like:
>
> my_dict = {
>'A': '1',
>'B': '2'
> }
>
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
>
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?
>
> Cheers,
> Andy.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with permutations

2008-09-07 Thread Paul Rubin
cnb <[EMAIL PROTECTED]> writes:
> perms([]) -> [[]];
> perms(L)  -> [[H|T] || H <- L, T <- perms(L--[H])].

I think the most direct transcription might be:

def perms(xs):
if len(xs)==0: return [[]]
return [([h]+t) for h in xs 
for t in perms([y for y in xs if y not in [h]])]

But it is rather inefficient, as is the Erlang version.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Updating python dictionary

2008-09-07 Thread Gabriel Genellina
En Sun, 07 Sep 2008 18:51:32 -0300, [EMAIL PROTECTED] <[EMAIL PROTECTED]> 
escribió:

> I have a dict of key/values and I want to change the keys in it, based
> on another mapping dictionary. An example follows:
>
> MAPPING_DICT = {
> 'a': 'A',
> 'b': 'B',
> }
>
> my_dict = {
> 'a': '1',
> 'b': '2'
> }
>
> I want the finished my_dict to look like:
>
> my_dict = {
> 'A': '1',
> 'B': '2'
> }
>
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
>
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?

Exactly. You can do that in one pass:

my_new_dict = dict((MAPPING_DICT[k],v) for (k,v) in my_dict.iteritems())

That's enough if MAPPING_DICT always contains all the keys. If you want to keep 
old keys that aren't in MAPPING_DICT unchanged, use MAPPING_DICT.get(k,k) 
instead. Other corner cases include many-to-one mappings, and incomplete 
mappings where a replacement key is also an unmapped old key.

-- 
Gabriel Genellina

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


Re: lacking follow-through

2008-09-07 Thread castironpi
On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:
> > This is the strangest post I've seen
> > since I've joined this list (only
> > recently). What the ?
>
> Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a
> bot!?  :-)
>
> Ciao,
>         Marc 'BlackJack' Rintsch

No, I'm legit, and I believe my complaint is.  That's all I can
guarantee anyway.  While I'm still not a vet on Usenet, I'm still
disappointed so far.  Though I should be flattered for my logic to be
ever compared to an A.I.'s.

Maybe the ideas are not that groundbreaking, but they still have been
dropped instead of critiqued.  Problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread Eric Wertman
+1 Bot
--
http://mail.python.org/mailman/listinfo/python-list


Long lines [was Re: __builtins__ magic behavior]

2008-09-07 Thread Steven D'Aprano
Gabriel, could I please ask you to configure your news-reader software or 
editor to limit the length of each line of your posts to 70 characters 
wide, as per the common standard for email and Usenet? Your lines are 
significantly longer than that, including one single line which is 325 
characters wide. That forces a lot of backwards and forwards scrolling to 
read your posts.

Thank you.



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


Re: lacking follow-through

2008-09-07 Thread Fredrik Lundh

Marc 'BlackJack' Rintsch wrote:

Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a 
bot!?  :-)


if so, they sure don't make c.l.py bots like they used to, do they?



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


Re: Updating python dictionary

2008-09-07 Thread John Machin
On Sep 8, 7:51 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hello...
>
> I have a dict of key/values and I want to change the keys in it, based
> on another mapping dictionary. An example follows:
>
> MAPPING_DICT = {
>     'a': 'A',
>     'b': 'B',
>
> }
>
> my_dict = {
>     'a': '1',
>     'b': '2'
>
> }
>
> I want the finished my_dict to look like:
>
> my_dict = {
>     'A': '1',
>     'B': '2'
>
> }
>
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
>
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?
>

Is this homework?

There seems to be an implicit assumption in the answers so far that
your mapping is a 1:1 mapping of all possible input keys.

If it doesn't include all possible input keys, answers will crash with
a KeyError. If there are any many:1 elements in the mapping (for
example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
in some checks for this.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Updating python dictionary

2008-09-07 Thread James Mills
On Mon, Sep 8, 2008 at 8:37 AM, John Machin <[EMAIL PROTECTED]> wrote:
> Is this homework?

I hope it's not - or I'll  be quite annoyed :)

> There seems to be an implicit assumption in the answers so far that
> your mapping is a 1:1 mapping of all possible input keys.
>
> If it doesn't include all possible input keys, answers will crash with
> a KeyError. If there are any many:1 elements in the mapping (for
> example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> in some checks for this.

You are quite right! But then he/she didn't
ask for this right ? :)

cheers
James

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Read and write binary data

2008-09-07 Thread Mars creature
Hi guys,
  I am new to Python, and thinking about migrating to it from matlab
as it is a really cool language. Right now, I am trying to figure out
how to control read and write binary data, like
'formatted','stream','big-endian','little-edian' etc.. as in fortran.
I googled, but can not find a clear answer. Anyone has clue where can
I learn it? Thanks!!
Jinbo
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread John Machin
On Sep 8, 8:36 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Marc 'BlackJack' Rintsch wrote:
> > Yeah, castironpi sometimes doesn't make much sense.  Maybe because it's a
> > bot!?  :-)
>
> if so, they sure don't make c.l.py bots like they used to, do they?
>
> 

That's correct. This one seems to have an anger management module :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread Steven D'Aprano
On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:

> Hi,
> 
> This is the strangest post I've seen
> since I've joined this list (only
> recently). What the ?

Oh don't mind castironpi, many people think he's an IRC bot with some 
experimental AI features that escaped onto Usenet *grins*. If you think 
that post of his was strange, you haven't seen anything yet. Many people 
have kill-filed him, and never even see his posts.

A word to castironpi: you just suggested you will pester the list to get 
a response. It's behaviour like that which gets you kill-filed. If you 
would spend one tenth of the effort that you spend on understand Python 
on understanding human psychology, you will probably get on with others 
much better and find fewer people claiming you're a bot.

Even if you yourself don't understand how others behave and expect you to 
behave, think of it as an intellectual puzzle: how can I fool the strange 
hairless apes into accepting me into their herd?



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


Re: doctest not seeing any of my doc tests

2008-09-07 Thread Steven D'Aprano
On Sun, 07 Sep 2008 15:51:01 +0200, Fredrik Lundh wrote:

> Steven D'Aprano wrote:
> 
>> I have a function in my module:
>> 
>> def selftest(verbose=False):
>> import doctest
>> doctest.testmod(verbose=verbose)
> 
> what happens if you change the above to
> 
>def selftest(verbose=False):
>import doctest, yourmodule
>doctest.testmod(yourmodule, verbose=verbose)
> 
> (where yourmodule is the name of your module, obviously)



Well, that certainly fixed the problem, thanks. It now correctly runs all 
my doctests.

But I don't understand why a bare doctest.testmod() works when you run it 
non-interactively, but fails when run interactively.



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


Re: Updating python dictionary

2008-09-07 Thread John Machin
On Sep 8, 8:42 am, "James Mills" <[EMAIL PROTECTED]> wrote:
> On Mon, Sep 8, 2008 at 8:37 AM, John Machin <[EMAIL PROTECTED]> wrote:

> > There seems to be an implicit assumption in the answers so far that
> > your mapping is a 1:1 mapping of all possible input keys.
>
> > If it doesn't include all possible input keys, answers will crash with
> > a KeyError. If there are any many:1 elements in the mapping (for
> > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> > in some checks for this.
>
> You are quite right! But then he/she didn't
> ask for this right ? :)
>

What do you mean by "this right"? Perhaps the Divine Right of OPs,
managers, examiners, business analysts, etc never to give a complete
spec up front and never to contemplate the consequences of Murphy's
Law?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and M2Crypto question

2008-09-07 Thread Graham Dumpleton
On Sep 7, 11:07 pm, Bojan Mihelac <[EMAIL PROTECTED]> wrote:
> Hi all!
>
> I am trying to install M2Crypto to work on OSX10.5 apache
> (mod_python). Error I receive:
>
> Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-
> macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image
> found.  Did find:
>         /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg-
> tmp/M2Crypto/__m2crypto.so: no matching architecture in universal
> wrapper
>
> I guess that have to do something with x64 architecture but I am
> stucked and not able to find a way and to make this work. M2Crypto lib
> works good stand alone.

See:

  
http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Code_For_Architecture

This is mod_wsgi documentation, but same issue applies to mod_python.

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


Re: Updating python dictionary

2008-09-07 Thread Steven D'Aprano
On Sun, 07 Sep 2008 15:59:52 -0700, John Machin wrote:

> On Sep 8, 8:42 am, "James Mills" <[EMAIL PROTECTED]> wrote:
>> On Mon, Sep 8, 2008 at 8:37 AM, John Machin <[EMAIL PROTECTED]>
>> wrote:
> 
>> > There seems to be an implicit assumption in the answers so far that
>> > your mapping is a 1:1 mapping of all possible input keys.
>>
>> > If it doesn't include all possible input keys, answers will crash
>> > with a KeyError. If there are any many:1 elements in the mapping (for
>> > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
>> > in some checks for this.
>>
>> You are quite right! But then he/she didn't ask for this right ? :)
>>
>>
> What do you mean by "this right"? Perhaps the Divine Right of OPs,
> managers, examiners, business analysts, etc never to give a complete
> spec up front and never to contemplate the consequences of Murphy's Law?


I *think* that what James Mills meant was:

"But then he/she didn't ask for this comma right?"



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

Re: Updating python dictionary

2008-09-07 Thread James Mills
On Mon, Sep 8, 2008 at 8:59 AM, John Machin <[EMAIL PROTECTED]> wrote:
> What do you mean by "this right"? Perhaps the Divine Right of OPs,
> managers, examiners, business analysts, etc never to give a complete
> spec up front and never to contemplate the consequences of Murphy's
> Law?

Now you're being silly.

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread castironpi
On Sep 7, 5:45 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote:
> > Hi,
>
> > This is the strangest post I've seen
> > since I've joined this list (only
> > recently). What the ?
>
> Oh don't mind castironpi, many people think he's an IRC bot with some
> experimental AI features that escaped onto Usenet *grins*. If you think
> that post of his was strange, you haven't seen anything yet. Many people
> have kill-filed him, and never even see his posts.
>
> A word to castironpi: you just suggested you will pester the list to get
> a response. It's behaviour like that which gets you kill-filed. If you
> would spend one tenth of the effort that you spend on understand Python
> on understanding human psychology, you will probably get on with others
> much better and find fewer people claiming you're a bot.
>
> Even if you yourself don't understand how others behave and expect you to
> behave, think of it as an intellectual puzzle: how can I fool the strange
> hairless apes into accepting me into their herd?
>
> --
> Steven

First, gauge their persistence tolerance.  Some people are not
persistent enough.  I don't want to annoy you, and I want to show
interest, but of course no more than I actually feel.  Are my
standards too low, or too high?

Second, debate the reverse psychology tack.  Claim I'm a bot to shake
their belief?  Or call them bots?  Perhaps they are.  Bots with
cooties.  Yes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread Paul Boddie
On 7 Sep, 23:00, castironpi <[EMAIL PROTECTED]> wrote:
> I am concerned by the lack of follow-through on some responses to
> recent ideas I have described.  Do I merely have a wrong understanding
> of group policy?

I think some people have taken exception to your contributions
previously, which I believe exhibits a certain degree of
shortsightedness on their part, considering for example the recent
thread which brought up just-in-time compilation techniques where
there were pretty valid reasons for keeping the thread going.
Certainly, it wasn't as if the level of discussion was stuck at basic
contradiction or mudslinging, and even if reading the different papers
on the topic might help an inquirer on the matter, there's certainly
nothing wrong with seeking guidance over which papers might be the
best ones, nor with seeking some kind of context for that work within
the realm of Python implementations, especially given the recent glut
of news on virtual machine improvements for other dynamic languages.

>   Is it a good policy (defined with respect to the
> future of Python and the welfare of humans at large) if so?  Is there
> a serious lack of diligence, or should I merely take more initiative,
> and ignore charges of 'pestering'?  (Warning, moderately deep outside
> social issues on table too.)

I'm no expert on getting other people to embrace ideas, but here's my
advice anyway. If you have an idea and can describe it coherently,
please do so; this won't guarantee positive responses, but there may
be people out there who feel that you're onto something. If the idea
has merit - generally, the most reliable way to know involves you
personally experiencing difficulties in a problem area where the idea
in question promises to alleviate some of those difficulties - then by
developing that idea, typically producing something that others can
try out, people will know that you mean business. Alternatively,
people might point you to existing work that will address the problems
you're having, saving you the bother of having to write a load of code
to enact that idea of yours.

You can be lucky and have people chasing you down over what you've
produced, but I'd argue that most of the time, for any given idea
which becomes a project, you'll have a few people interested in what
you've done, but the motivation for continuing will be something that
will depend on yourself and your own needs. You have to accept that
even if you think that people (and Python) might be well served in
listening to what you have to say, that message may go unheard.

Once upon a time, the BDFL and the most central core developers used
to read comp.lang.python and ideas about Python's future were
exchanged readily. Today, all lobbying takes place on the python-dev/
3000/ideas mailing lists, but those lists are more conservative with
regard to contributions than comp.lang.python (python-list). Perhaps
as a consequence, the divide between those steering the language and
those using it has grown: "producers" use the aforementioned lists,
"consumers" argue with each other on the newsgroup, and it might be in
the release notes that you learn about happenings that previously
would have been reported more widely elsewhere. Certainly, influencing
the future of Python, at least officially, is a lot more hard work
than it used to be.

One may decide to worry about this, along with matters like how Python
will remain able to compete with other languages and platforms. I
regard the future development of Python as a process which may not
necessarily serve my interests, but since the community around Python
is so much larger and more diverse than those following every last
Python 3.0 commit, I see no need to become agitated by the direction
of the language developers. Since Python is Free Software one has,
after all, a lot of flexibility when deciding who to associate with
and who to influence, and it is ultimately only through trying to
achieve things with the technology that one's priorities (or the
things one should be worrying about) emerge. For me, then, influencing
Python 3.x isn't a priority since I have enough to be thinking about
and working on, and I wonder if I'll ever do anything with Python 3.x
anyway.

So, I suppose, the message is this: follow your own interests, make
contributions in the ways that make sense to you, seek contact with
like-minded developers in groups which might be remote from mainstream
Python development (find an appropriate, potentially specialised
audience); these things will define any need you may have to influence
others.

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


Re: max(), sum(), next()

2008-09-07 Thread Mensanator
On Sep 7, 3:13�pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator <[EMAIL PROTECTED]> escribi�:
>
>
>
> > Actualy, I already get the behaviour I want. sum([1,None])
> > throws an exception. I don't see why sum([]) doesn't throw
> > an exception also (I understand that behaviour is by design,
> > I'm merely pointing out that the design doesn't cover every
> > situation).
> [...]
> > Exactly. That's why I would prefer sum([]) to raise an
> > exception instead of giving a false positive.
>
> The built in behavior can't be good for every usage. Nobody prevents you from 
> defining yoru own function tailored to your own specs, like this:
>
> def strict_sum(items):
> � � items = iter(items)
> � � try:
> � � � � first = items.next()
> � � except StopIteration:
> � � � � raise ValueError, "strict_sum with empty argument"
> � � return sum(items, first)
>
> Tweak as needed. Based on other posts I believe your Python skills are enough 
> to write it on your own, so I don't see why you're complaining so hard about 
> the current behavior.

I'm not complaining about the behaviour anymore, I just don't like
being told I'm wrong when I'm not.

But I think I've made my point, so there's no point in harping on
this anymore.

>
> --
> Gabriel Genellina

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

Re: lacking follow-through

2008-09-07 Thread MRAB
On Sep 7, 11:28 pm, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> +1 Bot

I think it's like duck typing: it doesn't matter whether he's actually
a bot, only whether he behaves like one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-07 Thread Mensanator
On Sep 7, 1:17�pm, Patrick Maupin <[EMAIL PROTECTED]> wrote:
> On Sep 7, 12:30�pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > On Sep 6, 11:05 pm, Steven D'Aprano <[EMAIL PROTECTED]
> > > Sheesh. That's not a problem, because Python is not trying to be a
> > > dialect of SQL.
>
> > And yet, they added a Sqlite3 module.
>
> Does that mean that, because there is an 'os' module, Python is trying
> to compete with Linux and Windows?

I wasn't thinking "compete", rather "complement". Python obviously
wants to be a player in the SQL market, so you would think it
would be in Python's interest to know how SQL behaves, just as it's in
Python's interest for the os module to know how BOTH Linnux and
Windows work.

>
> This is starting to feel like a troll,

It wasn't intended to be.

> but JUST IN CASE you are really
> serious about wanting to get work done with Python, rather than
> complaining about how it is not perfect,

Things never change if no one ever speaks up.

> I offer the following snippet
> which will show you how you can test the results of a sum() to see if
> there were any items in the list:

Thanks. I'll drop this from this point on.

>
> >>> class MyZero(int):
>
> ... � � pass
> ...
>
>
>
> >>> zero = MyZero()
> >>> x=sum([], zero)
> >>> isinstance(x,MyZero)
> True
> >>> x = sum([1,2,3], zero)
> >>> isinstance(x,MyZero)
> False- Hide quoted text -
>
> - Show quoted text -

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

Re: Updating python dictionary

2008-09-07 Thread MK Bernard
On Sep 7, 3:37 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 8, 7:51 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello...
>
> > I have a dict of key/values and I want to change the keys in it, based
> > on another mapping dictionary. An example follows:
>
> > MAPPING_DICT = {
> >     'a': 'A',
> >     'b': 'B',
>
> > }
>
> > my_dict = {
> >     'a': '1',
> >     'b': '2'
>
> > }
>
> > I want the finished my_dict to look like:
>
> > my_dict = {
> >     'A': '1',
> >     'B': '2'
>
> > }
>
> > Whereby the keys in the original my_dict have been swapped out for the
> > keys mapped in MAPPING_DICT.
>
> > Is there a clever way to do this, or should I loop through both,
> > essentially creating a brand new dict?
>
> Is this homework?
>
> There seems to be an implicit assumption in the answers so far that
> your mapping is a 1:1 mapping of all possible input keys.
>
> If it doesn't include all possible input keys, answers will crash with
> a KeyError. If there are any many:1 elements in the mapping (for
> example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> in some checks for this.

Thats exactly why I did an explicit check in my post, so as to make
sure that such a collision could not occur. It would seem that
something along what I posted would be safer, if less elegant, than
the others.
Cheers, MK
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-07 Thread Mensanator
On Sep 7, 2:17�pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 7 Sep 2008 10:30:09 -0700 (PDT), Mensanator <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> > On Sep 6, 11:05?pm, Steven D'Aprano <[EMAIL PROTECTED]
> > cybersource.com.au> wrote:
>
> > > Sheesh. That's not a problem, because Python is not trying to be a
> > > dialect of SQL.
>
> > And yet, they added a Sqlite3 module.
>
> � � � � Which is an interface TO an embedded/stand-alone SQL-based RDBM
> engine; it does not turn Python into a dialect of SQL -- Python does not
> process the SQL, it gets passed to the engine for SQL data processing.

But that's only half the story. The other half is data returned
as a result of SQL queries. And that's something Python DOES process.
And sometimes that processed data has to be inserted back into the
database. We certainly don't want Python to process the data in a way
that the database doesn't expect.

When I see a potential flaw (such as summing an empty list to 0),
should I just keep quiet about it, or let everyone know?

Well, now they know, so I'll shut up about this from now on, ok?

> --
> � � � � Wulfraed � � � �Dennis Lee Bieber � � � � � � � KD6MOG
> � � � � [EMAIL PROTECTED] � � � � � � [EMAIL PROTECTED]
> � � � � � � � � HTTP://wlfraed.home.netcom.com/
> � � � � (Bestiaria Support Staff: � � � � � � � [EMAIL PROTECTED])
> � � � � � � � � HTTP://www.bestiaria.com/

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

Re: Read and write binary data

2008-09-07 Thread Patrick Maupin
On Sep 7, 5:41 pm, Mars creature <[EMAIL PROTECTED]> wrote:
> Hi guys,
>   I am new to Python, and thinking about migrating to it from matlab
> as it is a really cool language. Right now, I am trying to figure out
> how to control read and write binary data, like
> 'formatted','stream','big-endian','little-edian' etc.. as in fortran.
> I googled, but can not find a clear answer. Anyone has clue where can
> I learn it? Thanks!!
> Jinbo

Start by looking at the array module.

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


Re: lacking follow-through

2008-09-07 Thread Ben Finney
Paul Boddie <[EMAIL PROTECTED]> writes:

> On 7 Sep, 23:00, castironpi <[EMAIL PROTECTED]> wrote:
> > I am concerned by the lack of follow-through on some responses to
> > recent ideas I have described. Do I merely have a wrong
> > understanding of group policy?
> 
> I think some people have taken exception to your contributions
> previously, which I believe exhibits a certain degree of
> shortsightedness on their part
[…]

For my part, I find those posts a mammoth waste of my time, since
they're shrouded in language so difficult to parse that I can't see
what they're supposed to be saying in a reasonable amount of time.

So, I consider it more valuable to never see those posts; if someone
else can find a gem of wisdom in any of them that's significantly
valuable, presumably I'll find out by some other means than attempting
to read those posts myself.

This is not intended as any kind of offense to the author, nor to
anyone not fluent in written English; it's merely a choice I make as
to how I will spend my time.

-- 
 \ “No wonder I'm all confused; one of my parents was a woman, the |
  `\ other was a man.” —Ashleigh Brilliant |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Use BeautifulSoup to delete certain tag while keeping its content

2008-09-07 Thread John Nagle

Jackie Wang wrote:

Dear all,

I have the following html code:


 
  Center Bank
  
  Los Angeles, CA
 



 
  Salisbury
Bank and Trust Company
  
   
   Lakeville, CT
  
 


How should I delete the 'font' tags while keeping the content inside?


See the BeautifulSoup documentation.  Find the font tags with findAll,
make a list, then go in and use "extract" and "replaceWith" appropriately.

John Nagle

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


Re: lacking follow-through

2008-09-07 Thread castironpi
On Sep 7, 7:34 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Sep 7, 11:28 pm, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
>
> > +1 Bot
>
> I think it's like duck typing: it doesn't matter whether he's actually
> a bot, only whether he behaves like one.

Do you support the bot interface and methods?
--
http://mail.python.org/mailman/listinfo/python-list


Subprocess freezes when piping from stdout.

2008-09-07 Thread James McGill
Hi All,

I'm using subprocess.Popen to run a C++ compiler and have set stdout =
PIPE. The exact line of code that I am using is:

process = Popen(command, stdout=PIPE)
status = process.wait()

This works fine until a large amount of data is written to stdout.
When this occurs, my python program seems to freeze. It will no longer
run or respond to Ctrl-C. I am assuming that it is stuck waiting for
the process to end, but I'm not sure why this should take so long (I
have left it running for hours and it never ended)

At the moment the code is being executed on a Win32 environment.

Is anyone aware of why this might be occurring, or of any ways around
this? Does the PIPE implementation in Win32 have a maximum buffer
size?

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


Re: Not fully understanding the role of Queue.task_done()

2008-09-07 Thread alex23
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> (btw, I've always thought that Python was all about making it easy to
> express the solution to a given problem in code, not to let you write
> programs without using your brain.  when did that change?)

The day Google App Engine was opened up to developers, I believe.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Subprocess freezes when piping from stdout.

2008-09-07 Thread Fredrik Lundh

James McGill wrote:


Is anyone aware of why this might be occurring, or of any ways around
this? Does the PIPE implementation in Win32 have a maximum buffer
size?


pipes always have a limited buffer size, on all platforms.  you're 
supposed to read data from them as it arrives (e.g. by explicitly 
reading from the "stdout" attribute, or by calling "communicate").


if you cannot do that, bind the channel to a file, not a pipe.



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


Re: lacking follow-through

2008-09-07 Thread Asun Friere
On Sep 8, 7:00 am, castironpi <[EMAIL PROTECTED]> wrote:
> I am concerned by the lack of follow-through on some responses to
> recent ideas I have described.  Do I merely have a wrong understanding
> of group policy?

[snip]

Perhaps the wrong idea of what the group is.  I would have thought
that
if one had a sufficiently developed idea and wanted to have it /
formally/
rejected, rather than merely sniped at, then writting a PEP would be
more
apposite than posting to c.l.py.

It's fine to post your not sufficiently developed ideas here merely
to
have them discussed.  But I don't know what makes you feel that you,
or
your ideas, are /entitled/ to any response at all, much less
"follow-through."
--
http://mail.python.org/mailman/listinfo/python-list


Spotlight Searching in Python - Mac OSX

2008-09-07 Thread cjstevens
Hi all, I'm having some issues getting a spotlight search to work
similar to the program demonstrated here:
http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/


Here is my class, complete with the code I am trying to use it with at
the end.


import objc, sys, os, osax, time
from Foundation import *
from ScriptingBridge import *
from appscript import *


class SystemBridge(NSObject):
"""Class to use the scripting bridge to interact with the system"""
_hideapp = objc.ivar(u"hideapp")
_volume = objc.ivar(u"volume")
_filename = objc.ivar(u"filename")
_filetype = objc.ivar(u"filetype")
_auth = objc.ivar(u"auth")
_logout = objc.ivar(u"logout")
query = objc.ivar(u"query")
StdAdditions = osax.ScriptingAddition()

def init(self):
super(SystemBridge, self).init()
# create and initalize our query
self.query = NSMetadataQuery.alloc().init()

# setup our Spotlight notifications
nf = NSNotificationCenter.defaultCenter()
nf.addObserver_selector_name_object_(self,
'queryNotification:', None, self.query)



# XXX: this framework isn't wrapped yet!
 
self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName',
True)])
self.query.setDelegate_(self)



return self

def hideApplication_(self, _hideapp):
app(u'System Events').processes[_hideapp].visible.set(False)

def loadResultsFromQuery_(self, notif):
results = notif.object().results()

NSLog("search count = %d", len(results))

# iterate through the array of results, and match to the
existing stores
for item in results:
nameStr = item.valueForAttribute_('kMDItemDisplayName')
print nameStr


def queryNotification_(self, note):
# the NSMetadataQuery will send back a note when updates are
happening.
# By looking at the [note name], we can tell what is happening
if note.name() ==
NSMetadataQueryDidStartGatheringNotification:
# the query has just started
NSLog("search: started gathering")


elif note.name() ==
NSMetadataQueryDidFinishGatheringNotification:
# at this point, the query will be done. You may recieve
an update
# later on.
NSLog("search: finished gathering");
self.loadResultsFromQuery_(note)

elif note.name() ==
NSMetadataQueryGatheringProgressNotification:
# the query is still gathering results...
NSLog("search: progressing...")

elif note.name() == NSMetadataQueryDidUpdateNotification:
# an update will happen when Spotlight notices that a file
as
# added, removed, or modified that affected the search
results.
NSLog("search: an update happened.")


def spotlightFriendlyPredicate_(self, predicate):
if predicate == NSPredicate.predicateWithValue_(True) or
predicate == NSPredicate.predicateWithValue_(False):
return False

elif isinstance(predicate, NSCompoundPredicate):

type = predicate.compoundPredicateType()
cleanSubpredicates = []
for dirtySubpredicate in predicate.subpredicates():
cleanSubpredicate =
self.spotlightFriendlyPredicate_(
dirtySubpredicate)
if cleanSubpredicate:

cleanSubpredicates.append(cleanSubpredicate)

if len(cleanSubpredicates) == 0:
return None

else:
if len(cleanSubpredicates) == 1 and type !=
NSNotPredicateType:
return cleanSubpredicates[0]

else:
return
NSCompoundPredicate.alloc().initWithType_subpredicates_(type,
cleanSubpredicates)

else:
return predicate

def createNewSearchForPredicate_(self, predicate):

# Format search file type
thePredicate = NSPredicate.predicateWithFormat_(
"(kMDItemContentType =
'com.apple.iwork.keynote.key')")
tempPredicate = NSPredicate.predicateWithFormat_(
"(kMDItemDisplayName IN[c] 'preso')")
predicate = NSCompoundPredicate.andPredicateWithSubpredicates_(
[thePredicate, tempPredicate])


self.query.setPre

firefox timestamp

2008-09-07 Thread abhilash pp
Hi all,
I don't know if this question will fit on this section,
any way my query is , i have used one script demork.py to extract details
from Firefox history.dat file
and now the problem is how to convert the TIMESTAMP given by that to normal
date and time.
example timestams are like this,

1202919771609375
1213874676203125
1215693263859375

i have used datetime module for this but it gave me error

>>> import datetime
>>> datetime.datetime.fromtimestamp(1215693263859375)

Traceback (most recent call last):
  File "", line 1, in 
datetime.datetime.fromtimestamp(1215693263859375)
ValueError: timestamp out of range for platform time_t


please help me to convert this ?
--
http://mail.python.org/mailman/listinfo/python-list