dict: retrieve the original key by key

2011-05-15 Thread Christoph Groth
Dear python experts,

I use a huge python dictionary where the values are lists of that
dictionary's keys (yes, a graph).  Each key is thus referenced several
times.

As the keys are rather large objects, I would like to save memory by
re-using key objects wherever possible, instead of having several equal
objects in memory.

There does not seem to be a way to retrieve the original key from a
python dictionary.  Is there a technical reason for this?  (Other than
that such functionality was not considered to be useful enough.)

What I will probably do now is store (key, real_value) as values in my
dictionary.  Is there a better solution?

thanks,
Christoph

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


Re: Python drawing library?

2011-05-15 Thread Rafael Durán Castañeda

On 15/05/11 01:01, OKB (not okblacke) wrote:

Is there any Python library for interactive drawing?  I've done
some googling but most searches for "drawing" lead me to libraries for
programmatic creation of shapes on some GUI canvas.  I'm looking for GUI
widgets that allow the user to draw with the mouse, like a paint
program, and let me get info about the drawing as its made (get color at
mouse location, etc.).  I'd prefer a wxPython solution, although any
Python solution would be better than none.

Thanks,
I'm not suere, but I think you should be able to do that using PyQt 
QPaintDevice.

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


Re: dict: retrieve the original key by key

2011-05-15 Thread Chris Rebert
On Sun, May 15, 2011 at 1:28 AM, Christoph Groth  wrote:
> Dear python experts,
>
> I use a huge python dictionary where the values are lists of that
> dictionary's keys (yes, a graph).  Each key is thus referenced several
> times.
>
> As the keys are rather large objects, I would like to save memory by
> re-using key objects wherever possible, instead of having several equal
> objects in memory.
>
> There does not seem to be a way to retrieve the original key from a
> python dictionary.  Is there a technical reason for this?  (Other than
> that such functionality was not considered to be useful enough.)

Define "original key".

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


Re: Python drawing library?

2011-05-15 Thread Wojtek Mamrak
Yes, it is possible with use of PyQt.

2011/5/15 Rafael Durán Castañeda :
> On 15/05/11 01:01, OKB (not okblacke) wrote:
>>
>>        Is there any Python library for interactive drawing?  I've done
>> some googling but most searches for "drawing" lead me to libraries for
>> programmatic creation of shapes on some GUI canvas.  I'm looking for GUI
>> widgets that allow the user to draw with the mouse, like a paint
>> program, and let me get info about the drawing as its made (get color at
>> mouse location, etc.).  I'd prefer a wxPython solution, although any
>> Python solution would be better than none.
>>
>> Thanks,
>
> I'm not suere, but I think you should be able to do that using PyQt
> QPaintDevice.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


recvall()

2011-05-15 Thread Navkirat Singh
Hi All,

I am trying to program an HTTP webserver, I am a little confused about the
best way to program a recvall function. There are a couple of ways to do
this? But performance wise which one is better?

a) recvall using a timeout?
b) recvall using a condition that nothing was received?
c) recvall using a condition for it to wait for a CRLF or a timeout
whichever occurs first?

Any help would be appreciated.

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


Re: dict: retrieve the original key by key

2011-05-15 Thread Christoph Groth
Chris Rebert  writes:

> On Sun, May 15, 2011 at 1:28 AM, Christoph Groth  wrote:
>> I use a huge python dictionary where the values are lists of that
>> dictionary's keys (yes, a graph).  Each key is thus referenced
>> several times.
>>
>> As the keys are rather large objects, I would like to save memory by
>> re-using key objects wherever possible, instead of having several
>> equal objects in memory.
>>
>> There does not seem to be a way to retrieve the original key from a
>> python dictionary.  Is there a technical reason for this?  (Other
>> than that such functionality was not considered to be useful enough.)
>
> Define "original key".

def original_key(dictionary, key):
for k in dictionary:
if k == key:
return k
raise KeyError(key)

But this is not efficient.

I would like to avoid having _multiple_ objects which are equal (a == b)
but not the same (a is not b).  This would save a lot of memory.

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


Python 3.2 Vectors.py module

2011-05-15 Thread Algis Kabaila
Hi All,

I would really appreciate any comments and suggestions for the 
Vectors.py module, which can be downloaded from 

http://akabaila.pcug.org.au/linalg/vectors.tar.gz

The tar ball is only about 4 KiB, but I gather that this mailing 
list does not tolerate attachments.

The module is designed with PYTHON 3.2 and it is required for 
some structural analysis programs to port them to Python 3.x 
world.  A quick start introduction to the module follows
*
#!/usr/bin/env python3.2
''' quickVector.py - quick introduction to Vectors module. More 
information in "the manual". The quick introduction starts right 
here! With Vectors.py in the current directory, fire up the 
Python 3.2 Idle and try Vector algebra in the Python Shell. 
(Alternatively, just fire up Python 3.2 and try the commands 
from the terminal - CLI.

>>> from Vectors import Vector
>>> v1 = Vector(3, 4)
>>> print('v1 = ', v1)
v1 =  Vector(3.0, 4.0, 0.0)
>>> print('v1.size =', v1.size)
v1.size = 5.0
>>> v2 = Vector(0, -5)
>>> print('v2 =', v2)
v2 = Vector(0.0, -5.0, 0.0)
>>> print('scalar product =', v1 * v2)
scalar product = -20.0
>>> print('vector product =', v1 ** v2)
vector product = Vector(0.0, 0.0, -15.0)
>>> v3 = v1 + v2
>>> print('v1 + v2 =', v3)
v1 + v2 = Vector(3.0, -1.0, 0.0)
>>> print('v3 - v1 verify = v2 =', v3 -v1)
v3 - v1 verify = v2 = Vector(0.0, -5.0, 0.0)
>>> # All vectors are three dimensional.  But
>>> # by specifying z = 0 we had vectors in (x y)
>>> # plane. However, when we form a vector product
>>> # (aka cross product), the resulting vector has
>>> # to be at right angles to the (x y) plane, so
>>> # we return to the 3 Dimensional media...
>>> # Vector (cross) product is signalled by **
>>> w1 = v1 ** v2
>>> print('w1 = v1 ** v2 =', w1)
w1 = v1 ** v2 = Vector(0.0, 0.0, -15.0)
>>> w2 = w1 + v1
>>> print('w2 a vector in 3 dim. =', w2)
w2 a vector in 3 dim. = Vector(3.0, 4.0, -15.0)
>>> # Time to look at the "user manual" and other examples.
>>> # Temp. home: http://akabaila/pcug.org.au/linalg/vectors.py 
'''
import doctest
doctest.testmod()
*

Thank you in anticipation for suggestions and comments.

OldAl.

-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Fathom 0.3.0

2011-05-15 Thread Filip Gruszczyński
Hi,

I have released version 0.2.0 of fathom, python3 package for database
inspection. Fathom supports retrieving database schema from Sqlite3,
PostgreSQL, MySQL and Oracle.

This is still very early version and I am experimenting with different
approaches. As always I would be very thankful for any input and suggestions
about what would be useful in the library or tools.

Here you can download the package:
http://code.google.com/p/fathom/downloads/list

**Changes in 0.3.0:**
-> Oracle support :-)
-> Triggers provide information about event upon which they are fired
-> utility function for finding procedures that access a table
-> fathom2graphviz draws lines between columns for foreign key
-> fathom2graphviz and fathom2django can now print output to a file,
rather than to std

-- 
Filip Gruszczyński
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.2 Vectors.py module

2011-05-15 Thread Daniel Kluev
On Sun, May 15, 2011 at 8:15 PM, Algis Kabaila  wrote:
> Hi All,
>
> I would really appreciate any comments and suggestions for the Vectors.py
> module, which can be downloaded from

- If you intend to provide it as general-purpose vector module for
other people to use, it would be better if you pack it in separate
package and upload to PyPI.
  You can find good tutorial on packaging here:
http://diveintopython3.org/packaging.html

- NumPy/SciPy has pretty fair support for vectors. Would be good if
you pointed out the differences to begin with.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


connect SIGINT to custom interrupt handler

2011-05-15 Thread Christoph Scheingraber
Hi,

I am trying to connect SIGINT (^c) to a custom interrupt handler like
this (no threading, just straightforward): 



if __name__ == "__main__":
quit = False
def interrupt_handler(signal, frame):
global quit
if not quit:
print "blabla, i'll finish my task and quit kind of message"
print "Press ^C again to interrupt immediately."
else:
sys.exit(2)
quit = True
signal.signal(signal.SIGINT, interrupt_handler)
# main will use the quit flag to determine if it should quit before next
# task
status = main()


This worked fine in some rare lucky cases, but most of the times, the
module I am using (my university's seismology project) catches the SIGINT
and quits:

select.error: (4, 'Interrupted system call')

How can I prevent the imported module's function from catching the
interrupt signal?


Thanks to anyone that takes the time to help me...

Chris

-- 
Chris Scheingraber - www.scheingraber.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads with gtk gui problem

2011-05-15 Thread Daniel Kluev
You can also use multiprocessing module instead of threads. Use pipe
and gobject.idle_add(somefunc) to process data from other thread.


-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict: retrieve the original key by key

2011-05-15 Thread Steven D'Aprano
On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:

> I would like to avoid having _multiple_ objects which are equal (a == b)
> but not the same (a is not b).  This would save a lot of memory.

Based on the idea of interning, which is used for Python strings:

cache = {}
def my_intern(obj):
return cache.setdefault(obj, obj)


x = make_some_object()
x = my_intern(x)

This ensures that equal objects in the graph are not just equal, but the 
same cached object.


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


Re: dict: retrieve the original key by key

2011-05-15 Thread Christoph Groth
Steven D'Aprano  writes:

> On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:
>
>> I would like to avoid having _multiple_ objects which are equal (a ==
>> b) but not the same (a is not b).  This would save a lot of memory.
>
> Based on the idea of interning, which is used for Python strings:
>
> cache = {} def my_intern(obj):
> return cache.setdefault(obj, obj)
>
>
> x = make_some_object() x = my_intern(x)
>
> This ensures that equal objects in the graph are not just equal, but
> the same cached object.

This requires another dictionary, though.

But hey, they keys of my dictionary are actually strings, so I can use
the built-in intern.  Somehow, I have never stumbled accross this
built-in function so far.

Thanks a lot for the hint!

Christoph

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


Re: Python 3.2 Vectors.py module

2011-05-15 Thread Algis Kabaila
On Sunday 15 May 2011 19:44:29 Daniel Kluev wrote:
> On Sun, May 15, 2011 at 8:15 PM, Algis Kabaila 
 wrote:
> > Hi All,
> > 
> > I would really appreciate any comments and suggestions for
> > the Vectors.py module, which can be downloaded from
> 
> - If you intend to provide it as general-purpose vector
> module for other people to use, it would be better if you
> pack it in separate package and upload to PyPI.
>   You can find good tutorial on packaging here:
> http://diveintopython3.org/packaging.html
> 
> - NumPy/SciPy has pretty fair support for vectors. Would be
> good if you pointed out the differences to begin with.

Daniel, 

Thank you for the packaging suggestion.  I had a glance at 
Chapter 16 of Dive into Python, do the packaging for my own use 
and only then will go to PyPi.  Pointing out the differences is 
a tall order, but I do understand its importance.   Actually, 
airing early the development in  a mailing list may be a good 
way to get some suggestions as to where similarities may be. For 
one, "euclid " was an inspiration.  I started by trying to 
update it for Python 3.x and that lead to developing an 
alternative package. The size of it (in terms of code lines) is 
differs by a factor of 10, partly because the Vectors.py does 
not deal with matrices as for my interests I would need a much 
wider reaching package.

My moves are slow for a variety of reasons, but ignoring advice 
is not one of the reasons.  Your suggestions are greatly 
appreciated.

OldAl.
-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the IP address of WIFI interface

2011-05-15 Thread Neal Becker
Far.Runner wrote:

> Hi python experts:
> There are two network interfaces on my laptop: one is 100M Ethernet
> interface, the other is wifi interface, both are connected and has an ip
> address.
> The question is: How to get the ip address of the wifi interface in a python
> script without parsing the output of a shell command like "ipconfig" or
> "ifconfig"?
> 
> OS: Windows or Linux
> 
> F.R

Here's some useful snippits for linux:

def get_default_if():
f = open('/proc/net/route')
for i in csv.DictReader(f, delimiter="\t"):
if long(i['Destination'], 16) == 0:
return i['Iface']
return None

def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,  # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])


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


Re: Get the IP address of WIFI interface

2011-05-15 Thread Tim Golden

On 15/05/2011 12:04 PM, Neal Becker wrote:

Far.Runner wrote:


Hi python experts:
There are two network interfaces on my laptop: one is 100M Ethernet
interface, the other is wifi interface, both are connected and has an ip
address.
The question is: How to get the ip address of the wifi interface in a python
script without parsing the output of a shell command like "ipconfig" or
"ifconfig"?

OS: Windows or Linux

F.R


Here's some useful snippits for linux:


... and for Windows:


import wmi

for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
  print nic.Caption, nic.IPAddress



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


Re: problem with GKT module?

2011-05-15 Thread Alister Ware
On Fri, 13 May 2011 13:13:00 +, alister ware wrote:

> I am using gtk.builder with a glade generated GUI
> 
> I have a simple call back defined for a radio button widget when I use
> widget.name in linux I get a value of None, windows returns the widget
> name as I would expect.
> 
> is this a bug?
> if not how should i find the name of the widget that has triggered a
> call back?
> 
> (I would like all my radio buttons to go to the same callback routine if
> possible to make code maintenance easier)
> 
So nobody has any Ideas on this at all?



-- 
I never failed to convince an audience that the best thing they
could do was to go away.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread SigmundV
I think the OP wants to find the intersection of two lists.
list(set(list1) & set(list2)) is indeed one way to achieve this. [i
for i in list1 if i in list2] is another one.

Sigmund

On May 15, 4:11 am, Chris Torek  wrote:
> In article <871v00j2bh@benfinney.id.au>
> Ben Finney   wrote:
>
> >As pointed out: you already know how to create a set from an object;
> >creating a list from an object is very similar:
>
> >    list(set(aa))
>
> >But why are you doing that? What are you trying to achieve?
>
> I have no idea why someone *else* is doing that, but I have used
> this very expression to unique-ize a list:
>
>     >>> x = [3, 1, 4, 1, 5, 9, 2, 6]
>     >>> x
>     [3, 1, 4, 1, 5, 9, 2, 6]
>     >>> list(set(x))
>     [1, 2, 3, 4, 5, 6, 9]
>     >>>
>
> Of course, this trick only works if all the list elements are
> hashable.
>
> This might not be the best example since the result is sorted
> "by accident", while other list(set(...)) results are not.  Add
> sorted() or .sort() if needed:
>
>     >>> x = ['three', 'one', 'four', 'one', 'five']
>     >>> x
>     ['three', 'one', 'four', 'one', 'five']
>     >>> list(set(x))
>     ['four', 'five', 'three', 'one']
>     >>> sorted(list(set(x)))
>     ['five', 'four', 'one', 'three']
>     >>>
> --
> In-Real-Life: Chris Torek, Wind River Systems
> Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
> email: gmail (figure it out)      http://web.torek.net/torek/index.html

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


Re: Converting a set into list

2011-05-15 Thread SigmundV
I'm sorry I top posted. I'll remember not to top post next time.

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


Re: Python enabled gdb on Windows and relocation

2011-05-15 Thread Ruben Van Boxem
2011/5/14 Doug Evans :
> On Sat, May 14, 2011 at 2:09 AM, Ruben Van Boxem
>  wrote:
>> 2011/5/14 Doug Evans :
>>> On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem
>>>  wrote:
 (now in plain-text as required by gdb mailing list)

 Hi,

 I am currently trying to integrate Python support into my toolchain
 build (including GDB of course). It is a sysrooted
 binutils+GCC+GDB+mingw-w64 toolchain.

 I currently have the basic setup working: I can link gdb with my
 manually generated import lib to the python dll from the official
 Windows install. If there is anything I am missing or a very easy
 solution to the problems decsribed below, please just say so. I am
 only suggesting what I would like to happen.

 Now on to the problems I'd like to discuss:

 1. gdb.exe won't start without me having set PYTHONPATH manually.
>>>
>>> In a properly configured/built gdb on linux this isn't necessary, even
>>> if python is installed in some random place.
>>> I'm not sure about windows though.
>>> Did you specify --with-python when you configured gdb, and if so did
>>> you specify a value?
>>> e.g., --with-python=SOME_VALUE
>>
>> I was cross-compiling a mingw toolchain+gdb from Linux, so I used
>> --with-python without a value (because gdb configure tries to find the
>> Python executabe), and I added -I"/path/to/python/includes" to CFLAGS
>> and -L"/path/to/pythondll/importlib" to LDFLAGS, which built as it
>> should. This is hacky though, and gdb configure should provide
>> --with-python-libs and --with-python-include to make it more
>> streamlined with any other build prerequisite (like
>> gmp/mpfr/mpc/cloog/ppl in GCC for example).
>
> Ah.
> Cross-compiling gdb with python is in need of improvement.
> Alas python hasn't been designed with cross-compilation in mind (e.g.
> build on linux, run on windows).
> AIUI, the way to get the parameters required for compiling with
> libpython is to get them from python's "distutils": kinda hard to do
> in a cross-compile.  Done correctly there's no need to run python.
>
> I haven't done anything more to support python in gdb's configure.ac
> because it's not clear to me what the right thing to do is: distutils
> provides more than just --libs and --includes (btw, we don't use
> --libs though, we use --ldflags which includes all of: the directory
> in which to find libpython, the -l for libpython, and the -l's for all
> the other libraries python needs). [Which isn't to say that someone
> else isn't free to tackle this.]
>
> In the meantime, what I've been doing is a hack: write a script that
> responds to:
> --includes
> --ldflags
> --exec-prefix
> and pass that as --with-python.
>
> E.g.
> bash$ cat $HOME/my-python-for-config
> #! /bin/sh
>
> if [ $# -ne 2 ]
> then
>        echo "Bad # args.  Blech!" >&2
>        exit 1
> fi
>
> # The first argument is the path to python-config.py, ignore it.
>
> case "$2" in
> --includes) echo "-I/usr/include/python2.6 -I/usr/include/python2.6" ;;
> --ldflags) echo "-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm
> -lpython2.6" ;;
> --exec-prefix) echo "/usr" ;;
> *) echo "Bad arg $2.  Blech!" >&2 ; exit 1 ;;
> esac
>
> exit 0
> bash$ ./configure --with-python=$HOME/my-python-for-config [...]
> [...]
>
>
> Note that --exec-prefix is the runtime location of python.
> GCC uses this to tell libpython where to find its support files.
> [grep for Py_SetProgramName in gdb/python/python.c]

OK, I tried your script in a couple of variations. It gets rid of the
traceback I had before, but still doesn't help the PYTHONPATH problem.
My directory structure is as follows (this is not in root, "/" is just
my main build directory, there are several levels below it):

/gdb <-- gdb build dir
/gdb/gdb <-- where the python configuration is done
/python <-- temporary install dir for python files for build,
extracted from the official Windows installer, also location of
libpython2.7.a import library
/python/include/python27 <-- python headers, found by gdb in both cases
/mingw64 <-- toolchain sysroot prefix
/mingw64/bin <-- install location of gdb and python27.dll
/mingw64/lib/python27 <-- install location of all python scripts

First variant:
--includes) echo "-I../../python/include" ;;
--ldflags) echo "-L../../python -lpython2.7" ;;
--exec-prefix) echo "../../mingw64/lib/python27" ;;

Here exec-prefix would be the relative path from where "configure"
does its magic to the final location of the scripts on the build
system.

Second variant:
--includes) echo "-I../../python/include" ;;
--ldflags) echo "-L../../python -lpython2.7" ;;
--exec-prefix) echo "../lib/python27" ;;

I thought the second points gdb to the installed location of the
python scripts, but it still needed PYTHONPATH for that. I used
relative paths in an attempt to "do the right thing", hackwise...
Remember that the whole "/mingw64" directory gets zipped and moved,
then it gets extracted to a random location in the Windows filesy

Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Nobody
On Sun, 15 May 2011 09:44:04 +, Christoph Scheingraber wrote:

> signal.signal(signal.SIGINT, interrupt_handler)

> This worked fine in some rare lucky cases, but most of the times, the
> module I am using (my university's seismology project) catches the SIGINT
> and quits:
> 
> select.error: (4, 'Interrupted system call')

After installing the signal handler, call:

signal.siginterrupt(signal.SIGINT, False)

This will cause (most) interrupted system calls to be restarted after the
signal has been handled.

> How can I prevent the imported module's function from catching the
> interrupt signal?

It isn't catching the signal. Unless you enable restarting of system
calls, an interrupted system call will typically fail with EINTR. Python
typically reports failures via exceptions; failures due to EINTR aren't
handled differently.

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


Re: Python enabled gdb on Windows and relocation

2011-05-15 Thread Ruben Van Boxem
2011/5/15 Ruben Van Boxem :
> 2011/5/14 Doug Evans :
>> On Sat, May 14, 2011 at 2:09 AM, Ruben Van Boxem
>>  wrote:
>>> 2011/5/14 Doug Evans :
 On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem
  wrote:
> (now in plain-text as required by gdb mailing list)
>
> Hi,
>
> I am currently trying to integrate Python support into my toolchain
> build (including GDB of course). It is a sysrooted
> binutils+GCC+GDB+mingw-w64 toolchain.
>
> I currently have the basic setup working: I can link gdb with my
> manually generated import lib to the python dll from the official
> Windows install. If there is anything I am missing or a very easy
> solution to the problems decsribed below, please just say so. I am
> only suggesting what I would like to happen.
>
> Now on to the problems I'd like to discuss:
>
> 1. gdb.exe won't start without me having set PYTHONPATH manually.

 In a properly configured/built gdb on linux this isn't necessary, even
 if python is installed in some random place.
 I'm not sure about windows though.
 Did you specify --with-python when you configured gdb, and if so did
 you specify a value?
 e.g., --with-python=SOME_VALUE
>>>
>>> I was cross-compiling a mingw toolchain+gdb from Linux, so I used
>>> --with-python without a value (because gdb configure tries to find the
>>> Python executabe), and I added -I"/path/to/python/includes" to CFLAGS
>>> and -L"/path/to/pythondll/importlib" to LDFLAGS, which built as it
>>> should. This is hacky though, and gdb configure should provide
>>> --with-python-libs and --with-python-include to make it more
>>> streamlined with any other build prerequisite (like
>>> gmp/mpfr/mpc/cloog/ppl in GCC for example).
>>
>> Ah.
>> Cross-compiling gdb with python is in need of improvement.
>> Alas python hasn't been designed with cross-compilation in mind (e.g.
>> build on linux, run on windows).
>> AIUI, the way to get the parameters required for compiling with
>> libpython is to get them from python's "distutils": kinda hard to do
>> in a cross-compile.  Done correctly there's no need to run python.
>>
>> I haven't done anything more to support python in gdb's configure.ac
>> because it's not clear to me what the right thing to do is: distutils
>> provides more than just --libs and --includes (btw, we don't use
>> --libs though, we use --ldflags which includes all of: the directory
>> in which to find libpython, the -l for libpython, and the -l's for all
>> the other libraries python needs). [Which isn't to say that someone
>> else isn't free to tackle this.]
>>
>> In the meantime, what I've been doing is a hack: write a script that
>> responds to:
>> --includes
>> --ldflags
>> --exec-prefix
>> and pass that as --with-python.
>>
>> E.g.
>> bash$ cat $HOME/my-python-for-config
>> #! /bin/sh
>>
>> if [ $# -ne 2 ]
>> then
>>        echo "Bad # args.  Blech!" >&2
>>        exit 1
>> fi
>>
>> # The first argument is the path to python-config.py, ignore it.
>>
>> case "$2" in
>> --includes) echo "-I/usr/include/python2.6 -I/usr/include/python2.6" ;;
>> --ldflags) echo "-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm
>> -lpython2.6" ;;
>> --exec-prefix) echo "/usr" ;;
>> *) echo "Bad arg $2.  Blech!" >&2 ; exit 1 ;;
>> esac
>>
>> exit 0
>> bash$ ./configure --with-python=$HOME/my-python-for-config [...]
>> [...]
>>
>>
>> Note that --exec-prefix is the runtime location of python.
>> GCC uses this to tell libpython where to find its support files.
>> [grep for Py_SetProgramName in gdb/python/python.c]
>
> OK, I tried your script in a couple of variations. It gets rid of the
> traceback I had before, but still doesn't help the PYTHONPATH problem.
> My directory structure is as follows (this is not in root, "/" is just
> my main build directory, there are several levels below it):
>
> /gdb <-- gdb build dir
> /gdb/gdb <-- where the python configuration is done
> /python <-- temporary install dir for python files for build,
> extracted from the official Windows installer, also location of
> libpython2.7.a import library
> /python/include/python27 <-- python headers, found by gdb in both cases
> /mingw64 <-- toolchain sysroot prefix
> /mingw64/bin <-- install location of gdb and python27.dll
> /mingw64/lib/python27 <-- install location of all python scripts
>
> First variant:
> --includes) echo "-I../../python/include" ;;
> --ldflags) echo "-L../../python -lpython2.7" ;;
> --exec-prefix) echo "../../mingw64/lib/python27" ;;
>
> Here exec-prefix would be the relative path from where "configure"
> does its magic to the final location of the scripts on the build
> system.
>
> Second variant:
> --includes) echo "-I../../python/include" ;;
> --ldflags) echo "-L../../python -lpython2.7" ;;
> --exec-prefix) echo "../lib/python27" ;;
>
> I thought the second points gdb to the installed location of the
> python scripts, but it still needed PYTHONPATH for that. I used
> relative paths in a

SEE KAREENA KAPOOR BOLLYWOOD HOT ACTRESS BOOBS PRESSED IN SHOPPING MALL

2011-05-15 Thread charmi s
SEE KAREENA KAPOOR BOLLYWOOD HOT ACTRESS BOOBS PRESSED IN SHOPPING
MALL
At http://hollypops.Co.CC

Due to GOOGLE security risks, i have hidden the videos in an image.
in that website on Right side  below search box click on image
and watch videos in all angles.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Christoph Scheingraber
I now have signal.siginterrupt(signal.SIGINT, False) in the line
below signal.signal(signal.SIGINT, interrupt_handler)

Unfortunately, pressing ^c still results in the same interrupt error. I
also tried putting signal.siginterrupt into the interrupt_handler
function, which gave an interesting result:
File "/usr/local/bin/obspysod", line 586, in interrupt_handler
signal.siginterrupt(signal.SIGINT, False)
AttributeError: 'int' object has no attribute 'siginterrupt'

Could there be a namespace problem?



On 2011-05-15, Nobody  wrote:
> On Sun, 15 May 2011 09:44:04 +, Christoph Scheingraber wrote:
>
>> signal.signal(signal.SIGINT, interrupt_handler)
>
>> This worked fine in some rare lucky cases, but most of the times, the
>> module I am using (my university's seismology project) catches the SIGINT
>> and quits:
>> 
>> select.error: (4, 'Interrupted system call')
>
> After installing the signal handler, call:
>
>   signal.siginterrupt(signal.SIGINT, False)
>
> This will cause (most) interrupted system calls to be restarted after the
> signal has been handled.
>
>> How can I prevent the imported module's function from catching the
>> interrupt signal?
>
> It isn't catching the signal. Unless you enable restarting of system
> calls, an interrupted system call will typically fail with EINTR. Python
> typically reports failures via exceptions; failures due to EINTR aren't
> handled differently.
>


-- 
Chris Scheingraber - www.scheingraber.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Miki Tebeka
Greetings,

> I am trying to connect SIGINT (^c) to a custom interrupt handler like
> this (no threading, just straightforward): 
Why not just catch KeyboardInterrupt?

All the best,
--
Miki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Chris Angelico
On Mon, May 16, 2011 at 12:32 AM, Christoph Scheingraber  wrote:
> I now have signal.siginterrupt(signal.SIGINT, False) in the line
> below signal.signal(signal.SIGINT, interrupt_handler)
>
> Unfortunately, pressing ^c still results in the same interrupt error. I
> also tried putting signal.siginterrupt into the interrupt_handler
> function, which gave an interesting result:
>    File "/usr/local/bin/obspysod", line 586, in interrupt_handler
>    signal.siginterrupt(signal.SIGINT, False)
>    AttributeError: 'int' object has no attribute 'siginterrupt'
>
> Could there be a namespace problem?

def interrupt_handler(signal, frame):

You're using 'signal' as a parameter here. The local int is masking
the global module.

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


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Thomas 'PointedEars' Lahn
Christoph Scheingraber wrote:

> I now have signal.siginterrupt(signal.SIGINT, False) in the line
> below signal.signal(signal.SIGINT, interrupt_handler)
> 
> Unfortunately, pressing ^c still results in the same interrupt error. I
> also tried putting signal.siginterrupt into the interrupt_handler
> function, which gave an interesting result:
> File "/usr/local/bin/obspysod", line 586, in interrupt_handler
> signal.siginterrupt(signal.SIGINT, False)
> AttributeError: 'int' object has no attribute 'siginterrupt'
> 
> Could there be a namespace problem?

Obviously.  `signal' refers to an `int' object, probably by something like

  signal = 42

before.  E.g. `print' or a debugger will tell you, as you have not showed 
the relevant parts of the code.


Please trim your quotes to the relevant minimum; DO NOT top-post.
Also, it is not acceptable behavior to use domain namespaces without 
authorization (ch...@spam.org is not a mailbox, yet spam.org is
registered to someone else).

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread TheSaint
SigmundV wrote:

> I think the OP wants to find the intersection of two lists.
> list(set(list1) & set(list2)) is indeed one way to achieve this. [i
> for i in list1 if i in list2] is another one

Exactly. I was confused on that I wasn't able to have a list in return.
The set intersection is the smartest result better than a "for" loop or a 
comprehension list.
Infact the operatin loops are compiled into python, therfore they are the 
fastest.
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread TheSaint
Chris Torek wrote:

> >>> x = ['three', 'one', 'four', 'one', 'five']
> >>> x
> ['three', 'one', 'four', 'one', 'five']
> >>> list(set(x))
> ['four', 'five', 'three', 'one']

Why one *"one"* has purged out?
Removing double occurences in a list?
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python enabled gdb on Windows and relocation

2011-05-15 Thread Ruben Van Boxem
2011/5/15 Ruben Van Boxem :
> 2011/5/15 Ruben Van Boxem :
>> 2011/5/14 Doug Evans :
>>> On Sat, May 14, 2011 at 2:09 AM, Ruben Van Boxem
>>>  wrote:
 2011/5/14 Doug Evans :
> On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem
>  wrote:
>> (now in plain-text as required by gdb mailing list)
>>
>> Hi,
>>
>> I am currently trying to integrate Python support into my toolchain
>> build (including GDB of course). It is a sysrooted
>> binutils+GCC+GDB+mingw-w64 toolchain.
>>
>> I currently have the basic setup working: I can link gdb with my
>> manually generated import lib to the python dll from the official
>> Windows install. If there is anything I am missing or a very easy
>> solution to the problems decsribed below, please just say so. I am
>> only suggesting what I would like to happen.
>>
>> Now on to the problems I'd like to discuss:
>>
>> 1. gdb.exe won't start without me having set PYTHONPATH manually.
>
> In a properly configured/built gdb on linux this isn't necessary, even
> if python is installed in some random place.
> I'm not sure about windows though.
> Did you specify --with-python when you configured gdb, and if so did
> you specify a value?
> e.g., --with-python=SOME_VALUE

 I was cross-compiling a mingw toolchain+gdb from Linux, so I used
 --with-python without a value (because gdb configure tries to find the
 Python executabe), and I added -I"/path/to/python/includes" to CFLAGS
 and -L"/path/to/pythondll/importlib" to LDFLAGS, which built as it
 should. This is hacky though, and gdb configure should provide
 --with-python-libs and --with-python-include to make it more
 streamlined with any other build prerequisite (like
 gmp/mpfr/mpc/cloog/ppl in GCC for example).
>>>
>>> Ah.
>>> Cross-compiling gdb with python is in need of improvement.
>>> Alas python hasn't been designed with cross-compilation in mind (e.g.
>>> build on linux, run on windows).
>>> AIUI, the way to get the parameters required for compiling with
>>> libpython is to get them from python's "distutils": kinda hard to do
>>> in a cross-compile.  Done correctly there's no need to run python.
>>>
>>> I haven't done anything more to support python in gdb's configure.ac
>>> because it's not clear to me what the right thing to do is: distutils
>>> provides more than just --libs and --includes (btw, we don't use
>>> --libs though, we use --ldflags which includes all of: the directory
>>> in which to find libpython, the -l for libpython, and the -l's for all
>>> the other libraries python needs). [Which isn't to say that someone
>>> else isn't free to tackle this.]
>>>
>>> In the meantime, what I've been doing is a hack: write a script that
>>> responds to:
>>> --includes
>>> --ldflags
>>> --exec-prefix
>>> and pass that as --with-python.
>>>
>>> E.g.
>>> bash$ cat $HOME/my-python-for-config
>>> #! /bin/sh
>>>
>>> if [ $# -ne 2 ]
>>> then
>>>        echo "Bad # args.  Blech!" >&2
>>>        exit 1
>>> fi
>>>
>>> # The first argument is the path to python-config.py, ignore it.
>>>
>>> case "$2" in
>>> --includes) echo "-I/usr/include/python2.6 -I/usr/include/python2.6" ;;
>>> --ldflags) echo "-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm
>>> -lpython2.6" ;;
>>> --exec-prefix) echo "/usr" ;;
>>> *) echo "Bad arg $2.  Blech!" >&2 ; exit 1 ;;
>>> esac
>>>
>>> exit 0
>>> bash$ ./configure --with-python=$HOME/my-python-for-config [...]
>>> [...]
>>>
>>>
>>> Note that --exec-prefix is the runtime location of python.
>>> GCC uses this to tell libpython where to find its support files.
>>> [grep for Py_SetProgramName in gdb/python/python.c]
>>
>> OK, I tried your script in a couple of variations. It gets rid of the
>> traceback I had before, but still doesn't help the PYTHONPATH problem.
>> My directory structure is as follows (this is not in root, "/" is just
>> my main build directory, there are several levels below it):
>>
>> /gdb <-- gdb build dir
>> /gdb/gdb <-- where the python configuration is done
>> /python <-- temporary install dir for python files for build,
>> extracted from the official Windows installer, also location of
>> libpython2.7.a import library
>> /python/include/python27 <-- python headers, found by gdb in both cases
>> /mingw64 <-- toolchain sysroot prefix
>> /mingw64/bin <-- install location of gdb and python27.dll
>> /mingw64/lib/python27 <-- install location of all python scripts
>>
>> First variant:
>> --includes) echo "-I../../python/include" ;;
>> --ldflags) echo "-L../../python -lpython2.7" ;;
>> --exec-prefix) echo "../../mingw64/lib/python27" ;;
>>
>> Here exec-prefix would be the relative path from where "configure"
>> does its magic to the final location of the scripts on the build
>> system.
>>
>> Second variant:
>> --includes) echo "-I../../python/include" ;;
>> --ldflags) echo "-L../../python -lpython2.7" ;;
>> --exec-prefix) echo "../lib/python27" ;;
>>
>> 

Re: Converting a set into list

2011-05-15 Thread Steven D'Aprano
On Mon, 16 May 2011 00:05:44 +0800, TheSaint wrote:

> Chris Torek wrote:
> 
>> >>> x = ['three', 'one', 'four', 'one', 'five'] x
>> ['three', 'one', 'four', 'one', 'five']
>> >>> list(set(x))
>> ['four', 'five', 'three', 'one']
> 
> Why one *"one"* has purged out?
> Removing double occurences in a list?

Break the operation up into two steps instead of one:


>>> x = ['three', 'one', 'four', 'one', 'five']
>>> s = set(x)
>>> print s
set(['four', 'five', 'three', 'one'])
>>> list(s)
['four', 'five', 'three', 'one']


Once an element is already in a set, adding it again is a null-op:


>>> s = set()
>>> s.add(42)
>>> s.add(42)
>>> s.add(42)
>>> print s
set([42])




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


Re: Converting a set into list

2011-05-15 Thread TheSaint
Steven D'Aprano wrote:

 s = set()
 s.add(42)
 s.add(42)
 s.add(42)
 print s
> set([42])

Good to know. I'll remember it

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Christoph Scheingraber
On 2011-05-15, Thomas 'PointedEars' Lahn  wrote:
>
> Obviously.  `signal' refers to an `int' object, probably by something like
>
>   signal = 42
>
> before.  E.g. `print' or a debugger will tell you, as you have not showed 
> the relevant parts of the code.

The problem is that I am running someone else's module which seems to
use signal, I guess that means I have to create a child method?
Is it correct anyway to have

signal.siginterrupt(signal.SIGINT, False)

in my custom interrupt_handler function or should it be outside but 
after signal.signal(signal.SIGINT, interrupt_handler)?

>
> Please trim your quotes to the relevant minimum; DO NOT top-post.
> Also, it is not acceptable behavior to use domain namespaces without 
> authorization (ch...@spam.org is not a mailbox, yet spam.org is
> registered to someone else).
>

I am sorry, I changed it to my own domain.

-- 
Chris Scheingraber - www.scheingraber.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread Roy Smith
In article 
<34fc571c-f382-405d-94b1-0a673da5f...@t16g2000vbi.googlegroups.com>,
 SigmundV  wrote:

> I think the OP wants to find the intersection of two lists.
> list(set(list1) & set(list2)) is indeed one way to achieve this. [i
> for i in list1 if i in list2] is another one.

Both ways work, but the first is O(n) and the second is O(n^2).

import time
n = 1
list1 = range(n)
list2 = range(n)
t0 = time.time()
list(set(list1) & set(list2))
t1 = time.time()
print "list(set) method took %f seconds" % (t1 - t0)
t0 = time.time()
[i for i in list1 if i in list2]
t1 = time.time()
print "loop method took %f seconds" % (t1 - t0)


./intersect.py 10
list(set) method took 0.004791 seconds
loop method took 1.437322 seconds
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread rusi
On May 15, 10:07 am, Steven D'Aprano  wrote:
>
> I'm afraid I don't understand what you mean. Can you explain please, what
> properties of "first class booleans" do you think are missing from Python?


Dijkstra's writings I alluded to, take a logic/math line to this.  Let
me try to rephrase Dijkstra (who is now sadly not able to defend our
(mis)understandings of his writings) in a more linguistic way:

In English when we say something like "x is y"  the y (predicate) can
be an adjective phrase -- the apple is red -- or a noun phrase -- the
apple is a fruit.

They seem similar; they are very different -- you agree??

>From times immemorial 'true' and 'false' have been used in the
adjective sense: eg Such-and-such statement is true.
Boole's contribution -- actually Dijkstra's recognition of Boole's
contribution -- is that dignifying {true, false} from adjectives to
nouns -- the boolean domain -- fundamentally alter and improve the
rules and possibilities for our thinking. [See his puzzles in the same
paper:
http://www.google.com/url?sa=D&q=http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

As an analogy for this consider arithmetic.

Even primitive people can count: My 3 children, my 5 sheep.  They do
this with the ordinals -- first child, second child, third child...
But arithmetic cannot really take off until we allow these numbers
(ordinals) to be dignified into entities in their own right --
cardinals.
ie the mathematician needs to believe in the existence of the numbers
1,2 etc for him to do his job well.

[As an aside I may mention that philosophers of mathematicians will
call this platonism: "In which heaven do these numbers exist?"
And platonism is mysticism. And mysticism is bullshit.  But the vast
majority of practicing mathematicians refuse to be dislodged from
their 'platonic heaven.'  For them mathematics can only be done if it
is done in 'discovery' mode and not in 'invention' mode.]

And so just as good math happens by believing that the numbers exist
and discovering their properties, good logic happens when we believe
that {True, False} exist (in some platonic heaven). Which is to say
they should be nouns in our language.

Well that in summary is the Boole's ideology (Dijkstra's evangelism)
understood linguistically and independent of python/programming.

Reapplied back to the math/programming field, we find that if a value-
domain (data-type) has to be first-class, it at the least has to be a
denotable entity in the language which should be conformable with its
abstract/expected properties.
For example if my language seems to have entities like '2' '3' '+' but
2+3 does not work out equal to 5 we would (I hope!) not say the
language has first-class numbers.

But in order for any of this discussion to be possible, equality
should be well-defined.
Which means that in addition to being an equivalence relation it must
have substitutivity
http://en.wikipedia.org/wiki/Equality_%28mathematics%29#Some_basic_logical_properties_of_equality
which is another form of a very fundamental principle attributed to
Leibniz, the principle of identity of indiscernibles:
http://en.wikipedia.org/wiki/Leibniz%27s_law

Seemingly you and Dijkstra are saying something similar when you say
[1,2,3] is a way of writing true
and he says 2<3 is a way of writing true.
But on further examination (with Leibniz law above) Dijkstra's 2<3 =
True will work consistently in all contexts but [1,2,3] = True will
work sometimes and fail sometimes.

In mathSpeak we say, the definition of bool is not well defined
In CSSpeak we say the definition is not first class.

In the language of algebraic specifications, the slogan is "No
confusion, No junk"
eg 
http://www.informatik.uni-bremen.de/agbkb/lehre/ws06-07/casl/slides/Datatypes-II.pdf

This is usually applied to specific models in a given language

But it could as well be applied to the models that a language supplies
by default.
And when we apply it to python's bool as a model of the abstract/math
concept bool it has confusion and junk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the IP address of WIFI interface

2011-05-15 Thread Jun Hu
Thanks for the tip, it is really helpful!
however the class of Win32_NetworkAdapterConfiguration doesn't include the
interface type (you can NOT tell if it is a wifi interface), so I change the
code a bit like following:

import wmi

wlan_int_id=None
for nic in wmi.WMI().Win32_NetworkAdapter():
if nic.NetConnectionID == "Wireless Network Connection":
wlan_int_id=nic.Index
break

if wlan_int_id<>None:
for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
if nic.Index==wlan_int_id:
print nic.IPAddress[0]
else:
print "WLAN interface NOT Found"



On Sun, May 15, 2011 at 4:12 AM, Tim Golden  wrote:

> On 15/05/2011 12:04 PM, Neal Becker wrote:
>
>> Far.Runner wrote:
>>
>>  Hi python experts:
>>> There are two network interfaces on my laptop: one is 100M Ethernet
>>> interface, the other is wifi interface, both are connected and has an ip
>>> address.
>>> The question is: How to get the ip address of the wifi interface in a
>>> python
>>> script without parsing the output of a shell command like "ipconfig" or
>>> "ifconfig"?
>>>
>>> OS: Windows or Linux
>>>
>>> F.R
>>>
>>
>> Here's some useful snippits for linux:
>>
>
> ... and for Windows:
>
> 
> import wmi
>
> for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
>  print nic.Caption, nic.IPAddress
>
> 
>
> TJG
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursion or iteration (was Fibonacci series recursion error)

2011-05-15 Thread Mark Dickinson
On May 15, 4:32 am, rusi  wrote:
> On May 15, 2:19 am, Ian Kelly  wrote:
> > Yup, linear.  Assuming you optimize the even case so that it doesn't
> > actually call fib(n//2) twice, the call tree can be approximated as a
> > balanced binary tree with height log(n).  The total number of nodes in
> > the tree is thus O(2 ** log(n)) = O(n).
>
> It would be linear if the base of the log were 2.
> I am not sure it is.
> You see the naive fib has a complexity which is fib itself. [Earlier
> discussion with Steven]
> fib is exponential but with radix < 2 [phi = (1 + sqrt(5))/2 ]
> This would suggest that this algo is slightly better than linear.

Nope.  It's linear, just as Ian Kelly said.  If g(n) is the total
number of fib calls made for fib(n), then it's easy to show (e.g., by
induction) that:

(a) g(n) is an increasing function of n, and
(b) g(2^k) = 2^k - 1 for all k >= 1.

Hence g(n) is O(n).

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


Re: Recursion or iteration (was Fibonacci series recursion error)

2011-05-15 Thread Mark Dickinson
On May 15, 8:20 pm, Mark Dickinson  wrote:
> On May 15, 4:32 am, rusi  wrote:
>
> > On May 15, 2:19 am, Ian Kelly  wrote:
> > > Yup, linear.  Assuming you optimize the even case so that it doesn't
> > > actually call fib(n//2) twice, the call tree can be approximated as a
> > > balanced binary tree with height log(n).  The total number of nodes in
> > > the tree is thus O(2 ** log(n)) = O(n).
>
> > It would be linear if the base of the log were 2.
> > I am not sure it is.
> > You see the naive fib has a complexity which is fib itself. [Earlier
> > discussion with Steven]
> > fib is exponential but with radix < 2 [phi = (1 + sqrt(5))/2 ]
> > This would suggest that this algo is slightly better than linear.
>
> Nope.  It's linear, just as Ian Kelly said.  If g(n) is the total
> number of fib calls made for fib(n), then it's easy to show (e.g., by
> induction) that:
>
> (a) g(n) is an increasing function of n, and
> (b) g(2^k) = 2^k - 1 for all k >= 1.
>
> Hence g(n) is O(n).

Hmm.  It's even easier:  g(n) is:

  * 1 if n == 1
  * n if n > 1, n odd
  * n-1 if n > 1, n even

So definitely linear. :-)

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


Re: Get the IP address of WIFI interface

2011-05-15 Thread Tim Golden

On 15/05/2011 20:23, Jun Hu wrote:

Thanks for the tip, it is really helpful!
however the class of Win32_NetworkAdapterConfiguration doesn't include
the interface type (you can NOT tell if it is a wifi interface), so I
change the code a bit like following:

import wmi

wlan_int_id=None
for nic in wmi.WMI().Win32_NetworkAdapter():
 if nic.NetConnectionID == "Wireless Network Connection":
 wlan_int_id=nic.Index
 break

if wlan_int_id<>None:
 for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
 if nic.Index==wlan_int_id:
 print nic.IPAddress[0]
else:
 print "WLAN interface NOT Found"


Glad it was useful; you can get a little bit prettier:


import wmi

c = wmi.WMI ()
for nic in c.Win32_NetworkAdapter (
  NetConnectionID="Wireless Network Connection"
):
  for config in nic.associators (
wmi_result_class="Win32_NetworkAdapterConfiguration"
  ):
print config.Caption, "=>", " / ".join (config.IPAddress)
  break
else:
  print "No Wireless NIC found"




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


Re: Converting a set into list

2011-05-15 Thread Thomas Rachel

Am 15.05.2011 17:56 schrieb TheSaint:

SigmundV wrote:


I think the OP wants to find the intersection of two lists.
list(set(list1)&  set(list2)) is indeed one way to achieve this. [i
for i in list1 if i in list2] is another one


Exactly. I was confused on that I wasn't able to have a list in return.
The set intersection is the smartest result better than a "for" loop or a
comprehension list.


I'm not sure about if it is really the smartest way.

s=set(list2);  [i for i in list1 if i in s]
is in the same order of magnitude as the set operation. Both solutions 
seem to be equivalent in that concerns the number of needed loop runs, 
but this two-step operation might require one less loop over list1.


The set&set solution, in contrary, might require one loop while 
transforming to a set and another one for the & operation.




Infact the operatin loops are compiled into python, therfore they are the
fastest.


Which loops do you mean here?


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


Trying to understand html.parser.HTMLParser

2011-05-15 Thread Andrew Berg
I'm trying to understand why HMTLParser.feed() isn't returning the whole
page. My test script is this:

import urllib.request
import html.parser
class MyHTMLParser(html.parser.HTMLParser):   
def handle_starttag(self, tag, attrs):
if tag == 'a' and attrs:
print(tag,'-',attrs)

url = 'http://x264.nl/x264/?dir=./64bit/8bit_depth'
page = urllib.request.urlopen(url).read()
parser = MyHTMLParser()
parser.feed(str(page))

I can do print(page) and get the entire HTML source, but
parser.feed(str(page)) only spits out the information for the top links
and none of the "revision" links. Ultimately, I just want to find
the name of the first "revision" link (right now it's
"revision1995", when a new build is uploaded it will be "revision2000"
or whatever). I figure this is a relatively simple page; once I
understand all of this, I can move on to more complicated pages.

I've searched Google, but everything I find is either outdated, a
recommendation for some external module (I don't need to do anything too
fancy and most modules don't completely support Python 3 anyway) or is
just a code snippet with no real explanation. I had a book that
explained this, but I had to return it to the library (and I'll have to
get back in line to check it out again).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict: retrieve the original key by key

2011-05-15 Thread Terry Reedy

On 5/15/2011 6:46 AM, Christoph Groth wrote:

Steven D'Aprano  writes:


On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:


I would like to avoid having _multiple_ objects which are equal (a ==
b) but not the same (a is not b).  This would save a lot of memory.


Python hashed collections have methods used to test if the collection 
has an item/key that is equal to some object. They do not currently have 
a method to return the equal item/key already there. This has been 
proposed and, I believe, rejected due to lack of sufficient presented 
use cases or because, conceptually, one wants to map key values to an 
object with the key value and Stephen's identity dict does precisely that.


In any case, if you put an object into a collection and you want to use 
the object for other purposes without accessing the collection, you must 
keep a reference to it outside of the collection.


>> Based on the idea of interning, which is used for Python strings:


cache = {} def my_intern(obj):
 return cache.setdefault(obj, obj)


x = make_some_object() x = my_intern(x)

This ensures that equal objects in the graph are not just equal, but
the same cached object.


This requires another dictionary, though.


It does, however, twice reuse the key already in your graph dict, so 
each entry is minimal extra memory.


It is typical in graph algorithms to have both a graph map (nodes to set 
of nodes) and a properties map (nodes to property structure). Some 
properties are fixed, others are changed during particular algoritms. It 
is also typical to use counts as node identifiers, so that both maps are 
implemented as sequences, but string indentifiers and dict for maps work 
too.



But hey, they keys of my dictionary are actually strings, so I can use
the built-in intern.  Somehow, I have never stumbled accross this
built-in function so far.


It was, however, removed in 3.x as a seldom-externally-used internal 
implementation detail.


--
Terry Jan Reedy

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


Re: Get the IP address of WIFI interface

2011-05-15 Thread Andrew Berg
On 2011.05.15 06:12 AM, Tim Golden wrote:
> ... and for Windows:
>
> 
> import wmi
>
> for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
>print nic.Caption, nic.IPAddress
>
> 
One thing I found out about Win32_NetworkAdapterConfiguration is that it
only contains /current/ information and not the stored info that it uses
when making an initial connection (you can see and edit this info in the
Network and Sharing Center applet). The difference is that if you're
offline, that WMI object will have no useful info at all. You can find
the info in the registry if you know what the UUID (or whatever it is)
of (or assigned to) the interface (it's in
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces).
The OP said the card would be connected, so it might not be an issue,
but I think it's important to know that. Wouldn't want you to suddenly
get blank strings or exceptions and not know why. ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict: retrieve the original key by key

2011-05-15 Thread Chris Rebert
On Sun, May 15, 2011 at 1:53 PM, Terry Reedy  wrote:
> On 5/15/2011 6:46 AM, Christoph Groth wrote:

>> But hey, they keys of my dictionary are actually strings, so I can use
>> the built-in intern.  Somehow, I have never stumbled accross this
>> built-in function so far.
>
> It was, however, removed in 3.x as a seldom-externally-used internal
> implementation detail.

Still exists in sys module though:
http://docs.python.org/dev/library/sys.html#sys.intern

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


Re: checking if a list is empty

2011-05-15 Thread Terry Reedy

On 5/15/2011 1:33 PM, rusi wrote:

On May 15, 10:07 am, Steven D'Aprano  wrote:


I'm afraid I don't understand what you mean. Can you explain please, what
properties of "first class booleans" do you think are missing from Python?


Given the usual CS definition of 'first class object', all Python 
objects are first class. But that does not preclude other definitions.



Dijkstra's writings I alluded to, take a logic/math line to this.  Let
me try to rephrase Dijkstra (who is now sadly not able to defend our
(mis)understandings of his writings) in a more linguistic way:

In English when we say something like "x is y"  the y (predicate) can
be an adjective phrase -- the apple is red -- or a noun phrase -- the
apple is a fruit.

They seem similar; they are very different -- you agree??


Sometimes. Sometimes it could mean 'the apple is fruity' or 'the apple 
has the characters that define the wider grouping of fruits'. "John is 
brilliant", "John is a brilliant man", and "John is a genius" (there is 
no 'a brilliant') pretty much have the same effective meaning. But I get 
the point about reification.



From times immemorial 'true' and 'false' have been used in the

adjective sense: eg Such-and-such statement is true.
Boole's contribution -- actually Dijkstra's recognition of Boole's
contribution -- is that dignifying {true, false} from adjectives to
nouns -- the boolean domain -- fundamentally alter and improve the
rules and possibilities for our thinking. [See his puzzles in the same
paper:
http://www.google.com/url?sa=D&q=http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

As an analogy for this consider arithmetic.

Even primitive people can count: My 3 children, my 5 sheep.  They do
this with the ordinals -- first child, second child, third child...
But arithmetic cannot really take off until we allow these numbers
(ordinals) to be dignified into entities in their own right --
cardinals.
ie the mathematician needs to believe in the existence of the numbers
1,2 etc for him to do his job well.

[As an aside I may mention that philosophers of mathematicians will
call this platonism: "In which heaven do these numbers exist?"
And platonism is mysticism. And mysticism is bullshit.  But the vast
majority of practicing mathematicians refuse to be dislodged from
their 'platonic heaven.'  For them mathematics can only be done if it
is done in 'discovery' mode and not in 'invention' mode.]

And so just as good math happens by believing that the numbers exist
and discovering their properties, good logic happens when we believe
that {True, False} exist (in some platonic heaven). Which is to say
they should be nouns in our language.

Well that in summary is the Boole's ideology (Dijkstra's evangelism)
understood linguistically and independent of python/programming.

Reapplied back to the math/programming field, we find that if a value-
domain (data-type) has to be first-class, it at the least has to be a
denotable entity in the language which should be conformable with its
abstract/expected properties.
For example if my language seems to have entities like '2' '3' '+' but
2+3 does not work out equal to 5 we would (I hope!) not say the
language has first-class numbers.


You seem to equate 'number' with 'natural number' in the classical 
sense. If '2' and '3' are residue classes (remainers) mod 5, then 2 + 3 
is 0. Even kids understand clock arithmetics. Of course,

the 24 hour (0 to 23 hourse) is saner than the older 1-12,am/pm system,
but kids even manage with that.


But in order for any of this discussion to be possible, equality
should be well-defined.
Which means that in addition to being an equivalence relation it must
have substitutivity
http://en.wikipedia.org/wiki/Equality_%28mathematics%29#Some_basic_logical_properties_of_equality
which is another form of a very fundamental principle attributed to
Leibniz, the principle of identity of indiscernibles:
http://en.wikipedia.org/wiki/Leibniz%27s_law

Seemingly you and Dijkstra are saying something similar when you say
[1,2,3] is a way of writing true
and he says 2<3 is a way of writing true.
But on further examination (with Leibniz law above) Dijkstra's 2<3 =
True will work consistently in all contexts


In general, a < b will work consistently as generally expected of total 
orders if, but only if, a and b are members of a totally ordered set and 
< indicates that total order. If '<' represents a partial order, 'amay be undefined or defined as false when 'b

> but [1,2,3] = True will work sometimes and fail sometimes.

'Bool() is a much a spelling of true or false as 'a 
< b'. It works just as consistently in all contexts.


*nornal expression: evaluates to an object with a well-defined boolean 
value, which is to say, causes bool() to return True or False.



In mathSpeak we say, the definition of bool is not well defined


The math definition of bool or the Python definition?
And what definition of 'well-defined'? On builtins, bool(ob) a

Re: Get the IP address of WIFI interface

2011-05-15 Thread Jun Hu
On Sun, May 15, 2011 at 2:14 PM, Andrew Berg wrote:

>
> One thing I found out about Win32_NetworkAdapterConfiguration is that it
> only contains /current/ information and not the stored info that it uses
> when making an initial connection (you can see and edit this info in the
> Network and Sharing Center applet). The difference is that if you're
> offline, that WMI object will have no useful info at all. You can find
> the info in the registry if you know what the UUID (or whatever it is)
> of (or assigned to) the interface (it's in
>
> HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces).
> The OP said the card would be connected, so it might not be an issue,
> but I think it's important to know that. Wouldn't want you to suddenly
> get blank strings or exceptions and not know why. ;-)
>
> Thanks for the reminder, however, it seems the IPAddress
of Win32_NetworkAdapterConfiguration will be 0.0.0.0 if the interface is NOT
connected (at least that is the result on my winxp), so I think we are safe
here.   ^_^
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: turn monitor off and on

2011-05-15 Thread Gregory Ewing

Terry Reedy wrote:
My monitor then displays 'No 
signal detected' in a box and puts itself into a low-power state 
awaiting a signal. Even if the monitor does not do that, a black screen 
should use less power.


I'm not so sure about that. If the monitor is an LCD and isn't
doing anything to reduce its own power usage, then the backlight
is still running and using just as much power, whether the screen
is black or not.

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


Re: checking if a list is empty

2011-05-15 Thread Steven D'Aprano
On Sun, 15 May 2011 10:33:38 -0700, rusi wrote:

> On May 15, 10:07 am, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>>
>> I'm afraid I don't understand what you mean. Can you explain please,
>> what properties of "first class booleans" do you think are missing from
>> Python?

[snip]

I'm afraid I didn't find your discussion about reification, Platonism and 
linguistics very helpful. Some of it I disagree with, some I agree with, 
but in neither case do I see any relevance to the question of whether 
bools are first class objects in Python, and if not, why not.


> Reapplied back to the math/programming field, we find that if a value-
> domain (data-type) has to be first-class, it at the least has to be a
> denotable entity in the language which should be conformable with its
> abstract/expected properties.

Now you're getting somewhere!

> For example if my language seems to have entities like '2' '3' '+' but
> 2+3 does not work out equal to 5 we would (I hope!) not say the language
> has first-class numbers.

Well, that's a problem. By that definition, floats are not first class 
numbers. While 2+3 does work out to be equal to 5, other standard 
properties of the real number system do not apply:

>>> 0.3 + 0.4 - 0.3 == 0.4
False

Similarly, in many languages (including older versions of Python), 
neither are integers:

>>> 2147483647 + 1
Traceback (innermost last):
  File "", line 1, in ?
OverflowError: integer addition


Other languages may wrap around, giving -1 or -2147483648.

So it seems that either we're forced to accept that neither floats nor 
integers are "first class", or instead back-track and ask:

"Hang on, who decides what the expected properties are?"



> But in order for any of this discussion to be possible, equality should
> be well-defined.
> Which means that in addition to being an equivalence relation it must
> have substitutivity


Can you show us a problem that is hard to solve in Python because ([1,2] 
and True) evaluates as True, but ([1,2] == True) evaluates as False?



> http://en.wikipedia.org/wiki/Equality_%28mathematics%
29#Some_basic_logical_properties_of_equality
> which is another form of a very fundamental principle attributed to
> Leibniz, the principle of identity of indiscernibles:
> http://en.wikipedia.org/wiki/Leibniz%27s_law

But Python truth values are not indiscernible. Do you think they must be?

If they are indiscernible, there can only be two unique values (possibly 
spelled "Veritas" and "Falsus" to avoid confusion with Python's True and 
False). But why must they be indiscernible?


> Seemingly you and Dijkstra are saying something similar when you say
> [1,2,3] is a way of writing true
> and he says 2<3 is a way of writing true. But on further examination
> (with Leibniz law above) Dijkstra's 2<3 = True will work consistently in
> all contexts but [1,2,3] = True will work sometimes and fail sometimes.

Please do not arbitrarily mix Python and mathematics syntax. What you 
have stated gives a SyntaxError.

[1,2,3] == True will work always, or you have a very buggy version of 
Python. It will always return False, as expected.


I suspect that in a boolean context, the operator you want is material 
biconditional, or XNOR, also known as "p if and only if q". Python does 
not have this as a built-in, but it's easy enough to write it:

def xnor(p, q):
if p: return q
else: return p if q else True

(I have deliberately written it to return one of the two arguments when 
possible. If you don't care for this behaviour, the else clause is even 
simpler: return not q)

If you don't like the name XNOR, rename it "equals" and be done. Nobody 
says that equality *must* be spelled with = or == as an infix operator. 
That would be a foolish insistence.

Another way would be to compare the canonical truth values for equality:

bool(p) == bool(q)

but of course there's nothing special about the canonical truth values 
except ease of use. One could choose any other values:

def canonical(flag):
if flag: return "Nobody expects the Spanish Inquisition!!!"
else: return None

canonical(p) == canonical(q)

The important thing is that Python's sense of equality doesn't just apply 
in the boolean domain, it applies to the broader any-arbitrary-Python-
object domain. Python's equals is too powerful to be limited to Python's 
truth values: it needs to distinguish between 42 and 23, while in the 
boolean domain one need not.

Consequently, if you want equality in the boolean domain, you need to use 
something other than the built-in == operator. Python doesn't allow you 
to override == for built-in objects, so the simplest, most straight-
forward way is with a function. Using such a function:

>>> equals = xnor
>>> equals( equals([1, 2], 42), equals("spam", 23) )
23

which is, naturally, just another way of spelling True.



> In mathSpeak we say, the definition of bool is not well defined In
> CSSpeak we say the definition is not first class.

That is no

MySQLdb SEC_TO_TIME function returns datetime.timedelta class

2011-05-15 Thread Jorge Romero
Hi Pythonists,

I'm retrieving some time data from a MySQL database using Python's MySQLdb
library. Here's the situation, I got a time field on MySQL given in seconds,
I need it on HH:MM:SS format, so I'm SELECTING that field with SEC_TO_TIME
function, something like this:

query = "SELECT SEC_TO_TIME(SUM(seconds)) FROM table"
fetched = cursor.execute(query)
return fetched[0]

The result of the query is given to me as *datetime.timedelta *type, which
has an undesired print behavior for my purposes:

>>> query = "SELECT SEC_TO_TIME(SUM(seconds)) FROM table"
>>> fetched = cursor.execute(query)
>>> print fetched[0]
3 days, 7:30:09
>>> print type(fetched[0])


Instead of *datetime.timedelta *I need *datetime.time *type. Does anybody
knows how to change this behavior or is it something I must deal with my
code?

Thanks in advanced.

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


Re: dict: retrieve the original key by key

2011-05-15 Thread Ian Kelly
On Sun, May 15, 2011 at 4:18 AM, Steven D'Aprano
 wrote:
> On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:
>
>> I would like to avoid having _multiple_ objects which are equal (a == b)
>> but not the same (a is not b).  This would save a lot of memory.
>
> Based on the idea of interning, which is used for Python strings:
>
> cache = {}
> def my_intern(obj):
>    return cache.setdefault(obj, obj)

And if the idea of a dictionary with identical keys and values
offends, you can also use a set:

cache = set()
def my_intern(obj):
  cache.add(obj)
  return cache.intersection([obj]).pop()

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


Re: Question about available python lib for a task

2011-05-15 Thread Tim Roberts
cesium5...@yahoo.ca wrote:
>
>I would like to build a database of all the MS-Excel file on a LAN. I 
>would like to get the files metadata : filename, summary, location, 
>size, etc.
>
>Is there a dedicated python lib for the task?

No.  The file name, location, and size are all completely generic.  You can
do that with standard Python and the os.walk command.

The document properties (like the summary) can be accessed in a couple of
ways.  You can do it in Excel by opening the application, opening the
document, and using the BuiltinDocumentProperties collection.  Or, you can
do it without Excel, using the COM interfaces for "structured storage",
like IPropertySetStorage and IPropertyStorage.

>Is pywin32 one of the possible lib available?

You will need PyWin32 in order to use COM to launch Excel, or use the
structured storage interfaces.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand html.parser.HTMLParser

2011-05-15 Thread David Robinow
On Sun, May 15, 2011 at 4:45 PM, Andrew Berg  wrote:
> I'm trying to understand why HMTLParser.feed() isn't returning the whole
> page. My test script is this:
>
> import urllib.request
> import html.parser
> class MyHTMLParser(html.parser.HTMLParser):
>    def handle_starttag(self, tag, attrs):
>        if tag == 'a' and attrs:
>            print(tag,'-',attrs)
>
> url = 'http://x264.nl/x264/?dir=./64bit/8bit_depth'
> page = urllib.request.urlopen(url).read()
> parser = MyHTMLParser()
> parser.feed(str(page))
>
> I can do print(page) and get the entire HTML source, but
> parser.feed(str(page)) only spits out the information for the top links
> and none of the "revision" links. Ultimately, I just want to find
> the name of the first "revision" link (right now it's
> "revision1995", when a new build is uploaded it will be "revision2000"
> or whatever). I figure this is a relatively simple page; once I
> understand all of this, I can move on to more complicated pages.
You've got bad HTML. Look closely and you'll see the there's no space
between the "revision" strings and the style tag following.
The parser doesn't like this. I don't know a solution other than
fixing the html.
(I created a local copy, edited it and it worked.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread harrismh777

rusi wrote:

But on further examination (with Leibniz law above) Dijkstra's 2<3 =
True will work consistently in all contexts but [1,2,3] = True will
work sometimes and fail sometimes.


It would have to be written 2<3 == True;  [1,2,3] == True;  otherwise,

...

+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get the IP address of WIFI interface

2011-05-15 Thread MrJean1
Perhaps, this recipe works for your case:

  

It does parse ifconfig and ipconfig, if found.

/Jean



On May 15, 2:14 pm, Andrew Berg  wrote:
> On 2011.05.15 06:12 AM, Tim Golden wrote:> ... and for Windows:
>
> > 
> > import wmi
>
> > for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
> >    print nic.Caption, nic.IPAddress
>
> > 
>
> One thing I found out about Win32_NetworkAdapterConfiguration is that it
> only contains /current/ information and not the stored info that it uses
> when making an initial connection (you can see and edit this info in the
> Network and Sharing Center applet). The difference is that if you're
> offline, that WMI object will have no useful info at all. You can find
> the info in the registry if you know what the UUID (or whatever it is)
> of (or assigned to) the interface (it's in
> HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Inter 
> faces).
> The OP said the card would be connected, so it might not be an issue,
> but I think it's important to know that. Wouldn't want you to suddenly
> get blank strings or exceptions and not know why. ;-)

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


Re: problem with GKT module?

2011-05-15 Thread harrismh777

Alister Ware wrote:

I have a simple call back defined for a radio button widget when I use

 widget.name in linux I get a value of None, windows returns the widget
 name as I would expect.



First, not familiar with your issue...

... but might be able to help you think through it...

I am assuming that you are building a Python script using a glade 
interface that provides the widgets drag-an-drop style and then allowing 
you to take the default code, add to it, or otherwise modify it.


I am also assuming that the /call back/ is returning a Python None, on 
the linux platform... otherwise you're getting the widget name from the 
same script on the windows platform??  right?


It might be helpful to examine both scripts to see where (if any) they 
differ. More likely than not, this little snag is a difference in the 
way that the windows version of gtk+ libraries are working, than the 
original ones on the linux platform.


On the other hand, the Python wrappers for the gtk+ library on the linux 
platform may be hiding the return values. Python functions return 'None' 
if the 'return' is not explicitly coded. The gtk+ libraries may be 
returning a value but the 'builder' is not generating the right Python 
wrapper. I'm making this up, but you get the idea, and you can probably 
check from here.


On the other hand, folks here can enter into a discussion with you 
regarding the generated Python code (output from the builder) if you 
provide relevant code snippets.



Kind regards,
m harris

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


Re: turn monitor off and on

2011-05-15 Thread harrismh777

Gregory Ewing wrote:

I'm not so sure about that. If the monitor is an LCD and isn't
doing anything to reduce its own power usage, then the backlight
is still running and using just as much power, whether the screen
is black or not.


Depends on dpmi.  Some monitors turn off the backlight, and some don't. 
My monitor(s) that are LCD turn off the backlight... and the downside of 
that (very annoying) is that they have to 'warm up' again... making them 
dim for the first few seconds of use...


An LED flat panel is a completely different animal, because there is no 
backlight (no ccfl). They monitors don't use much power in the first 
place, but they use less when they're blank, obviously, not producing light.


kind regards,
m harris

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


Re: checking if a list is empty

2011-05-15 Thread Terry Reedy

On 5/15/2011 5:36 PM, Terry Reedy wrote:

On 5/15/2011 1:33 PM, rusi wrote:



Dijkstra's writings I alluded to,


at
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html

"Acquiring that familiarity requires what in these financial times is 
known as "intellectual investment"; you can take my word for it that 
this investment quickly pays off."


I recommend understanding the following as three more "intellectual 
investments":


We create a Boolean domain by drawing a distinction in some domain and 
treating everything on each side of the distinction as equal in some 
value. A Boolean value or variable represents such a dichotomy, a choice 
between two all-inclusive but mutually exclusive possibilities. Boole 
derived his domain from truth/falsity of propositions. But that is an 
interpretation of his abstract model and only one of endless possibilities.


This realization that switching networks are another interpretation is 
the basis of digital computation. Boolean algebra theorems are theorems 
about switching networks and can be used to design such networks. Such 
networks can be used to do boolean arithmetic. The trick is to coerce 
physical components into one of two states. Part of the trick is to not 
look when they are transiting between them.


For its built-in information objects, Python choose 'representation of 
something' versus 'representation of nothing' as the dichotomy. It 
matches 'something' to True and 'nothing' to False as this is generally 
more useful than the opposite matching. In boolean contexts, it 
automatically fetches the boolean value of an object.


--
Terry Jan Reedy

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


Re: checking if a list is empty

2011-05-15 Thread harrismh777

Steven D'Aprano wrote:

I'm afraid I don't understand what you mean. Can you explain please,





http://www.informatik.uni-bremen.de/agbkb/lehre/ws06-07/casl/slides/Datatypes-II.pdf


Geeze,  I wonder if software is mathematics



kind regards,
m harris



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


obviscating python code for distribution

2011-05-15 Thread Littlefield, Tyler

Hello all:
I have been considering writing a couple of programs in Python, but I 
don't want to distribute the code along with them. So I'm curious of a 
couple things.
First, does there exist a cross-platform library for playing audio 
files, whose license I would not be violating if I do this?

Second, would I be violating the twisted, wxpython licenses by doing this?
Finally, is there a good way to accomplish this? I know that I can make 
.pyc files, but those can be disassembled very very easily with the 
disassembler and shipping these still means that the person needs the 
modules that are used. Is there another way to go about this?


--

Take care,
Ty
my website:
http://tds-solutions.net
my blog:
http://tds-solutions.net/blog
skype: st8amnd127
“Programmers are in a race with the Universe to create bigger and better 
idiot-proof programs, while the Universe is trying to create bigger and better
idiots.  So far the Universe is winning.”
“If Java had true garbage collection, most programs would delete themselves 
upon execution.”

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


Re: checking if a list is empty

2011-05-15 Thread Algis Kabaila
On Friday 13 May 2011 18:47:50 Hans Georg Schaathun wrote:
> On Thu, 12 May 2011 23:20:20 +1000, Chris Angelico
> 
>wrote:
> :  Writing a program requires expertise both in programming
snip...
> 
> And the main difference here, is that the civil engineers
> have a much better language to share information.  The best
> programmers have is the programming language, and we ought
> to make that as good as possible.

As an old Civil Engineer and a retired educator of Civil and 
Aeronautical Engineers, I want to get at the end of the long 
thread.  Early in the thread I (wrongly) thought that the 
discussion just did not make sense.  Much as has been said, 
makes a good sense, though some of it is hardly relevant.  So 
what is the purpose of this discussion - is it to proffer advice 
to the "Benevolent Dictator for life" and to his cohort or is it 
to better understand the programming language Python?

In relation to the first part of the question is that the aim is 
far too ambitious - the success of Python language is enough to 
suggest that Guido and his team do not need advice and they will 
ask for it if they really do want to hear the opinions about it.  
The job they have done in developing the language is admirable 
and the users better concentrate on trying to understand it 
better.

The second part of the (rhetorical) question is that the answer 
depends what the designers of Python have chosen as criterion 
for "True" or "False". In my little effort to present Vector 
algebra in an easy to use manner
(refer to thread of yesterday: "Python 3.2 Vectors.py module")
it was necessary to answer the question of what could and what 
should be used to determine what the instruction '=='  or  '>='  
should mean and what should be used for comparison.  The only 
one that I could find useful was the equality - two vectors are 
equal if and only if all three of their components are equal.  
As the components (for purposes of engineering analysis) are 
real numbers, even the postulation of (v1.x == v2.x) is 
problematic, as has been pointed out in the thread (as the 
"floats" are subject to unavoidable round off errors).  So the 
answers are not necessarily unique and one must consider what 
the program is supposed to achieve.

BTW, the "Vector" class inherits from the list, which  avoids 
"reinventing the wheel". The other operators are assigned 
specific purposes, viz. v1 * v2 is a scalar product of two 
vectors (the result is a scalar, float), while v1 * r  (where v1 
is a vector and r is a float) is scaling the size of vector by 
factor r,  (the result is a vector) i.e. each component of v1 is 
multiplied by r.

Vector product (cross product) is shown as  v1 ** v2 (the result 
is a vector).  The purpose of choosing this scheme is neither 
linguistic, nor philosophical - it is practical, just as the 
vector algebra is practical.  It helps to visualise solutions of 
physical problems (or, if you prefer, engineering problems).

OldAl.
-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Daniel Kluev
On Mon, May 16, 2011 at 1:04 PM, Littlefield, Tyler  wrote:
> Hello all:
> Finally, is there a good way to accomplish this? I know that I can make .pyc
> files, but those can be disassembled very very easily with the disassembler
> and shipping these still means that the person needs the modules that are
> used. Is there another way to go about this?

No, there is no way to prevent users from getting access to raw python
sources. By its nature and design, python is not meant to be used this
way, and even obfuscation would not harm readability much.
However, you can write all parts you want to hide in C/C++/Cython and
distribute them as .so/.dll

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Nobody
On Sun, 15 May 2011 17:05:57 +, Christoph Scheingraber wrote:

> Is it correct anyway to have
> 
> signal.siginterrupt(signal.SIGINT, False)
> 
> in my custom interrupt_handler function

No.

> or should it be outside but after
> signal.signal(signal.SIGINT, interrupt_handler)? 

Yes.


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


Re: Converting a set into list

2011-05-15 Thread Daniel Kluev
> Both solutions seem to be equivalent in that concerns the number of needed 
> loop runs, but this two-step operation might require one less loop over list1.
> The set&set solution, in contrary, might require one loop while transforming 
> to a set and another one for the & operation.

python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
"l3 = list(set(l1) & set(l2))"
100 loops, best of 3: 2.19 msec per loop

python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
"s=set(l2); l3 = [i for i in l1 if i in s]"
100 loops, best of 3: 2.45 msec per loop

python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
"l3 = list(set(l1) & set(l2))"
10 loops, best of 3: 28 msec per loop

python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
"s=set(l2); l3 = [i for i in l1 if i in s]"
10 loops, best of 3: 28.1 msec per loop

So even with conversion back into list set&set is still marginally faster.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread James Mills
On Mon, May 16, 2011 at 12:21 PM, Daniel Kluev  wrote:
> No, there is no way to prevent users from getting access to raw python
> sources. By its nature and design, python is not meant to be used this
> way, and even obfuscation would not harm readability much.
> However, you can write all parts you want to hide in C/C++/Cython and
> distribute them as .so/.dll

Or you could do what everyone else is doing
and provide your "application" as a service in some manner.

cheers
James

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


Re: connect SIGINT to custom interrupt handler

2011-05-15 Thread Nobody
On Sun, 15 May 2011 14:32:13 +, Christoph Scheingraber wrote:

> I now have signal.siginterrupt(signal.SIGINT, False) in the line
> below signal.signal(signal.SIGINT, interrupt_handler)
> 
> Unfortunately, pressing ^c still results in the same interrupt error.

Sorry; I wasn't paying sufficient attention to the details:

>>> select.error: (4, 'Interrupted system call')

According to Linux' signal(7) manpage, select() is never restarted,
regardless of the siginterrupt() setting.

In general, wait-for-something functions aren't restarted; the caller is
expected to check that the waited-for condition actually happened, so
returning prematurely isn't considered problematic.

EINTR is one of those "special" errors (like EAGAIN) which don't
actually indicate an error. In the context of select(), a return value of
-1 with errno set to EINTR should normally be handled in the same way as a
return value of zero, i.e. "nothing has happened yet, try again".

While the EINTR case isn't identical to the zero-return case, it's much
closer to it than it is to a genuine error. If it's being treated like
genuine errors (i.e. raising an exception), that's a defect in the Python
bindings. In which case, I'd suggest catching the exception and checking
the error code, e.g.:

def myselect(rlist, wlist, xlist, timeout = None):
try:
return select.select(rlist, wlist, xlist, timeout)
except select.error, e:
if e[0] == errno.EINTR:
return 0
raise

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


Re: obviscating python code for distribution

2011-05-15 Thread Ben Finney
"Littlefield, Tyler"  writes:

> I have been considering writing a couple of programs in Python, but I
> don't want to distribute the code along with them.

This topic has been raised many times before, and there is a response
which is now common but may sound harsh:

What is it you think you would gain by obfuscating the code, and why is
that worthwhile? What evidence do you have that code obfuscation would
achieve that?

> Finally, is there a good way to accomplish this? I know that I can
> make .pyc files, but those can be disassembled very very easily with
> the disassembler and shipping these still means that the person needs
> the modules that are used. Is there another way to go about this?

Not really, no. You would be best served by critically examining the
requirement to obfuscate the code at all.

-- 
 \ “Leave nothing to chance. Overlook nothing. Combine |
  `\  contradictory observations. Allow yourself enough time.” |
_o__) —Hippocrates |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Littlefield, Tyler
I'm putting lots of work into this. I would rather not have some script 
kiddy dig through it, yank out chunks and do whatever he wants. I just 
want to distribute the program as-is, not distribute it and leave it 
open to being hacked.

On 5/15/2011 9:29 PM, Ben Finney wrote:

"Littlefield, Tyler"  writes:


I have been considering writing a couple of programs in Python, but I
don't want to distribute the code along with them.

This topic has been raised many times before, and there is a response
which is now common but may sound harsh:

What is it you think you would gain by obfuscating the code, and why is
that worthwhile? What evidence do you have that code obfuscation would
achieve that?


Finally, is there a good way to accomplish this? I know that I can
make .pyc files, but those can be disassembled very very easily with
the disassembler and shipping these still means that the person needs
the modules that are used. Is there another way to go about this?

Not really, no. You would be best served by critically examining the
requirement to obfuscate the code at all.




--

Take care,
Ty
my website:
http://tds-solutions.net
my blog:
http://tds-solutions.net/blog
skype: st8amnd127
“Programmers are in a race with the Universe to create bigger and better 
idiot-proof programs, while the Universe is trying to create bigger and better
idiots.  So far the Universe is winning.”
“If Java had true garbage collection, most programs would delete themselves 
upon execution.”

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


Re: obviscating python code for distribution

2011-05-15 Thread harrismh777

Littlefield, Tyler wrote:

I'm putting lots of work into this. I would rather not have some script
kiddy dig through it, yank out chunks and do whatever he wants. I just
want to distribute the program as-is, not distribute it and leave it
open to being hacked.


Protection via obfuscation is invalid practically as well as 
philosophically. Those of us who work in the free software movement (or 
the open software movement too) specifically believe that obfuscation is 
an incorrect approach.


Obfuscation is the paramount Microsoft strategy for protection and for 
security. It doesn't work. In fact, making the code open permits what 
many of us who consider open source to be 'good science' more secure by 
allowing peer review and community improvement.


Some of us believe that code is not useful unless its open. If I can't 
see what you're doing, comment on it, improve it if I like, and share it 
with others I don't need it (its really that simple).


Nobody can make this decision for you, of course, but please consider 
making your coding free software (GPL license), or at least open and GPL 
compatible licensed.


kind regards,
m harris


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


Re: MySQLdb SEC_TO_TIME function returns datetime.timedelta class

2011-05-15 Thread Chris Angelico
On Mon, May 16, 2011 at 10:42 AM, Jorge Romero  wrote:
> Hi Pythonists,
> I'm retrieving some time data from a MySQL database using Python's MySQLdb
> library. Here's the situation, I got a time field on MySQL given in seconds,
> I need it on HH:MM:SS format, so I'm SELECTING that field with SEC_TO_TIME
> function, something like this:
> query = "SELECT SEC_TO_TIME(SUM(seconds)) FROM table"

You're summing a column, so presumably the values are actually deltas
(it doesn't make sense, for instance, to add Tues March 16th to Sat
Nov 2nd). The result exceeds a day; in what format do you actually
want it?

For maximum flexibility, you could ditch the SEC_TO_TIME call and
simply work with the integer seconds in Python. You can then format
that into H:MM:SS or whatever suits you.

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


TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Gnarlodious
Can someone please explain what I am doing wrong?

Calling script:

from Gnomon import GnomonBase
Gnomon=GnomonBase(3)


Called script:

class GnomonBase(object):
def __init__(self, bench):
# do stuff

But all I get is:
TypeError: __init__() takes exactly 1 positional argument (2 given)

I don't understand, I am only sending one variable. What does it think
I am sending two?

This is Python 3.1.3.

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread harrismh777

Gnarlodious wrote:

class GnomonBase(object):
 def __init__(self, bench): <===  (1)   (2)
 # do stuff


This only answers the surface question I have not taken any time to 
see or understand what (if anything) you are doing which might make any 
sense... only that the message is complaining about giving __init__() 
two parms, because you gave it two parms


... I know you're joking, but I don't know why...?






kind regards,
m harris


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


Re: obviscating python code for distribution

2011-05-15 Thread Steven D'Aprano
On Sun, 15 May 2011 21:36:53 -0600, Littlefield, Tyler wrote:

> I'm putting lots of work into this. I would rather not have some script
> kiddy dig through it, yank out chunks and do whatever he wants. 


The best way to do that is to labour in obscurity, where nobody either 
knows or cares about your application. There are hundreds of thousands, 
possibly millions, of such applications, with a user base of one: the 
creator.

One other alternative is to ask yourself, what's the marginal value of 
yanking out chunks from my code? What harm does it do me if Joe Haxor 
spends hours pulling out one subroutine, or a dozen, from my app, and 
using them in his app? Why should I care?

It never ceases to amaze me how often people write some trivial 
application, like a thousand others, or even some trivial function or 
class, and then treat it like the copyright to Mickey Mouse. I don't know 
what your application is, or how it works. It's conceivable that it's the 
next Microsoft Office. But my advice to you is to take a pragmatic, 
realistic view of the cost of copyright infringement.

If it's going to cost you $1000 in extra effort to prevent $100 of harm, 
it's simply not worth it.



> I just
> want to distribute the program as-is, not distribute it and leave it
> open to being hacked.

Right... because of course we all know how Windows being distributed 
without source code makes it soo secure.

You are conflating two different issues:

* Can people "steal" or copy my ideas and code?

* Can people hack my code (in the bad sense)?


I hope this does not offend, because I mean it in the nicest possible 
way, but if you think that not distributing source code will prevent your 
code from being broken, then you are delusional.

Look at Facebook and its periodic security holes and accounts being 
hacked. Not only don't Facebook distribute source code, but they don't 
distribute *anything* -- their application is on their servers, behind a 
firewall. Does it stop hackers? Not a chance.


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


Re: MySQLdb SEC_TO_TIME function returns datetime.timedelta class

2011-05-15 Thread Jorge Romero
On Sun, May 15, 2011 at 11:50 PM, Chris Angelico  wrote:

> On Mon, May 16, 2011 at 10:42 AM, Jorge Romero 
> wrote:
> > Hi Pythonists,
> > I'm retrieving some time data from a MySQL database using Python's
> MySQLdb
> > library. Here's the situation, I got a time field on MySQL given in
> seconds,
> > I need it on HH:MM:SS format, so I'm SELECTING that field with
> SEC_TO_TIME
> > function, something like this:
> > query = "SELECT SEC_TO_TIME(SUM(seconds)) FROM table"
>
> You're summing a column, so presumably the values are actually deltas
> (it doesn't make sense, for instance, to add Tues March 16th to Sat
> Nov 2nd). The result exceeds a day; in what format do you actually
> want it?
>
> For maximum flexibility, you could ditch the SEC_TO_TIME call and
> simply work with the integer seconds in Python. You can then format
> that into H:MM:SS or whatever suits you.
>
> Chris Angelico
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Yeah, I believe that's the way to go, retrieve seconds and deal with them
with Python, for flexibility as you pointed. I need the seconds to become
HH:MM:SS format.

What seems weird to me is why MySQLdb treats the result of the query as
deltas. Here's what I get if a query directly the database, output from PHP
MyAdmin:

SEC_TO_TIME(SUM(billsec))
*79:30:09*
*
*
*This value suits better the datetime.time type, instead of
datetime.deltatime.
*

Thanks Chris for your feedback.

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Chris Rebert
On Sun, May 15, 2011 at 8:53 PM, Gnarlodious  wrote:
> Can someone please explain what I am doing wrong?
>
> Calling script:
>
> from Gnomon import GnomonBase
> Gnomon=GnomonBase(3)
>
>
> Called script:
>
> class GnomonBase(object):
>    def __init__(self, bench):
>        # do stuff
>
> But all I get is:
> TypeError: __init__() takes exactly 1 positional argument (2 given)
>
> I don't understand, I am only sending one variable. What does it think
> I am sending two?

Please post the *full* exception Traceback.

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Ian Kelly
On Sun, May 15, 2011 at 9:53 PM, Gnarlodious  wrote:
> class GnomonBase(object):
>    def __init__(self, bench):
>        # do stuff
>
> But all I get is:
> TypeError: __init__() takes exactly 1 positional argument (2 given)
>
> I don't understand, I am only sending one variable. What does it think
> I am sending two?

Usually this error means that you forgot to include "self" in the
method signature.  As a result it receives two arguments (self and
bench) but only has one defined (bench).

The snippet you posted looks correct, though.  It might be easier to
help if you posted the actual code.  Also the full stack trace might
be helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Ben Finney
"Littlefield, Tyler"  writes:

> I'm putting lots of work into this. I would rather not have some
> script kiddy dig through it, yank out chunks and do whatever he wants.
> I just want to distribute the program as-is, not distribute it and
> leave it open to being hacked.

How do these arguments apply to your code base when they don't apply to,
say, LibreOffice or Linux or Python or Apache or Firefox?

How is your code base going to be harmed by having the source code
available to recipients, when that demonstrably doesn't harm countless
other code bases out there?

-- 
 \   “Let others praise ancient times; I am glad I was born in |
  `\  these.” —Ovid (43 BCE–18 CE) |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Gnarlodious
I don't have a trace because I am using mod_wsgi under Apache. Maybe
there is a way to debug using mod_wsgi but I haven't been able to
figure out how.

My problem is that in order to run mod_wsgi I had to downgrade to
Python 3.1.3 which may be causing the problem. This website was
running fine in Py3.2.

I did find an explanation that sounds like this is an intentional
deprecation in Python:



It looks like we are now expected to initialize instance variables
with a setter statement?

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Steven D'Aprano
On Sun, 15 May 2011 20:53:31 -0700, Gnarlodious wrote:

> Can someone please explain what I am doing wrong?
> 
> Calling script:
> 
> from Gnomon import GnomonBase
> Gnomon=GnomonBase(3)
> 
> 
> Called script:
> 
> class GnomonBase(object):
> def __init__(self, bench):
> # do stuff
> 
> But all I get is:
> TypeError: __init__() takes exactly 1 positional argument (2 given)
> 
> I don't understand, I am only sending one variable. What does it think I
> am sending two?

Whenever you call a method, the instance is automatically provided by 
Python as an argument (conventionally called "self") to the function.

So, for any arbitrary method, the call:

instance.method(arg)


is converted to:

type(instance).method(instance, arg)

hence two arguments.

My guess is that your GnomonBase __init__ method is *not* what you show 
above, but (probablY) one of the following:

def __init__(bench):  # oops, forgot self
# do stuff

def __init__(selfbench):  # oops, forgot the comma
# do stuff



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


Re: obviscating python code for distribution

2011-05-15 Thread Chris Angelico
On Mon, May 16, 2011 at 2:03 PM, Steven D'Aprano
 wrote:
> The best way to do that is to labour in obscurity, where nobody either
> knows or cares about your application. There are hundreds of thousands,
> possibly millions, of such applications, with a user base of one: the
> creator.

And I'm sure Steven will agree with me that this is not in any way a
bad thing. I've written hundreds of such programs myself (possibly
thousands), and they have all served their purposes. On a slightly
larger scale, there are even more programs that have never left the
walls of my house, having been written for my own family - not because
I'm afraid someone else will steal them, but because they simply are
of no value to anyone else. But hey, if anyone wants a copy of my code
that's basically glue between [obscure application #1] and [obscure
application #2] that does [obscure translation] as well to save a
human from having to do it afterwards, sure! You're welcome to it! :)

However, I do not GPL my code; I prefer some of the other licenses
(such as CC-BY-SA), unless I'm working on a huge project that's not
meant to have separate authors. For something that by and large is one
person's work, I think it's appropriate to give attribution. But
discussion of exactly _which_ open source license to use is a can of
worms that's unlikely to be worth opening at this stage.

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Chris Rebert
On Sun, May 15, 2011 at 9:30 PM, Gnarlodious  wrote:
> I don't have a trace because I am using mod_wsgi under Apache. Maybe
> there is a way to debug using mod_wsgi but I haven't been able to
> figure out how.
>
> My problem is that in order to run mod_wsgi I had to downgrade to
> Python 3.1.3 which may be causing the problem. This website was
> running fine in Py3.2.
>
> I did find an explanation that sounds like this is an intentional
> deprecation in Python:
>  do-they-do>
> 
>
> It looks like we are now expected to initialize instance variables
> with a setter statement?

Er, what are you talking about? That's always been the case; it's
nothing new at all.
Perhaps your "# do stuff" from earlier isn't doing the right stuff?
Posting the actual code would help.

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


Memcached in python 3

2011-05-15 Thread Navkirat Singh
Hi Guys,

How can I used memcached with python 3? Are there any other good
alternatives to memcached? What about python dictionary manager, would it
compare to memcached if I were to use it for storing in-memory information?

Any light on this matter will be appreciated.

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Ian Kelly
On Sun, May 15, 2011 at 10:30 PM, Gnarlodious  wrote:
> I don't have a trace because I am using mod_wsgi under Apache. Maybe
> there is a way to debug using mod_wsgi but I haven't been able to
> figure out how.

http://code.google.com/p/modwsgi/wiki/DebuggingTechniques

> My problem is that in order to run mod_wsgi I had to downgrade to
> Python 3.1.3 which may be causing the problem. This website was
> running fine in Py3.2.
>
> I did find an explanation that sounds like this is an intentional
> deprecation in Python:
>  do-they-do>
> 

I don't think those are related.  If it were an intentional change in
Python from 2007, then you would be seeing the error in both versions.
 I don't see how the stackoverflow link has any bearing on the error
at all.

> It looks like we are now expected to initialize instance variables
> with a setter statement?

You mean like this?

x = Foo()
x.y = z

No, there is no such expectation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Gnarlodious
Well, I have a whole lot of scripts where I could say something like
this:

def __init__(self, var1, var2, var3...):

Now suddenly I have to change them all to run in Python 3.1.3?

This is apparently not a bug. And I rebooted still getting the same
behavior.

Can someone explain it?

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


Re: TypeError: __init__() takes exactly 1 positional argument (2 given)

2011-05-15 Thread Gnarlodious
Thanks for all the help, this looks like a bug in mod_wsgi. I tried it
interactively under Py3.1.3 and it behaves normally. I'll take this
over to the mod_wsgi group.

-- Gnarlie
http://Gnarlodious.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Littlefield, Tyler

Hello:
Thanks all for your information and ideas. I like the idea of open 
source; I have a fairly large (or large, by my standards anyway) project 
that I am working on that is open source.


Here's kind of what I want to prevent. I want to write a multi-player 
online game; everyone will essentually end up connecting to my server to 
play the game. I don't really like the idea of security through 
obscurity, but I wanted to prevent a couple of problems.
1) First I want to prevent people from hacking at the code, then using 
my server as a test for their new setups. I do not want someone to gain 
some extra advantage just by editing the code.

Is there some other solution to this, short of closed-source?
Thanks,

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


Re: checking if a list is empty

2011-05-15 Thread rusi
I have been scolded off-list for pursuing a discussion that has
nothing to do with python.
So I continue a bit gingerly :-)  and will stop when others feel this
is useless/irrelevant/whatever.

Steven wrote:

> I'm afraid I didn't find your discussion about reification, Platonism and
> linguistics very helpful. Some of it I disagree with, some I agree with,
> but in neither case do I see any relevance to the question of whether
> bools are first class objects in Python, and if not, why not.

Thank you (Steven and Terry) for using the word 'reification'. I used
the more common 'firstclass' because I assumed that will be more
generally known. I however prefer reification since one can discuss
(more cooly :-) ) what and how much one should reify; the word
reification has less of a strong value judgment in philosophy than
firstclass has in computer science.

The lead-writeup on reification 
http://en.wikipedia.org/wiki/Reification_%28computer_science%29
has the following line:
> Informally, reification is often referred to as "making something a 
> first-class citizen" within the scope of a particular system.

So from the CS side reification == movement-towards-firstclassness
>From the philosophical side we could try to define platonism (non-
mystically) as "The strong reification of abstract concepts"

So much for my defense of bringing in platonism into the discussion.

Steven wrote:
>
> > Seemingly you and Dijkstra are saying something similar when you say
> > [1,2,3] is a way of writing true
> > and he says 2<3 is a way of writing true. But on further examination
> > (with Leibniz law above) Dijkstra's 2<3 = True will work consistently in
> > all contexts but [1,2,3] = True will work sometimes and fail sometimes.

> Please do not arbitrarily mix Python and mathematics syntax. What you have 
> stated gives a SyntaxError.

Is this non-mixing-up possible? Like 'reification,' I do not know if
using the funny brackets of denotational semantics would be
intelligible on this list ( and I dont know how to write them in
ASCII) but using |[ ]| as an approximation, I would have to say
something like:

Dijkstra's |[ 2<3 ]| = True will work consistently... Python's |
[ [1,2,3] ]|  = |[True ]| will be be true in boolean contexts and not
elsewhere.
Note that the first |[]| is for the object language called mathematics
and the other two for the object language called python. And the = is
in a pidgin English-math meta language that is need to discuss these
object languages.

I am not clear that this form of discourse actually enhances clarity,
however it does bring up the point that this discussion is as much
about object/meta-language distinctions and confusions as it is about
reification.

You see when Terry talks of boolean algebra for switching networks, he
is referring to logic as an object language.
But when we use logic to discuss and understand (and argue :-) ) we
are using  it in the meta-language.

Dijkstra's signal contribution -- which he attributes to Boole,
Leibniz and Recorde (for the = sign) -- lies in this:
>From the time of Aristotle, all usage of logic in the meta-language
(logic as the substrate for arguments rather than logic as a model for
things like switching networks)  has been a string of assertions
linked up with 'implies' 'therefore' 'follows from' etc.  All these
when modelled (in a suitable object logic) would traditionally look
like => (implies) or at best <= (follows from)

It is possible to do all this -- traditional logic -- using = (aka
iff, <=>, etc)

The benefit is that logic becomes much more like traditional algebra:
Proofs become of the form:

desideradum
=
:
:
= true

The cost is that bool has to be properly reified.

Steven wrote:
> Rusi wrote:
> > For example if my language seems to have entities like '2' '3' '+' but
> > 2+3 does not work out equal to 5 we would (I hope!) not say the language
> > has first-class numbers.

> Well, that's a problem. By that definition, floats are not first class
> numbers. While 2+3 does work out to be equal to 5, other standard
> properties of the real number system do not apply:

> >>> 0.3 + 0.4 - 0.3 == 0.4

>From C onwards (and in Fortran), its been called float, not real.
Note that C like python uses a math-suggesting name int for integers
but a hardware implementation name for float.  This suggests that
(aside from overflow) int in C corresponds to the math Z whereas float
does not quite correspond to real.  [The whole field of numerical
analysis comes about because of this non-correspondence]

In the language Pascal, what we call float today was called real and
this would be an argument.
But in this context I dont get the argument...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-15 Thread rusi
On May 16, 2:36 am, Terry Reedy  wrote:
> On 5/15/2011 1:33 PM, rusi wrote:
>
> > On May 15, 10:07 am, Steven D'Aprano > +comp.lang.pyt...@pearwood.info>  wrote:
>
> >> I'm afraid I don't understand what you mean. Can you explain please, what
> >> properties of "first class booleans" do you think are missing from Python?
>
> Given the usual CS definition of 'first class object', all Python
> objects are first class. But that does not preclude other definitions.
>
> 
>
> What CS definition?

Perhaps your definition matches the wikipedia article:
http://en.wikipedia.org/wiki/First-class_object

And I am using the extended definition on the talk page:
http://en.wikipedia.org/wiki/Talk:First-class_object#Is_it_is.2C_or_is_it_aint.3F

[Evidently the arguments of this thread are repeatedly played out
elsewhere :-; ]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread James Mills
On Mon, May 16, 2011 at 3:41 PM, Littlefield, Tyler  wrote:
> Here's kind of what I want to prevent. I want to write a multi-player online
> game; everyone will essentually end up connecting to my server to play the
> game. I don't really like the idea of security through obscurity, but I
> wanted to prevent a couple of problems.
> 1) First I want to prevent people from hacking at the code, then using my
> server as a test for their new setups. I do not want someone to gain some
> extra advantage just by editing the code.
> Is there some other solution to this, short of closed-source?

As I mentioned before (which I don't think you quite got)...

Write your "game" for the "web".
Write is as a SaaS (Software as a Service) - even if it's free and open source.

cheers
James

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


Re: obviscating python code for distribution

2011-05-15 Thread Chris Angelico
On Mon, May 16, 2011 at 3:41 PM, Littlefield, Tyler  wrote:
> Here's kind of what I want to prevent. I want to write a multi-player online
> game; everyone will essentually end up connecting to my server to play the
> game. I don't really like the idea of security through obscurity, but I
> wanted to prevent a couple of problems.
> 1) First I want to prevent people from hacking at the code, then using my
> server as a test for their new setups. I do not want someone to gain some
> extra advantage just by editing the code.
> Is there some other solution to this, short of closed-source?

1) If you're worried about people getting hold of the code that's
running on your server, that's a server security issue and not a
Python obscurity issue (if they get the code, they can run it no
matter how obscured it is).

2) Was there a problem 2? :)

As James Mills said, just leave it on the server and then you don't
have to give out the source (and by "don't have to", I mean ethically,
legally, and technically).

You may want to give some thought to scaleability of your code; Google
told their staff to avoid Python for things that are going to get
hammered a lot (although it's possible that Google's idea of "a lot"
is five orders of magnitude more than you'll ever get!!). But if your
game world puts a hard limit on its own load (eg if players are on a
50x50 board and you know you can handle 2500 simultaneous players),
you won't have a problem.

Also, Python doesn't really cater to servers that want to have their
code updated on the fly; I'm sure you could work something out using a
dictionary of function objects, but otherwise you're stuck with
bringing the server down to do updates. That's considered normal in
today's world, but I really don't know why... downtime is SO last
century!

Chris Angelico
happily running servers on fully open source stacks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-15 Thread Littlefield, Tyler

>Write your "game" for the "web".
>Write is as a SaaS (Software as a Service) - even if it's free and 
open source.
I understood you loud and clear. And that makes a lot of assumptions on 
my game and the design. I don't really care to host this over the web. I 
want a
centralized server that would perform the logic, where I can offload the 
playing of sounds (through a soundpack that's already installed) to the 
client-side.
Not only that, but a lot of web technologies that would be used for this 
wouldn't really work, as I am doing this for the blind; Flash as well as 
a lot

of the popular setups are not very accessible.

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


Re: obviscating python code for distribution

2011-05-15 Thread Littlefield, Tyler

Hello:
I wanted to make the client in python, and the server possibly, though 
I'm not really sure on that. I was not worried about the code for the 
server being stolen, as much as I was worried about people tinkering 
with the client code for added advantages. Most of the logic can be 
handled by the server to prevent a lot of this, but there are still ways 
people could give themselves advantages by altering the client.


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


Re: obviscating python code for distribution

2011-05-15 Thread James Mills
On Mon, May 16, 2011 at 4:16 PM, Littlefield, Tyler  wrote:
> I understood you loud and clear. And that makes a lot of assumptions on my
> game and the design. I don't really care to host this over the web. I want a
> centralized server that would perform the logic, where I can offload the
> playing of sounds (through a soundpack that's already installed) to the
> client-side. Not only that, but a lot of web technologies that would be used
> for this wouldn't really work, as I am doing this for the blind; Flash as
> well as a lot of the popular setups are not very accessible.

Funny you should mention this "now" :)
I happen to be blind myself.

Yes I agree Flash is not very accessible (never has been).

Web Standards web apps and such however are quite
accessible!

cheers
James

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


Re: Converting a set into list

2011-05-15 Thread Peter Otten
Daniel Kluev wrote:

>> Both solutions seem to be equivalent in that concerns the number of
>> needed loop runs, but this two-step operation might require one less loop
>> over list1. The set&set solution, in contrary, might require one loop
>> while transforming to a set and another one for the & operation.
> 
> python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
> "l3 = list(set(l1) & set(l2))"
> 100 loops, best of 3: 2.19 msec per loop
> 
> python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)"
> "s=set(l2); l3 = [i for i in l1 if i in s]"
> 100 loops, best of 3: 2.45 msec per loop
> 
> python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
> "l3 = list(set(l1) & set(l2))"
> 10 loops, best of 3: 28 msec per loop
> 
> python -m timeit -s "l1 = range(1, 10); l2 = range(5, 15)"
> "s=set(l2); l3 = [i for i in l1 if i in s]"
> 10 loops, best of 3: 28.1 msec per loop
> 
> So even with conversion back into list set&set is still marginally faster.

If you are looking for speed, consider

s = set(l1)
s.intersection_update(l2)
l3 = list(s) 

$ python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)" 
"list(set(l1) & set(l2))"
100 loops, best of 3: 4 msec per loop

$ python -m timeit -s "l1 = range(1, 1); l2 = range(5000, 15000)" "s = 
set(l1); s.intersection_update(l2); list(s)"
100 loops, best of 3: 1.99 msec per loop


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