Re: importing modules question

2007-10-18 Thread Amit Khemka
On 10/18/07, warhero <[EMAIL PROTECTED]> wrote:
> 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

'import module' statement imports the 'module' object and binds the
name to the local namespace. Any names defined in the module will have
to referenced by module.module_object

so you need to do something like this:
import loadee
if __name__ == "__main__":
 l = loadee.loadee()

Alternatively you can directly import the objects defined in a module by :

from loadee import loadee
if __name__ == "__main__":
 l = loadee()

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


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

2007-10-18 Thread Gerard Flanagan
On Oct 18, 1:55 am, Debajit Adhikary <[EMAIL PROTECTED]> 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?
>


from itertools import izip

def toggle(start=True):
flag = start
while 1:
flag = not flag
yield flag


CSS = ("even", "odd")

HTML = '%d%s'

result = [(1, 'One'), (2, 'two'), (3, 'Three'), (4, 'Four'), (5,
'Five')]

for flag, (id, name) in izip(toggle(), result):
print HTML % (CSS[flag], id, name)


1One
2two
3Three
4Four
5Five

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


Re: A near realtime file system mirror application written in Python

2007-10-18 Thread Roc Zhou
mirrord/fs_mirror makes use of inotify, which is a functionality afforded
by the recent Linux (from 2.6.12). It is a counterpart of FAM, since Linux
FAM has stopped so long.

On 10/17/07, Roc Zhou <[EMAIL PROTECTED]> wrote:
>
> Hello:
>
> Recently I started an open source project "cutils" on the
> sourceforge:
> https://sourceforge.net/projects/crablfs/
>
> The document can be found at:
> http://crablfs.sourceforge.net/#ru_data_man
>
> This project's mirrord/fs_mirror is a near realtime file system
> mirroring application across 2 or more hosts, now it can work
> for me.
>
> I hope this tool can be useful to you.
>
> Thank you.
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-18 Thread Paul Hankin
On Oct 17, 11:45 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> [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.

Perhaps, but I think you'll need a better use-case than this :)

Actually, would a c-version be much faster?

--
Paul Hankin

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


Re: Stopping a fucntion from printing its output on screen

2007-10-18 Thread Paul Hankin
On Oct 17, 3:57 pm, sophie_newbie <[EMAIL PROTECTED]> 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?

Yes, in your functions that you may or may not want to print stuff,
declare them with a stream parameter that defaults to stdout.

For example:

import sys

def f(i, out = sys.stdout)
   # Do something...
   print >>out, "i is %d" % i

Then usually, you call
f(10)

But when you want to elide the output, use Jeremy's nullwriter:
class NullWriter(object):
def write(self, arg):
pass
nullwriter = NullWriter()

f(10, out = nullwriter)

Having the output stream explicit like this is much better style than
abusing sys.stdout, and it won't go wrong when errors occur. It's the
same idea as avoiding global variables.

--
Paul Hankin

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


[OT] PLEASE HELP US

2007-10-18 Thread Albert77
Hello,
my name is Albert and I'm looking for help.
Please visit my web page.
www.willmarry.net

Thanks

Albert

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


MOD_PYTHON + packages reloading

2007-10-18 Thread lukasz . f24
Hello,

I came across annoying problem during my fun with mod_python. I turned
out that mod_python load package only onca and don't care about any
changes to it. Obviously it makes sense on production server but
during development is more then annoying. I find a way to reload my
module:

m = apache.import_module(name)
reload(m)

But this solution doesn't satisfy my. Is there any way to use old good
import x.x.x or from x.x.x import y and somehow set mod_python to
autoreload packages? apache.import_module(name,autoreload=1) didn't
work.
What is more interesting if a file is in the same directory (no in the
package) i don't need to wory about reloading, python doesn't cache
it.

Please help me :)

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


Re: ANN: magnitude 0.9.1

2007-10-18 Thread Joan M. Garcia
George Sakkis <[EMAIL PROTECTED]> writes:
> On Oct 16, 7:35 am, Laurent Pointal <[EMAIL PROTECTED]> >
>> How does it compare to the scalar module ?
>> (seehttp://russp.us/scalar.htm)
>
> or the Unum module (http://home.scarlet.be/be052320/Unum.html) ?

Both scalar and unum treat units as variables.  You are
supposed to import them, so you end up with variables like M
and S in your namespace.  And they don't seem to be able to
understand prefixes as they combine with variable names.

On the other side, they both provide something that
magnitude does not have: the ability to define arbitrary
units.  magnitude limits you to combinations of the standard
SI units, plus dollar and bit.  It is trivial to implement
user generation of arbitrary names for these combinations,
but not of arbitrary independent units.

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


Re: ANN: magnitude 0.9.1

2007-10-18 Thread juan
> A further issue, that requires a change of interface: Please comply
> with PEP 8 http://www.python.org/dev/peps/pep-0008/> for your
> module interface. In particular, please name classes with TitleCase,
> and functions, methods, and instance names with
> lower_case.

Done, almost.  I should have seen that document before.  I
think magnitude is compliant now, both in its API and its
innards.  The only thing missing is to raise objects instead
of strings.

> Also: "precision" is the correct spelling of that word.

Now that's embarrassing.  Thanks.

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


ANN: magnitude 0.9.2

2007-10-18 Thread Joan M. Garcia
Following the feedback on the first release of magnitude it
has changed enough to deserve a second release, which
modifies the API, solves a couple of bugs, and brings it in
line with python's style guide.  Main changes:

* imul, idiv had wrong output unit, so that after a /= b
  printing showed wrong units. 

* mod's output has the units of the division. 

* outputPrecission, defaultFormat and outputUnits are now
  output_precision, default_format and output_units.


Magnitude:

A physical quantity is a number with a unit, like 10
km/h. Units can be any of the SI units, plus a bunch of
non-SI, bits, dollars, and any combination of them. They can
include the standard SI prefixes. Magnitude can operate with
physical quantities, parse their units, and print them. You
don't have to worry about unit consistency or conversions;
everything is handled transparently. By default output is
done in basic SI units, but you can specify any output unit,
as long as it can be reduced to the basic units of the
phisical quantity.

Home page: http://juanreyero.com/magnitude/ 

Cheers,

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


Re: Strange behaviour with reversed()

2007-10-18 Thread Steven D'Aprano
On Thu, 18 Oct 2007 02:49:12 -0300, Gabriel Genellina wrote:

> 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.

...

> 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.

You know, that's probably the *least* intuitive behaviour possible.

For reversed() to iterate over the input as it was at creation time is a 
reasonable design choice; for it to iterate over the input as it is at 
call time is also a reasonable design choice; but for it to iterate over 
some unholy mutant melding of the sequence as-it-was and as-it-is is 
simply bizarre. I hope it just fell out of the implementation and wasn't 
a deliberate design choice.


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


Re: Strange behaviour with reversed()

2007-10-18 Thread Steven D'Aprano
On Thu, 18 Oct 2007 15:24:27 +1000, Ben Finney wrote:

> 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".

That's not correct. You can modify sequences while iterating, and the 
results are often perfectly predictable (but watch out for off-by-one 
errors):

>>> L = range(5)
>>> for item in L: # iterate over half of L
... print item, "- deleting last item =", L[-1]
... del L[-1]
...
0 - deleting last item = 4
1 - deleting last item = 3
2 - deleting last item = 2


(BTW, I'm not implying that the above is good practice. Far from it.)

The result of modifying sequences while you iterate over them is often -- 
not always -- hard to predict, but it is rarely indeterminate or 
undefined.

enumerate(), for example, iterates over the input sequence *as it is* at 
call time, not creation time. The result of modifying the sequence is 
well defined, but not necessarily what you want. For an exercise in 
Sorcerer's Apprentice, try this:

L = range(10)
for i, x in enumerate(L):
print i, x
L.append("another!")

Remember, ctrl-C to interrupt Python.


But even if it is undefined in the case of reversed(), there should be 
some sort of note in the docs. By analogy with sorted(), reversed() looks 
like it should make a copy. And if not, it looks like it should iterate 
over the input sequence as it exists when called. In fact, it does a 
little of both.


> 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.

By analogy with sorted(), reversed() looks like it should be iterating 
over a copy. In any case, it isn't clear from the docs that reversed() is 
actually a type of view. I like views, it's just that I like to know when 
I'm working with one.


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


Re: MOD_PYTHON + packages reloading

2007-10-18 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> I came across annoying problem during my fun with mod_python. I turned
> out that mod_python load package only onca and don't care about any
> changes to it. Obviously it makes sense on production server but
> during development is more then annoying.

Have you read the mod_python manual?

http://www.modpython.org/live/current/doc-html/dir-other-par.html

5.4.8 PythonAutoReload

Syntax: PythonAutoReload {On, Off}
Default: PythonAutoReload On
Context: server config, virtual host, directory, htaccess
Override: not None
Module: mod_python.c

If set to Off, instructs mod_python not to check the modification date 
of the module file.

By default, mod_python checks the time-stamp of the file and reloads the 
module if the module's file modification date is later than the last 
import or reload. This way changed modules get automatically reimported, 
eliminating the need to restart the server for every change.

Disabling autoreload is useful in production environment where the 
modules do not change; it will save some processing time and give a 
small performance gain. 

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


Re: if instance exists problem ..

2007-10-18 Thread Diez B. Roggisch
Ben Finney wrote:

> "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.

I've misread the post entirely, so just... discard my message :)

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


Re: Strange behaviour with reversed()

2007-10-18 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>> 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.
> 
> You know, that's probably the *least* intuitive behaviour possible.
> 
> For reversed() to iterate over the input as it was at creation time is 
a 
> reasonable design choice; for it to iterate over the input as it is at 
> call time is also a reasonable design choice; but for it to iterate 
over 
> some unholy mutant melding of the sequence as-it-was and as-it-is is 
> simply bizarre. I hope it just fell out of the implementation and 
wasn't 
> a deliberate design choice.

You mean that you don't find it intuitive that it iterates through the 
indices that existed at creation time and returns the values as they are 
now? I'd have said that was the *most* intuitive behaviour.

The only other behaviours I would regard as intuitive for iteration over 
a mutating sequence would be to throw an exception either for mutating 
the sequence while the iterator exists or for using the iterator after a 
mutation.

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


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

2007-10-18 Thread Hrvoje Niksic
Paul Hankin <[EMAIL PROTECTED]> writes:

> 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.

Why?  a.extend(b) is at least as readable, and is guaranteed to extend
the same list.  In general, "a += b" can fall back to the slower "a =
a + b" for sequences that don't support +=.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Order by value in dictionary

2007-10-18 Thread Duncan Booth
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> Without throwing away 500 items:
> 
> def sortt(d):
> sorted_items = sorted(d.iteritems(),
>   key=operator.itemgetter(1),
>   reverse=True)
> return map(operator.itemgetter(0), sorted_items)

Isn't that just equivalent to:

def sortt(d):
return sorted(d.iterkeys(), key=d.__getitem__,
 reverse=True)

which has the advantage of not building a list of tuples just to throw it 
away?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MOD_PYTHON + packages reloading

2007-10-18 Thread lukasz . f24
On 18 Oct, 09:55, Duncan Booth <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I came across annoying problem during my fun with mod_python. I turned
> > out that mod_python load package only onca and don't care about any
> > changes to it. Obviously it makes sense on production server but
> > during development is more then annoying.
>
> Have you read the mod_python manual?
>
> http://www.modpython.org/live/current/doc-html/dir-other-par.html
>
> 5.4.8 PythonAutoReload
>
> Syntax: PythonAutoReload {On, Off}
> Default: PythonAutoReload On
> Context: server config, virtual host, directory, htaccess
> Override: not None
> Module: mod_python.c
>
> If set to Off, instructs mod_python not to check the modification date
> of the module file.
>
> By default, mod_python checks the time-stamp of the file and reloads the
> module if the module's file modification date is later than the last
> import or reload. This way changed modules get automatically reimported,
> eliminating the need to restart the server for every change.
>
> Disabling autoreload is useful in production environment where the
> modules do not change; it will save some processing time and give a
> small performance gain.

Yes I have read it. This is my config file

ServerName info
DocumentRoot D:/web/info/

  AddHandler mod_python .py
  PythonHandler index
  PythonDebug On
  PythonAutoReload On
  AllowOverride All
  Allow from All
  AllowOverride All



Even when autoreload is ON mod_python doesn't care about any changes
if I import something from package in traditional way :(

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


Re: Problem of Readability of Python

2007-10-18 Thread Marc 'BlackJack' Rintsch
On Wed, 17 Oct 2007 15:01:09 -0700, kiilerix wrote:

> 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.

I'm using the following "dummy" class with a little extra functionality:

def Bunch(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

person = Bunch(name='Eric', age=42)
print person.name
point = Bunch(x=4711, y=23)

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


Re: MOD_PYTHON + packages reloading

2007-10-18 Thread Graham Dumpleton
On Oct 18, 6:55 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I came across annoying problem during my fun with mod_python. I turned
> > out that mod_python load package only onca and don't care about any
> > changes to it. Obviously it makes sense on production server but
> > during development is more then annoying.
>
> Have you read the mod_python manual?
>
> http://www.modpython.org/live/current/doc-html/dir-other-par.html
>
> 5.4.8 PythonAutoReload
>
> Syntax: PythonAutoReload {On, Off}
> Default: PythonAutoReload On
> Context: server config, virtual host, directory, htaccess
> Override: not None
> Module: mod_python.c
>
> If set to Off, instructs mod_python not to check the modification date
> of the module file.
>
> By default, mod_python checks the time-stamp of the file and reloads the
> module if the module's file modification date is later than the last
> import or reload. This way changed modules get automatically reimported,
> eliminating the need to restart the server for every change.
>
> Disabling autoreload is useful in production environment where the
> modules do not change; it will save some processing time and give a
> small performance gain.

Have you read the other document:

  http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html

In particular read the documentation for the import_module() function.
It clearly describes in what limited cases module reloading is
performed. It does not do it for all modules as many mistakenly
believe. It does not do any form of module reloading on Python
packages because it is impossible to do properly due to the fact that
cyclic dependencies can occur with how packages are generally
structured.

For a description of some of the issues and why mod_python 3.3 works
like it does, see the big list of problems related to module reloading
in older versions of mod_python:

  http://www.dscpl.com.au/wiki/ModPython/Articles/ModuleImportingIsBroken

So, what is in 3.3 as described in documentation for import_module()
is as good as it gets. As long as you work within the constraints it
imposes you can go a long way, but don't expect miracles.

Graham

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


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

2007-10-18 Thread Amit Khemka
On 10/18/07, Carsten Haese <[EMAIL PROTECTED]> wrote:
> 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.
>

Why not just use enumerate ?

clvalues = ["Even", "Odd"]
for i, (id, name) in enumerate(result):
stringBuffer.write('''

   %d
   %s
 
 '''
%
(clvalues[i % 2], id, name))

Cheers,

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


Re: Script to Download Ubuntu Gutsy ASAP

2007-10-18 Thread Eduardo O. Padoan
On 10/18/07, danfolkes <[EMAIL PROTECTED]> wrote:
> 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,

Please, don't do it. Use the torrent, Luke.
Also, use the HTTP error code - while the file is not at the server,
you will receive a 404, I think.

-- 
http://www.advogato.org/person/eopadoan/
Bookmarks: http://del.icio.us/edcrypt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: magnitude 0.9.2

2007-10-18 Thread Thomas Heller
Joan M. Garcia schrieb:
> Following the feedback on the first release of magnitude it
> has changed enough to deserve a second release, which
> modifies the API, solves a couple of bugs, and brings it in
> line with python's style guide.  Main changes:
> 
> * imul, idiv had wrong output unit, so that after a /= b
>   printing showed wrong units. 
> 
> * mod's output has the units of the division. 
> 
> * outputPrecission, defaultFormat and outputUnits are now
>   output_precision, default_format and output_units.
> 
> 
> Magnitude:
> 
> A physical quantity is a number with a unit, like 10
> km/h. Units can be any of the SI units, plus a bunch of
> non-SI, bits, dollars, and any combination of them. They can
> include the standard SI prefixes. Magnitude can operate with
> physical quantities, parse their units, and print them. You
> don't have to worry about unit consistency or conversions;
> everything is handled transparently. By default output is
> done in basic SI units, but you can specify any output unit,
> as long as it can be reduced to the basic units of the
> phisical quantity.
> 
> Home page: http://juanreyero.com/magnitude/ 

Three comments, from looking at it:

- "physical", not "phisical" ;-)

- you raise string exceptions in various places; these are deprecated and
  should not be used.  Also it is very difficult to catch them.

- ScientificPython from Konrad Hinsen also contains a somewhat similar
  module.  IIRC, it is named PhysicalQuantities.  You might look into that
  and mention it on the homepage.

Thomas

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


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

2007-10-18 Thread Paul Hankin
On Oct 18, 12:11 pm, "Amit Khemka" <[EMAIL PROTECTED]> wrote:
> On 10/18/07, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > Rather than spelling out the final result, I'll give you hints: Look at
> > itertools.cycle and itertools.izip.
>
> Why not just use enumerate ?
>
> clvalues = ["Even", "Odd"]
> for i, (id, name) in enumerate(result):
> stringBuffer.write('''
> 
>%d
>%s
>  
>  '''
> %
> (clvalues[i % 2], id, name))

I like this code: straightforward and pragmatic. Everyone else seems
to be reinventing itertools.cycle - they should have listened to
Carsten, and written something like this:

import itertools

clvalues = itertools.cycle(['Even', 'Odd'])
for clvalue, (id, name) in itertools.izip(clvalues, result):
 stringBuffer.write('''
 
%(id)d
%(clvalue)s
 ''' % locals())

--
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-18 Thread Paul Hankin
On Oct 18, 10:21 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Paul Hankin <[EMAIL PROTECTED]> writes:
> > 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.
>
> Why?  a.extend(b) is at least as readable, and is guaranteed to extend
> the same list.  In general, "a += b" can fall back to the slower "a =
> a + b" for sequences that don't support +=.

Not to me: I can never remember which of a.append and a.extend is
which. Falling back to a = a + b is exactly what you want. For
instance:

a = (1, 2, 3)
a += (4, 5, 6)

works, whereas:

a = (1, 2, 3)
a.extend((4, 5, 6))

doesn't. So using += makes your code more general. There's no standard
sequence type that has extend and not +=, so worrying that += is
slower isn't a concern unless you're using a user-defined class. Even
then, it's probably a mistake that should be fixed in the class rather
than requiring .extend() to be used instead of +=.

--
Paul Hankin

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


Re: Order by value in dictionary

2007-10-18 Thread Amit Khemka
On 10/17/07, Abandoned <[EMAIL PROTECTED]> wrote:
> Very very thanks everbody..
>
> These are some method..
> Now the fastest method is second..
>
>  1 ===
> def sortt(d):
> items=d.items()
> backitems=[ [v[1],v[0]] for v in items]
> backitems.sort()
> #boyut=len(backitems)
> #backitems=backitems[boyut-500:]
> a=[ backitems[i][1] for i in range(0,len(backitems))]
> a.reverse()
> return a
>
>  2 =
> import operator
> def sortt(d):
> backitems=d.items()
> boyut=len(backitems)
> backitems=backitems[boyut-500:]
> backitems=sorted(backitems, key=operator.itemgetter(1))
> a=[ backitems[i][0] for i in range(0,len(backitems))]
> a.reverse()
> return a
>
>  3 =
> def sortt(d):
> backitems=d.items()
> backitems.sort(lambda x,y:cmp(x[1],y[1]))
> backitems=sorted(backitems, key=operator.itemgetter(1))
> a=[ backitems[i][0] for i in range(0,len(backitems))]
> a.reverse()
> return a
>
> == 4 ===
> import heapq
>
> def sortt(d):
> backitems=d.items()
> backitems=heapq.nlargest(1000, backitems, operator.itemgetter(1))
> a=[ backitems[i][0] for i in range(0,len(backitems))]
> a.reverse()
> return a
>

Btw, there are specialized algorithms called "Selection Algorithms"
for finding k largest items in a collection.

http://en.wikipedia.org/wiki/Selection_algorithm

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


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

2007-10-18 Thread Bruno Desthuilliers
Debajit Adhikary a écrit :
> 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)

And what about a.extend(b) ?

> How do I do this using a list comprehension?

Why would you want a list comp here ???

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

Depends. Anyway, the pythonic solution here is to use the appropriate 
list method !-)

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


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

2007-10-18 Thread Brian Blais

On Oct 18, 2007, at Oct 18:7:47 AM, Paul Hankin wrote:


On Oct 18, 12:11 pm, "Amit Khemka" <[EMAIL PROTECTED]> wrote:

Why not just use enumerate ?

clvalues = ["Even", "Odd"]
for i, (id, name) in enumerate(result):
stringBuffer.write('''

   %d
   %s
 
 '''
%
(clvalues[i % 2], id, name))


I like this code: straightforward and pragmatic.


Although the itertools is probably the way to go here, I've used the  
following construct, especially in two-player games.  I like the  
readability of it:


value='Even'
other_value='Odd'
for i, (id,name) in enumerate(result):
stringBuffer.write('''

%d
%s

''' % (value,id,name)


value,other_value=other_value,value   # swap the value





bb

--
Brian Blais
[EMAIL PROTECTED]
http://web.bryant.edu/~bblais



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

Re: Inheriting automatic attributes initializer considered harmful?

2007-10-18 Thread Andrew Durdin
On 10/17/07, Alex Martelli <[EMAIL PROTECTED]> wrote:
>
> fake_str is not called, because special-method lookup occurs on the
> TYPE, *NOT* on the instance.

So it does; I'd forgotten that.  I need to remember to actually check
that the code does what I think it does before posting it on c.l.p
:-|

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


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

2007-10-18 Thread Grant Edwards
On 2007-10-18, Gerard Flanagan <[EMAIL PROTECTED]> wrote:
> On Oct 18, 1:55 am, Debajit Adhikary <[EMAIL PROTECTED]> 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?
>>
>
>
> from itertools import izip
>
> def toggle(start=True):
> flag = start
> while 1:
> flag = not flag
> yield flag

I like the solution somebody sent me via PM:

def toggle():
while 1:
yield "Even"
yield "Odd"

-- 
Grant Edwards   grante Yow! Are we THERE yet?
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2007-10-18 Thread Hrvoje Niksic
Paul Hankin <[EMAIL PROTECTED]> writes:

> Not to me: I can never remember which of a.append and a.extend is
> which.

Interesting, with me it's the other way around.  Maybe it's because I
used Python before extend was available.

> Falling back to a = a + b is exactly what you want.

Not if you want to mutate the original object, possibly referenced
from elsewhere.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-18 Thread Stargaming
On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote:
[snip]
> 
> 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))
> 

Note this certainly should've been `reversed()`, with a trailing 'd'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: magnitude 0.9.2

2007-10-18 Thread juan
Thomas Heller <[EMAIL PROTECTED]> writes:
> - "physical", not "phisical" ;-)

I see a worrisome pattern starting to emerge :-).  Thanks. 

> - you raise string exceptions in various places; these are
> deprecated and should not be used.  Also it is very
> difficult to catch them.

Yes, I believe it is the last big thing before I am fully
PEP8-compliant.  I'll change it and make a new release as
soon as I can. 

> - ScientificPython from Konrad Hinsen also contains a
> somewhat similar module.  IIRC, it is named
> PhysicalQuantities.

It is very similar to magnitude.  Same approach, almost the
same API. 

>  You might look into that and mention it on the homepage.

Done.  I will eventually have to stop adding references to
alternatives, but so far so good. 

jm

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


Re: Noob questions about Python

2007-10-18 Thread Bruno Desthuilliers
Stargaming a écrit :
> On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote:
> [snip]
>> 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))
>>
> 
> Note this certainly should've been `reversed()`, with a trailing 'd'.

2-0 for Stargaming. I'll have to either change glasses, buy a new 
keyboard (this one is obviously broken), or learn to both use a keyboard 
and re-read what I post.
-- 
http://mail.python.org/mailman/listinfo/python-list

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

2007-10-18 Thread dedalusenator
First off, apologies for posting code that had issues. My bad and
promise next time to do due diligence.

>learn about semaphores.

Definitely will.

>While this may not be an issue in this snippet

Even when more than one user concurrently launches this python
program? Let me read up on this like you suggested and then get back.

Thanks for all your help,
-Stephen
On Oct 17, 4:57 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> [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- Hide quoted text -
>
> - Show quoted text -


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

Re: Capturing OutputDebugString information in python

2007-10-18 Thread Tim Golden
danbrotherston wrote:
> 
> 
> Wow, more of a response than I expected, thanks very much for the
> research.  While not related to the mutex, the problem did appear to
> be permission related.  For the record, on windows XP
> 
> import sys
> import mmap
> import win32event
> 
> buffer_ready = win32event.CreateEvent (None, 0, 0,
> "DBWIN_BUFFER_READY")
> data_ready = win32event.CreateEvent (None, 0, 0, "DBWIN_DATA_READY")
> buffer = mmap.mmap (0, 4096, "DBWIN_BUFFER", mmap.ACCESS_WRITE)
> 
> 
> win32event.SetEvent (buffer_ready)
> 
> 
> while win32event.WaitForSingleObject (data_ready, 1000) ==
> win32event.WAIT_TIMEOUT:
>print "Timed out"
> 
> print "Was signaled"
> 
> appears to work.  Write access appears to be required for the buffer
> (which I can read and get useful data from:
> 
> print buffer.read(4)
> print buffer.read(4092)
> 
> and no security object.  I wasn't the one who figured this out, so I'm
> really not sure why it works...but it seems to.

Excellent! Do you mind if I add a solution based on this as a
How-Do-I? to my site [1] (suitably accredited, of course)?

TJG

[1] http://timgolden.me.uk/python/win32_how_do_i.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Capturing OutputDebugString information in python

2007-10-18 Thread danbrotherston


Wow, more of a response than I expected, thanks very much for the
research.  While not related to the mutex, the problem did appear to
be permission related.  For the record, on windows XP

import sys
import mmap
import win32event

buffer_ready = win32event.CreateEvent (None, 0, 0,
"DBWIN_BUFFER_READY")
data_ready = win32event.CreateEvent (None, 0, 0, "DBWIN_DATA_READY")
buffer = mmap.mmap (0, 4096, "DBWIN_BUFFER", mmap.ACCESS_WRITE)


win32event.SetEvent (buffer_ready)


while win32event.WaitForSingleObject (data_ready, 1000) ==
win32event.WAIT_TIMEOUT:
   print "Timed out"

print "Was signaled"

appears to work.  Write access appears to be required for the buffer
(which I can read and get useful data from:

print buffer.read(4)
print buffer.read(4092)

and no security object.  I wasn't the one who figured this out, so I'm
really not sure why it works...but it seems to.


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


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

2007-10-18 Thread Alex Martelli
Grant Edwards <[EMAIL PROTECTED]> wrote:
   ...
> I like the solution somebody sent me via PM:
> 
> def toggle():
> while 1:
> yield "Even"
> yield "Odd"

I think the itertools-based solution is more elegant:

toggle = itertools.cycle(('Even', 'Odd'))

and use toggle rather than toggle() later; or, just use that
itertools.cycle call inside the expression instead of toggle().


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


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

2007-10-18 Thread Alex Martelli
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?

That's what the timeit module is for, but make sure that the snippet
you're timing has no side effects (since it's repeatedly executed).
E.g.:

brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
'a=z[:];a.extend(b)'
100 loops, best of 3: 0.769 usec per loop
brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
100 loops, best of 3: 0.664 usec per loop
brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
'a=z[:];a.extend(b)'
100 loops, best of 3: 0.769 usec per loop
brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
100 loops, best of 3: 0.665 usec per loop
brain:~ alex$ 

The repetition of the measurements show them very steady, so now you
know that += is about 100 nanoseconds faster (on my laptop) than extend
(the reason is: it saves the tiny cost of looking up 'extend' on a; to
verify this, use much longer lists and you'll notice that while overall
times for both approaches increase, the difference between the two
approaches remains about the same for lists of any length).

But the key point to retain is: make sure that the snippet is free of
side effects, so that each of the MANY repetitions that timeit does is
repeating the SAME operation.  If we initialized a in the -s and then
just extended it in the snippet, we'd be extending a list that keeps
growing at each repetition -- a very different operation than extending
a list of a certain fixed starting length (here, serendipitously, we'd
end up measuring the same difference -- but in the general case, where
timing difference between approaches DOES depend on the sizes of the
objects involved, our measurements would instead become meaningless).

Therefore, we initialize in -s an auxiliary list, and copy it in the
snippet.  That's better than the more natural alternative:

brain:~ alex$ python -mtimeit 'a=[1,2,3];a+=[4,5,6]'
100 loops, best of 3: 1.01 usec per loop
brain:~ alex$ python -mtimeit 'a=[1,2,3];a.extend([4,5,6])'
100 loops, best of 3: 1.12 usec per loop
brain:~ alex$ python -mtimeit 'a=[1,2,3];a+=[4,5,6]'
100 loops, best of 3: 1.02 usec per loop
brain:~ alex$ python -mtimeit 'a=[1,2,3];a.extend([4,5,6])'
100 loops, best of 3: 1.12 usec per loop

as in this "more natural alternative" we're also paying each time
through the snippet the cost of building the literal lists; this
overhead (which is a lot larger than the difference we're trying to
measure!) does not DISTORT the measurement but it sure OBSCURES it to
some extend (losing us about one significant digit worth of difference
in this case).  Remember, the WORST simple operation you can do in
measurement is gauging a small number delta as the difference of two
much larger numbers X and X+delta... so, make X as small as feasible to
reduce the resulting loss of precision!-)

You can find more details on commandline use of timeit at
 (see adjacent nodes in Python
docs for examples and details on the more advanced use of timeit inside
your own code) but I hope these indications may be of help anyway.


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


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

2007-10-18 Thread Iain King
On Oct 18, 2:29 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> 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...
>


I always use:

   state = 1 - state

for toggles.  I doubt it's much more pythonic though :)

Iain

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


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

2007-10-18 Thread J. Clifford Dyer
On Thu, Oct 18, 2007 at 11:57:10AM -, Paul Hankin wrote regarding Re: 
Appending a list's elements to another list using a list comprehension:
> 
> Not to me: I can never remember which of a.append and a.extend is
> which. Falling back to a = a + b is exactly what you want. For
> instance:
> 
> a = (1, 2, 3)
> a += (4, 5, 6)
> 
> works, whereas:
> 
> a = (1, 2, 3)
> a.extend((4, 5, 6))
> 
> doesn't. So using += makes your code more general. There's no standard
> sequence type that has extend and not +=, so worrying that += is
> slower isn't a concern unless you're using a user-defined class. Even
> then, it's probably a mistake that should be fixed in the class rather
> than requiring .extend() to be used instead of +=.
> 

I was going to argue that in fact += is not more general, it just covers a 
different set of use cases, but then I tested my hypothesis...

>>> a = [1,2,3]
>>> b = a
>>> c = [4,5,6]
>>> d = c
>>> e = [7,8,9]
>>> a.extend(e)
>>> b
[1, 2, 3, 7, 8, 9]
>>> c += e
>>> d # I expected [4, 5, 6]
[4, 5, 6, 7, 8, 9]
>>> c = c + e # But += doesn't do the same as this
>>> c
[4, 5, 6, 7, 8, 9, 7, 8, 9]
>>> d
[4, 5, 6, 7, 8, 9]

So I learned something new.

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


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

2007-10-18 Thread cokofreedom
On Oct 18, 3:48 pm, Iain King <[EMAIL PROTECTED]> wrote:
> On Oct 18, 2:29 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
>
>
>
> > 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...
>
> I always use:
>
>state = 1 - state
>
> for toggles.  I doubt it's much more pythonic though :)
>
> Iain

why not do
state = not state
?

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


Re: Version specific or not?

2007-10-18 Thread Steve Holden
Scott David Daniels wrote:
> Steven W. Orr wrote:
>> We have an app and I'm trying to decide where the app ... .
>> /usr/lib/python2.3/site-packages
>> or
>> /usr/lib/site-python
>>
>> The latter would solve a lot of problems for me.
> Fewer than you suspect
> 
>> If there are multiple versions of python installed on the same machine, 
>> having a shebang that just looked for /usr/bin/python would make my life 
>> a lot easier.
> 
>> * Since we distribute .pyo files, is there an issue if the .pyo was 
>> built with 2.3.5 and then executed by 2.4 or 2.5?
> 
> Each python M.N.X has its own byte code for distinct values of M and/or N.
> So, if you had a shared directory, not only would your users have to
> be able to write to the shared directory (when they import mumble, and
> mumble.pyc or mumble.pyo has been generated by a different version of
> Python, they will recompile mumble.py and rewrite mumble.pyc (or .pyo).
> 
If the users *don't* have write access to the directory then no 
byte-code is stored, and everything has to compile the libraries each 
time. So it isn't necessary to have write, but either way sharing 
libraries between versions is a pain for the reason you state.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Convert string to command..

2007-10-18 Thread Abandoned
I want to convert a string to command..
For example i have a string:
a="['1']"
I want to do this list..
How can i do ?

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


Re: Convert string to command..

2007-10-18 Thread Adam Atlas
On Oct 18, 10:23 am, Abandoned <[EMAIL PROTECTED]> wrote:
> I want to convert a string to command..
> For example i have a string:
> a="['1']"
> I want to do this list..
> How can i do ?

Use the builtin function "eval".

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> I want to convert a string to command..
> For example i have a string:
> a="['1']"
> I want to do this list..
> How can i do ?

The correct wording here would be expression. To evaluate expressions, there
is the function eval:

a = eval("['1']")

But beware: if the expression contains some potentially harmful code, it
will be executed. So it is generally considered bad style to use eval.

An example that fails would be 

a = eval("10**2000**2000")

or such thing.

Another alternative is to use parsers like simplejson to extract the
information. This of course only works, if your expressions are valid json.

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


Re: Pull Last 3 Months

2007-10-18 Thread Hyuga
On Oct 18, 12:25 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> 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']

Ah, you beat me to it.  I was going to point out that if you're going
to be using month strings, you should use calendar, since it can also
use the correct locale.  Plus, it offers a ridiculously simple
solution to this problem compared to all the others.

Hyuga

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
Thanks you all answer..
But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
(100.000 elements)
Is there any easy alternative ?

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> Thanks you all answer..
> But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> (100.000 elements)
> Is there any easy alternative ?

How big? How slow? For me, a 1-element list takes  0.04 seconds to be
parsed. Which I find fast.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > Thanks you all answer..
> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> > (100.000 elements)
> > Is there any easy alternative ?
>
> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
> parsed. Which I find fast.
>
> Diez

173.000 dict elements and it tooks 2.2 seconds this very big time for
my project

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


Re: pymssql - insert NULL to int

2007-10-18 Thread Diez B. Roggisch
rc wrote:

> 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.

I'm pretty sure you tried "None" instead of None

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


Re: open remote terminal

2007-10-18 Thread Steve Holden
Fabian Braennstroem wrote:
> 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
> 
pexpect would be the usual solution, I believe, if you could get it to 
interact correctly with your virtual terminal.

   http://pexpect.sourceforge.net/

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Re: CGI and external JavaScript nightmare

2007-10-18 Thread Steve Holden
allen.fowler wrote:
>> 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?
> 
That's funny.

The OP's problem is that he suffers from the delusion that people want 
to steal the source code for his CGI script.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> 173.000 dict elements and it tooks 2.2 seconds this very big time
> for my project

If you're generating the string from Python, use cPickle instead.
Much faster:

>>> import time
>>> d = dict((i, i+1) for i in xrange(17))
>>> len(d)
17
>>> s=repr(d)
>>> t0 = time.time(); d2 = eval(s); t1 = time.time()
>>> t1-t0
1.5457899570465088
>>> import cPickle as pickle
>>> s = pickle.dumps(d, -1)
>>> len(s)
1437693
>>> t0 = time.time(); d2 = pickle.loads(s); t1 = time.time()
>>> t1-t0
0.060307979583740234
>>> len(d2)
17

That is 25x speedup.  Note that cPickle's format is binary.  Using the
textual format makes for more readable pickles, but reduces the
speedup to "only" 9.5x on my machine.


P.S.
Before someone says that using pickle is unsafe, remember that he is
considering *eval* as the alternative.  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Abandoned wrote:
>> > Thanks you all answer..
>> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
>> > (100.000 elements)
>> > Is there any easy alternative ?
>>
>> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
>> parsed. Which I find fast.
>>
>> Diez
> 
> 173.000 dict elements and it tooks 2.2 seconds this very big time for
> my project

Where does the data come from?

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:26 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > 173.000 dict elements and it tooks 2.2 seconds this very big time
> > for my project
>
> If you're generating the string from Python, use cPickle instead.
> Much faster:
>
> >>> import time
> >>> d = dict((i, i+1) for i in xrange(17))
> >>> len(d)
> 17
> >>> s=repr(d)
> >>> t0 = time.time(); d2 = eval(s); t1 = time.time()
> >>> t1-t0
> 1.5457899570465088
> >>> import cPickle as pickle
> >>> s = pickle.dumps(d, -1)
> >>> len(s)
> 1437693
> >>> t0 = time.time(); d2 = pickle.loads(s); t1 = time.time()
> >>> t1-t0
>
> 0.060307979583740234>>> len(d2)
>
> 17
>
> That is 25x speedup.  Note that cPickle's format is binary.  Using the
> textual format makes for more readable pickles, but reduces the
> speedup to "only" 9.5x on my machine.
>
> P.S.
> Before someone says that using pickle is unsafe, remember that he is
> considering *eval* as the alternative.  :-)


import cPickle as pickle
a="{2:3,4:6,2:7}"
s=pickle.dumps(a, -1)
g=pickle.loads(s);
print g
'{2:3,4:6,2:7}'

Thank you very much for your answer but result is a string ??

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Abandoned wrote:
> >> > Thanks you all answer..
> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> >> > (100.000 elements)
> >> > Is there any easy alternative ?
>
> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
> >> parsed. Which I find fast.
>
> >> Diez
>
> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> > my project
>
> Where does the data come from?
>
> Diez

Data come from database..
I want to cache to speed up my system and i save the dictionary to
database for speed up but eval is very slow for do this.
Not: 2.2 second only eval operation.

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


Re: Convert string to command..

2007-10-18 Thread Marc 'BlackJack' Rintsch
On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:

> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
> 
> Thank you very much for your answer but result is a string ??

In Python terms yes, strings in Python can contain any byte value.  If you
want to put this into a database you need a BLOB column or encode it as
base64 or something similar more ASCII safe.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:51 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:
> > import cPickle as pickle
> > a="{2:3,4:6,2:7}"
> > s=pickle.dumps(a, -1)
> > g=pickle.loads(s);
> > print g
> > '{2:3,4:6,2:7}'
>
> > Thank you very much for your answer but result is a string ??
>
> In Python terms yes, strings in Python can contain any byte value.  If you
> want to put this into a database you need a BLOB column or encode it as
> base64 or something similar more ASCII safe.
>
> Ciao,
> Marc 'BlackJack' Rintsch

'{2:3,4:6,2:7}' already in database, i select this and convert to real
dictionary..

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


version 1.4 of scalar class released

2007-10-18 Thread [EMAIL PROTECTED]
Version 1.4 of my scalar class is available at

http://RussP.us/scalar.htm

No major changes. I have corrected the "repr" function to make it more
useful, and I have added a "unit_type" function that returns the type
of a unit (e.g., time, length, force). The unit_type function is
intended mainly for interactive, "calculator-style" use.

If you do scientific or engineering calculations or programming,
please check out my scalar class. I think you'll like it.

It will relieve you of the burden of keeping track of units ("darn, I
can't remember if that angle is in radians or degrees?"). And the
really nifty thing about it is that, when you want high execution
speed for production runs, you can easily switch off the units with a
simple change of the import line. All the unit objects will then be
replaced with bulit-in types (typically floats), and your output will
be unchanged, but you will notice a dramatic speedup.

A complete user guide is available in both pdf and html formats. Give
it a try and let me know what you think!

--Russ P.

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Abandoned wrote:
>> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> >> Abandoned wrote:
>> >> > Thanks you all answer..
>> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
>> >> > (100.000 elements)
>> >> > Is there any easy alternative ?
>>
>> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
>> >> be parsed. Which I find fast.
>>
>> >> Diez
>>
>> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
>> > my project
>>
>> Where does the data come from?
>>
>> Diez
> 
> Data come from database..
> I want to cache to speed up my system and i save the dictionary to
> database for speed up but eval is very slow for do this.
> Not: 2.2 second only eval operation.

Does the dictionary change often?

And you should store a pickle to the database then. Besides, making a
database-query of that size (after all, we're talking a few megs here) will
take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
it just that you think they are?

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


Pyinotify : which user ?

2007-10-18 Thread Sébastien Weber
Hello,

I'm actually writing an application with pyinotify which watchs a 
directory.
Pyinotify lets me know the events (access, modify, suppression, etc.) on 
and in the directory, but not the users who are responsable of them.
Does someone know a library which could give me that information (who's 
using a file) ?

Thank's in advance,

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


strptime and microseconds

2007-10-18 Thread mathieu
Hi there,

  I am trying to use strptime to parse my microseconds but I was not
able the documentation for it. The only list I found was:

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

 So I can get seconds with %S, but nowhere is there a microsecond
symbol...

Thanks for pointer to doc,
-Mathieu


s1 = "20070619"
s2 = "150348.62"
s = s1+s2
d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
>
> Thank you very much for your answer but result is a string ??

Because you gave it a string.  If you give it a dict, you'll get a
dict:

>>> import cPickle as pickle
>>> a = {1:2, 3:4}
>>> s = pickle.dumps(a, -1)
>>> g = pickle.loads(s)
>>> g
{1: 2, 3: 4}

If your existing database already has data in the "{...}" format, then
eval it only the first time.  Then you'll get the dict which you can
cache thruogh the use of dumps/loads.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:57 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Abandoned wrote:
> >> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> >> Abandoned wrote:
> >> >> > Thanks you all answer..
> >> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> >> >> > (100.000 elements)
> >> >> > Is there any easy alternative ?
>
> >> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
> >> >> be parsed. Which I find fast.
>
> >> >> Diez
>
> >> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> >> > my project
>
> >> Where does the data come from?
>
> >> Diez
>
> > Data come from database..
> > I want to cache to speed up my system and i save the dictionary to
> > database for speed up but eval is very slow for do this.
> > Not: 2.2 second only eval operation.
>
> Does the dictionary change often?
>
> And you should store a pickle to the database then. Besides, making a
> database-query of that size (after all, we're talking a few megs here) will
> take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
> it just that you think they are?
>
> Diez- Hide quoted text -
>
> - Show quoted text -

I'm very confused :(
I try to explain main problem...
I have a table like this:
id-1 | id-2 | value
23 24   34
56 68   66
56 98   32455
55 62   655
56 28   123
 ( 3 millions elements)

I select where id=56 and 100.000 rows are selecting but this took 2
second. (very big for my project)
I try cache to speed up this select operation..
And create a cache table:
id-1 | all
56{68:66, 98:32455, 62:655}

When i select where id 56 i select 1 row and its took 0.09 second but
i must convert text to dictionary..

Have you got any idea what can i do this conver operation ?
or
Have you got any idea what can i do cache for this table ?

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 7:02 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > import cPickle as pickle
> > a="{2:3,4:6,2:7}"
> > s=pickle.dumps(a, -1)
> > g=pickle.loads(s);
> > print g
> > '{2:3,4:6,2:7}'
>
> > Thank you very much for your answer but result is a string ??
>
> Because you gave it a string.  If you give it a dict, you'll get a
> dict:
>
> >>> import cPickle as pickle
> >>> a = {1:2, 3:4}
> >>> s = pickle.dumps(a, -1)
> >>> g = pickle.loads(s)
> >>> g
>
> {1: 2, 3: 4}
>
> If your existing database already has data in the "{...}" format, then
> eval it only the first time.  Then you'll get the dict which you can
> cache thruogh the use of dumps/loads.

Sorry i can't understand :(
Yes my database already has data in the "{..}" format and i select
this and i want to use it for dictionary..
in your example:
first data is a string
finally data is already string

I want to command like eval. (eval is not good because it is slow for
my project)

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)
> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}

If you use Python to create this cache table, then simply don't dump
it as a dictionary, but as a pickle:

id-1 | all
56 

When you load it, convert the string to dict with cPickle.loads
instead of with eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Matimus
On Oct 18, 9:09 am, Abandoned <[EMAIL PROTECTED]> wrote:
> On Oct 18, 6:57 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Abandoned wrote:
> > > On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > >> Abandoned wrote:
> > >> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > >> >> Abandoned wrote:
> > >> >> > Thanks you all answer..
> > >> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> > >> >> > (100.000 elements)
> > >> >> > Is there any easy alternative ?
>
> > >> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
> > >> >> be parsed. Which I find fast.
>
> > >> >> Diez
>
> > >> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> > >> > my project
>
> > >> Where does the data come from?
>
> > >> Diez
>
> > > Data come from database..
> > > I want to cache to speed up my system and i save the dictionary to
> > > database for speed up but eval is very slow for do this.
> > > Not: 2.2 second only eval operation.
>
> > Does the dictionary change often?
>
> > And you should store a pickle to the database then. Besides, making a
> > database-query of that size (after all, we're talking a few megs here) will
> > take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
> > it just that you think they are?
>
> > Diez- Hide quoted text -
>
> > - Show quoted text -
>
> I'm very confused :(
> I try to explain main problem...
> I have a table like this:
> id-1 | id-2 | value
> 23 24   34
> 56 68   66
> 56 98   32455
> 55 62   655
> 56 28   123
>  ( 3 millions elements)
>
> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)
> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}
>
> When i select where id 56 i select 1 row and its took 0.09 second but
> i must convert text to dictionary..
>
> Have you got any idea what can i do this conver operation ?
> or
> Have you got any idea what can i do cache for this table ?

I think several people have given you the correct answer, but for some
reason you aren't getting it. Instead of saving the string
representation of a dictionary to the database, pickle the dictionary
(not the string representation, but the actual dictionary) and save
the pickled object as a BLOB to the database. using pickle to re-
create the dictionary should be much faster than evaluating a string
representation of it.

Matt


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


Re: strptime and microseconds

2007-10-18 Thread mathieu
On Oct 18, 6:36 pm, mathieu <[EMAIL PROTECTED]> wrote:
> On Oct 18, 6:00 pm, mathieu <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi there,
>
> >   I am trying to use strptime to parse my microseconds but I was not
> > able the documentation for it. The only list I found was:
>
> >  http://docs.python.org/lib/module-time.html
>
> >  So I can get seconds with %S, but nowhere is there a microsecond
> > symbol...
>
> > Thanks for pointer to doc,
> > -Mathieu
>
> > s1 = "20070619"
> > s2 = "150348.62"
> > s = s1+s2
> > d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))
>
> Getting closer...
>
> s1 = "20070619"
> s2 = "115344.51"
> s3 = "115445.123456"
>
> ms2 = eval(s2) % 1
> mms2 = int(ms2 * 100 + 0.5)
> ms3 = eval(s3) % 1
> mms3 = int(ms3 * 100 + 0.5)
>
> s = s1 + s2
> d1 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
> d1.replace(microsecond = mms2)
> #print d1.microsecond
>
> s = s1 + s3
> d2 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
> d2.replace(microsecond = mms3)
> #print d2.microsecond
>
> d = d2 - d1
> print d.seconds
> print d.microseconds
>
> why would d.microseconds be 0 ??
>
> Thanks,
> -Mathieu


D'oh !

Ok final version is simply:

s1 = "20070619"
s2 = "115344.51"
s3 = "115446.123456"

ms2 = eval(s2) % 1
mms2 = int(ms2 * 100 + 0.5)
ms3 = eval(s3) % 1
mms3 = int(ms3 * 100 + 0.5)

s = s1 + s2
d1 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
d1 = d1.replace(microsecond = mms2)
#
s = s1 + s3
d2 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
d2 = d2.replace(microsecond = mms3)
#
d = d2 - d1
print d.seconds
print d.microseconds

sorry for the noise :))
-Mathieu




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


Re: strptime and microseconds

2007-10-18 Thread mathieu
On Oct 18, 6:00 pm, mathieu <[EMAIL PROTECTED]> wrote:
> Hi there,
>
>   I am trying to use strptime to parse my microseconds but I was not
> able the documentation for it. The only list I found was:
>
>  http://docs.python.org/lib/module-time.html
>
>  So I can get seconds with %S, but nowhere is there a microsecond
> symbol...
>
> Thanks for pointer to doc,
> -Mathieu
>
> s1 = "20070619"
> s2 = "150348.62"
> s = s1+s2
> d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))


Getting closer...

s1 = "20070619"
s2 = "115344.51"
s3 = "115445.123456"

ms2 = eval(s2) % 1
mms2 = int(ms2 * 100 + 0.5)
ms3 = eval(s3) % 1
mms3 = int(ms3 * 100 + 0.5)

s = s1 + s2
d1 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
d1.replace(microsecond = mms2)
#print d1.microsecond

s = s1 + s3
d2 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
d2.replace(microsecond = mms3)
#print d2.microsecond

d = d2 - d1
print d.seconds
print d.microseconds

why would d.microseconds be 0 ??

Thanks,
-Mathieu

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


Re: some questions about Python and tkinter

2007-10-18 Thread fabdeb
On Oct 16, 9:17 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 16 Oct 2007 11:52:22 -0700, fabdeb wrote:
> > the first: what is the differences between a function and a classe?
>
> A class bundles data and functions into one object.
>
> > In which case i should use a function ?
> > In which case i should use a class ?
>
> If you have several functions that operate on the same data it might make
> sense to put all into a class to treat them as one "unit".
>
> > The second: there is some pincipals gui toolkit: tkinter , Python Mega-
> > Widgets, PyGTK, PyQt, FxPy, WxPy
>
> > what are the advantages of each one, and in which case i use each of
> > them?
>
> `Tkinter` is part of the standard library.  If you use that or one of the
> others is a matter of taste to some degree.  In a GNOME environment PyGTK
> may look more natural, under KDE a PyQt or PyKDE based GUI may feel more
> "native".  Another factor for a decision might be the license of the GUI
> toolkit.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks for all your links and responses .
I have a better comprehension of what i have to do for my program.

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> Sorry i can't understand :(
> Yes my database already has data in the "{..}" format and i select
> this and i want to use it for dictionary..

But, do you use Python to create that data?  If so, simply convert it
to pickle binary format instead of "{...}".  As explained in my other
post:

> id-1 | all
> 56{68:66, 98:32455, 62:655}

If you use Python to create this cache table, then simply don't dump
it as a dictionary, but as a pickle:

id-1 | all
56 

When you load it, convert the string to dict with cPickle.loads
instead of with eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Pyinotify : which user ?

2007-10-18 Thread Roc Zhou
-- Forwarded message --
From: Roc Zhou <[EMAIL PROTECTED]>
Date: Oct 19, 2007 12:48 AM
Subject: Re: Pyinotify : which user ?
To: Sébastien Weber <[EMAIL PROTECTED]>

The command lsof or fuser can report who is using the file, maybe you can
have a look at their source code, but they must be C code.

But since inotify is not absolute realtime, once the file is modified,
lsof or fuser can not return the right result.

I think it's better to use a good authentication method if you want to
use inotify this way, then you know when a user logged in and what
actions or commands he/she invoked, and record the inotify events with
timestamps. And a more careful permission strategy may be more sensible.

Or you can make use of SVN?

I'm also doing a project that makes use of pyinotify, one function of it
can be a "REPORT" as an IDS(Intrusion Detection System), and I reaches
several limitations of pyinotify, which you may be interested in.

The project is at:
http://sourceforge.net/projects/crablfs

And the document is at:
http://crablfs.sourceforge.net/#ru_data_man

Thanks.

On 18 Oct 2007 16:00:24 GMT, Sébastien Weber <[EMAIL PROTECTED]> wrote:
>
> Hello,
>
> I'm actually writing an application with pyinotify which watchs a
> directory.
> Pyinotify lets me know the events (access, modify, suppression, etc.) on
> and in the directory, but not the users who are responsable of them.
> Does someone know a library which could give me that information (who's
> using a file) ?
>
> Thank's in advance,
>
> SW.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 7:40 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > Sorry i can't understand :(
> > Yes my database already has data in the "{..}" format and i select
> > this and i want to use it for dictionary..
>
> But, do you use Python to create that data?  If so, simply convert it
> to pickle binary format instead of "{...}".  As explained in my other
> post:
>
> > id-1 | all
> > 56{68:66, 98:32455, 62:655}
>
> If you use Python to create this cache table, then simply don't dump
> it as a dictionary, but as a pickle:
>
> id-1 | all
> 56 
>
> When you load it, convert the string to dict with cPickle.loads
> instead of with eval.

Yes i understand and this very very good ;)
But i have a problem..
a=eval(a)
a=pickle.dumps(a, -1)
cursor.execute("INSERT INTO cache2 VALUES ('%s')" % (a))
conn.commit()

and give me error:

psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
0x80
HINT:  This error can also happen if the byte sequence does not match
the encoding expected by the server, which is controlled by
"client_encoding".



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


Re: Convert string to command..

2007-10-18 Thread Sebastian Bassi
On 10/18/07, Adam Atlas <[EMAIL PROTECTED]> wrote:
>
> Use the builtin function "eval".

What is the difference with os.system()?

-- 
Sebastián Bassi (セバスティアン). Diplomado en Ciencia y Tecnología.
Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6
GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: CGI and external JavaScript nightmare

2007-10-18 Thread Paul Boddie
On 18 Okt, 17:24, Steve Holden <[EMAIL PROTECTED]> wrote:
> allen.fowler wrote:

[Quoting IamIan...]

> >> 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?

[...]

> > Not sure I fully understand the question.
>
> > Can you post the CGI code here?
>
> That's funny.

Yes, there's no point in employing sophisticated technical mechanisms
for security when they are all undermined by some good old-fashioned
social engineering. ;-)

> The OP's problem is that he suffers from the delusion that people want
> to steal the source code for his CGI script.

The solution being that of ensuring that the Web server settings tell
the server to always run CGI scripts and never serve up the scripts
themselves as content. Additional security, such as file permissions,
access to the server, and so on, are beyond the scope of casual Usenet
advice with the level of detail provided by the inquirer.

Paul

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


Re: Convert string to command..

2007-10-18 Thread Richard Brodie

"Matimus" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I think several people have given you the correct answer, but for some
> reason you aren't getting it. Instead of saving the string
> representation of a dictionary to the database...

Mind you, if this were Jeopardy, "Store a binary pickle
of a denormalized table back in the database" would
be a tough one. 


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


Re: python logging module and custom handler specified in config file

2007-10-18 Thread Vinay Sajip
On 15 Oct, 15:15, Frank Aune <[EMAIL PROTECTED]> wrote:
> What I'm wondering, is if its possible to specify the database handler in a
> config file like:
>
> [handler_database]
> class=DBHandler
> level=DEBUG
> formatter=database
> args=('localhost', uid='root')
>
> I've seen the log_test14.py example bundled withloggingmodule, which
> describes the DBHandler class and I can get it working if I attach this
> handler to the root logger inside my application, but I would really like to
> do it through a config file like above. But since thelogging.handlers module
> does not know about the DBHandler class, obviously this does not work.
>
> I was thinking perhaps specifying module and classname in the class= option
> above, like class=dbhandler.DBHandler, but it will just complain that
> name 'dbhandler' is not defined.
>
> Is this possible to archieve somehow?
>

The values in the config file are interpreted in the context of the
logging module's namespace. Hence, one way of achieving what you want
is putting any custom handlers in
a module of your own, and providing a binding in the logging module's
namespace. For example: assuming your DBHandler is defined in a module
customhandlers, you could do this somewhere in your code, before
loading the configuration:

import logging
import customhandlers # Use your own module name here

logging.custhandlers = customhandlers # Bind your module to
"custhandlers" in logging

and then your logging configuration can refer to
"custhandlers.DBHandler". Of course I merely used "custhandlers" and
"customhandlers" to show how you can bind to an arbitrary name.

The same technique applies to the arguments passed to the constructor.

Hope this helps,

Vinay Sajip


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


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
> On Oct 18, 6:51 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:
>>> import cPickle as pickle
>>> a="{2:3,4:6,2:7}"
>>> s=pickle.dumps(a, -1)
>>> g=pickle.loads(s);
>>> print g
>>> '{2:3,4:6,2:7}'
>>> Thank you very much for your answer but result is a string ??
>> In Python terms yes, strings in Python can contain any byte value.  If you
>> want to put this into a database you need a BLOB column or encode it as
>> base64 or something similar more ASCII safe.
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> '{2:3,4:6,2:7}' already in database, i select this and convert to real
> dictionary..

MVHO is that whoever uses a RDBMS to store language-specific serialized 
collections should be shot down without sommation.

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


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
(snip)
> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
> 
> Thank you very much for your answer but result is a string ??
> 
Of course it's a string. That's what you pickled. What did you hope ? If 
you want a dict back, then pickle a dict.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Richard Brodie a écrit :
> "Matimus" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>> I think several people have given you the correct answer, but for some
>> reason you aren't getting it. Instead of saving the string
>> representation of a dictionary to the database...
> 
> Mind you, if this were Jeopardy, "Store a binary pickle
> of a denormalized table back in the database" would
> be a tough one. 
> 
> 
Indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
(snip)
> I'm very confused :(
> I try to explain main problem...
> I have a table like this:
> id-1 | id-2 | value
> 23 24   34
> 56 68   66
> 56 98   32455
> 55 62   655
> 56 28   123
>  ( 3 millions elements)
> 
> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)

Not to bad in the absolute.

> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}

I really doubt this is the right way to go.

> When i select where id 56 i select 1 row and its took 0.09 second but
> i must convert text to dictionary..
> 
> Have you got any idea what can i do this conver operation ?

Other alread answered

> Have you got any idea what can i do cache for this table ?

Depends on your RDBMS. And as far as I'm concerned, I'd start by trying 
to find out how to optimize this query within the RDBMS - good ones are 
usually highly optimized softwares with provision for quite a lot of 
performance tuning.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2007-10-18 Thread Luis Zarrabeitia
On Thursday 18 October 2007 09:09, Grant Edwards wrote:
> I like the solution somebody sent me via PM:
>
> def toggle():
> while 1:
> yield "Even"
> yield "Odd"
>

That was me.
Sorry, list, I meant to send it to everyone but I my webmail didn't respect 
the list* headers :(.

Thanks, Grant!

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-18 Thread Arnaud Delobelle
On Oct 18, 7:06 am, Ixiaus <[EMAIL PROTECTED]> wrote:
[...]
> 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"?

I haven't got literature but I've got a (hopefully straightforward)
explanation:

In binary 2 is 10.  When you multiply by 10, you shift all your digits
left by 1 place.
When you multiply by 10**n (which is 1 followed by n zeroes), you
shift all your digits left by n places.

HTH

--
Arnaud


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


Running another python interpreter

2007-10-18 Thread Simon Pickles
Hello,

I have several servers which link to each other (and of course, to clients).

At present, I am starting them in turn manually. Is there a way with 
python to say, "open gateway.py in a new interpreter window"?

I looked at execv, etc, but they seem to replace the current process. 
Ah, maybe I need spawnv().

I am on windows i386, python 2.5

Thanks

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> > When you load it, convert the string to dict with cPickle.loads
> > instead of with eval.
> 
> Yes i understand and this very very good ;)

Good!  :-)

> psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
> 0x80
> HINT:  This error can also happen if the byte sequence does not match
> the encoding expected by the server, which is controlled by
> "client_encoding".

Use a different column type for cache2's column, one more appropriate
for storing binary characters (perhaps BYTEA for Postgres).  Don't
forget to also use a bind variable, something like:

cursor.execute("INSERT INTO cache2 VALUES (?)", a)

Using "INSERT ... ('%s')" % (a) won't work, since the huge binary
string in a can contain arbitrary characters, including the single
quote.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Carsten Haese
On Thu, 2007-10-18 at 19:53 +0200, Hrvoje Niksic wrote:
> Don't
> forget to also use a bind variable, something like:
> 
> cursor.execute("INSERT INTO cache2 VALUES (?)", a)

I second the advice, but that code won't work. The bind parameters must
be a sequence, and psycopg2 (unfortunately) uses %s for parameter
markers, instead of the SQL standard question mark. So the actual code
would be

cursor.execute("INSERT INTO cache2 VALUES (%s)", (a,) )

HTH,

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


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


Re: Running another python interpreter

2007-10-18 Thread Simon Pickles
Well, I tried:
   
os.spawnv(os.P_NOWAIT, "gateway.py", ())

and got:

OSError: [Errno 8] Exec format



Simon Pickles wrote:
> Hello,
>
> I have several servers which link to each other (and of course, to clients).
>
> At present, I am starting them in turn manually. Is there a way with 
> python to say, "open gateway.py in a new interpreter window"?
>
> I looked at execv, etc, but they seem to replace the current process. 
> Ah, maybe I need spawnv().
>
> I am on windows i386, python 2.5
>
> Thanks
>
> si
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with format string / MySQL cursor

2007-10-18 Thread Florian Lindner
Hello,
I have a string:

INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
`gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)

that is passed to a MySQL cursor from MySQLdb:

ret = cursor.execute(sql, paras)

paras is:

('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
flindner/Mail/test', 1001, 1001, '123')

But that gives me an error:

Traceback (most recent call last):
  File "account.py", line 188, in ?
main()
  File "account.py", line 33, in main
execute(action, account_type, options)
  File "account.py", line 129, in execute
executeSQL(sql, options.username, options.login, options.home,
options.directory, options.uid, options.gid, options.password)
  File "/home/flindner/common.py", line 29, in executeSQL
ret = cursor.execute(sql, paras)
  File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
148, in execute
query = query % db.literal(args)
TypeError: int argument required


I don't see errors in the format string or some other problem

What's wrong?

Thanks,

Florian

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


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

2007-10-18 Thread Debajit Adhikary
On Oct 18, 9:47 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> 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?
>
> That's what the timeit module is for, but make sure that the snippet
> you're timing has no side effects (since it's repeatedly executed).
> E.g.:
>
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 100 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 100 loops, best of 3: 0.664 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 100 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 100 loops, best of 3: 0.665 usec per loop
> brain:~ alex$
>
> The repetition of the measurements show them very steady, so now you
> know that += is about 100 nanoseconds faster (on my laptop) than extend
> (the reason is: it saves the tiny cost of looking up 'extend' on a; to
> verify this, use much longer lists and you'll notice that while overall
> times for both approaches increase, the difference between the two
> approaches remains about the same for lists of any length).

> You can find more details on commandline use of timeit at
>  (see adjacent nodes in Python
> docs for examples and details on the more advanced use of timeit inside
> your own code) but I hope these indications may be of help anyway.

Thanks for the wonderful explanation on timeit.
Thats one more tool now in my arsenal :P

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


Re: Strange behaviour with reversed()

2007-10-18 Thread Andreas Kraemer
On Oct 18, 2:25 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> >> 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.
>
> > You know, that's probably the *least* intuitive behaviour possible.
>
> > For reversed() to iterate over the input as it was at creation time is
> a
> > reasonable design choice; for it to iterate over the input as it is at
> > call time is also a reasonable design choice; but for it to iterate
> over
> > some unholy mutant melding of the sequence as-it-was and as-it-is is
> > simply bizarre. I hope it just fell out of the implementation and
> wasn't
> > a deliberate design choice.
>
> You mean that you don't find it intuitive that it iterates through the
> indices that existed at creation time and returns the values as they are
> now? I'd have said that was the *most* intuitive behaviour.
>
> The only other behaviours I would regard as intuitive for iteration over
> a mutating sequence would be to throw an exception either for mutating
> the sequence while the iterator exists or for using the iterator after a
> mutation.

Maybe it would have been slightly more intuitive if reversed() had
been implemented like this,

def Reversed(seq):
  for i in xrange(len(seq)-1,-1,-1):
yield seq[i]

so that the length of the sequence is determined when the iteration
starts, not when the iterator is created?

The unfortunate naming may also have added to the confusion since its
similarity to "sorted" suggests that a copy of the list is returned.
However,

>>> type(reversed([]))


and for comparison

>>> type(iter([]))


reveals what it really is.

-Andreas

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


1 year free

2007-10-18 Thread nayloon
www.nayloon.com business2business website.Full dynamic and 2 language
10 pages.You post your products you can find customer from all over
world.Try it.You will see the different.

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


Re: Embedded Boost.Python Enum

2007-10-18 Thread Roman Yakovenko
On 10/18/07, Cory <[EMAIL PROTECTED]> wrote:
>
> 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 think you should read next documentation:

http://boost.org/libs/python/doc/v2/scope.html

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?


http://boost.org/libs/python/doc/tutorial/doc/html/python/embedding.html
Embedding example:
http://svn.boost.org/trac/boost/browser/trunk/libs/python/test/import_.cpp

HTH

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-- 
http://mail.python.org/mailman/listinfo/python-list

image resize question

2007-10-18 Thread Tim Arnold
Hi, I'm using the Image module to resize PNG images from 300 to 100dpi for 
use in HTML pages, but I'm losing some vertical and horizontal lines in the 
images (usually images of x-y plots).

Here's what I do:
import Image
def imgResize(self,filename):
img = Image.open(filename)
dpi = img.info.get('dpi')
if dpi and 295 < int(dpi[0]) < 305:
wd = img.size[0]/3.0 #convert from 300dpi to 100dpi
ht = img.size[1]/3.0
newimg= img.resize((int(wd),int(ht)))
newimg.save(filename)

imgResize('myimage.png')

Can someone point me to a better way so I don't lose the reference lines in 
the images?
thanks,
--Tim Arnold


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


Re: Strange behaviour with reversed()

2007-10-18 Thread Terry Reedy

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|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.

The input specification strongly suggests that rev.next() successively 
yields seq[len(seq)-1], ..., seq[0]

The main question is when len(seq) is called -- on creation as it is, or 
immediately before the first yield as you appear to expect, and as it would 
be in this generator (which does NOT match the actual implementation):

def rev(seq):
n = len(seq)
while n:
 n =-1
 yield seq[n]

If len(seq) were called repeatedly (after the yield, for instance), then 
termination would no longer guaranteed (see below).

I suppose the doc could be augmented with "The iterator is intialized once 
with len(sequence) when it is created, rather than when first used or 
anytime thereafter."  But I wonder whether that would confuse those not 
thinking about corner case nuances.

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

The sequence can potentially be modified between all calls to RL.next, and 
not just before the first as in your examples.

abcs = list('abc')
for a in reversed(abcs):
print a
abcs.append(a)

The 'reverse' of a changing sequence, especially one changing in length, is 
a poorly defined concept.

| >>> L = list("abc")
| >>> RL = reversed(L)
| >>> del L
| >>> list(RL)
| ['c', 'b', 'a']
|
| This suggests that reversed() makes a copy of the list:

Nope.  'del L' merely removes the association between 'L' and the list, 
leaving the internal association between RL and the list and hence the list 
itself.  So the above is consistent with storing a reference (and an index 
initialized to len-1).

| >>> 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:

It suggests that it uses a reference and an index initialized to len-1 when 
reversed is called (rather than when RL.next is first called).

| >>> RL = reversed(L)
| >>> L[0] = 'e'
| >>> list(RL)
| ['d', 'c', 'b', 'e']
|
| And these examples suggests that reversed() is confused, or at least
| confusing:

This is completely consist with iterating down via reference and index.

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

In the internal loop of list, RL first tries to return L[2].  But that 
raises an exception, so RL quits

Terry Jan Reedy



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


problem with Python class creating

2007-10-18 Thread dmitrey
Hi all,
I have the code like this one:

from myMisc import ooIter
class MyClass:
def __init__(self): pass
iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
to other func named ooIter
field2 = val2
field3 = val3 # etc

So it yields "global name 'self' is not defined", that is true. How
could I handle the situation?

Currently I do (and it works, but give me some troubles - I should
call MyClass.__init__ for each children class, and there are lots of
those ones)

class MyClass:
def __init__(self):
iterfcn = lambda *args: ooIter(self) # i.e pass the class
instance to other func named ooIter
field2 = val2
field3 = val3 # etc

I suspect it has better solution, is it?
Thank you in advance, Dmitrey

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


Re: Problem with format string / MySQL cursor

2007-10-18 Thread timaranz
On Oct 19, 7:32 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
> Hello,
> I have a string:
>
> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)
>
> that is passed to a MySQL cursor from MySQLdb:
>
> ret = cursor.execute(sql, paras)
>
> paras is:
>
> ('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
> flindner/Mail/test', 1001, 1001, '123')
>
> But that gives me an error:
>
> Traceback (most recent call last):
>   File "account.py", line 188, in ?
> main()
>   File "account.py", line 33, in main
> execute(action, account_type, options)
>   File "account.py", line 129, in execute
> executeSQL(sql, options.username, options.login, options.home,
> options.directory, options.uid, options.gid, options.password)
>   File "/home/flindner/common.py", line 29, in executeSQL
> ret = cursor.execute(sql, paras)
>   File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
> 148, in execute
> query = query % db.literal(args)
> TypeError: int argument required
>
> I don't see errors in the format string or some other problem
>
> What's wrong?
>
> Thanks,
>
> Florian

You should be using '?' for parameter bindings in your sql string not
python format specifiers (you are after all writing sql here not
python).

INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
`gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?)

Cheers
Tim


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


Re: problem with Python class creating

2007-10-18 Thread Bruno Desthuilliers
dmitrey a écrit :
> Hi all,
> I have the code like this one:
> 
> from myMisc import ooIter
> class MyClass:

Unless you have a need for compatibility with aged Python versions, 
you'd be better using new-style classes:

class MyClass(object):

> def __init__(self): pass

This is the default behaviour, so you may as well get rid of this line.

> iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
> to other func named ooIter

cf below about this...

> field2 = val2
> field3 = val3 # etc

You're aware that these two attributes are *class* attributes (that is, 
shared by all instances) ?

> So it yields "global name 'self' is not defined", that is true.

Indeed.

> How
> could I handle the situation?


 iterfcn = lambda self: ooIter(self)

which could as well be written:

 def iterfcn(self):
 ooIter(self)


Remember that Python's methods are - at least at this stage - plain 
functions, so the 'self' parameter is *not* optional - else how could 
the function access the current instance ?

And FWIW, you don't need the *args if you don't use any other than 'self'.

> Currently I do (and it works, but give me some troubles - I should
> call MyClass.__init__ for each children class,

Not unless these classes define their own initializers. But that's 
another problem

> and there are lots of
> those ones)
> 
> class MyClass:
> def __init__(self):
> iterfcn = lambda *args: ooIter(self) 

The real problem is that you create one anonymous function *per instance*.

> I suspect it has better solution, is it?

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


Re: problem with Python class creating

2007-10-18 Thread timaranz
On Oct 19, 8:22 am, dmitrey <[EMAIL PROTECTED]> wrote:
> Hi all,
> I have the code like this one:
>
> from myMisc import ooIter
> class MyClass:
> def __init__(self): pass
> iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
> to other func named ooIter
> field2 = val2
> field3 = val3 # etc
>
> So it yields "global name 'self' is not defined", that is true. How
> could I handle the situation?
>
> Currently I do (and it works, but give me some troubles - I should
> call MyClass.__init__ for each children class, and there are lots of
> those ones)
>
> class MyClass:
> def __init__(self):
> iterfcn = lambda *args: ooIter(self) # i.e pass the class
> instance to other func named ooIter
> field2 = val2
> field3 = val3 # etc
>
> I suspect it has better solution, is it?
> Thank you in advance, Dmitrey

without having tested - I think this should work for you:

from myMisc import ooIter

class MyClass:
 def __init__(self): pass
 iterfcn = lambda self: ooIter(self)

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


Can you escape a % in string that will used for substitution

2007-10-18 Thread Gerard Brunick
Is there a way to do:

s = "I like python %i%s of the time."
print s % (99, "%")

without having to pass in "%"?

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


  1   2   >