Re: Presentation software for Python code

2009-04-24 Thread alex23
On Apr 24, 4:23 pm, Michael Hoffman <4g4trz...@sneakemail.com> wrote:
> That looks like it would be perfect. Unfortunately it doesn't seem to
> work on my Windows laptop:
>
> I don't understand this. OpenGL Extensions Viewer says I have OpenGL 1.5
> and the glGenBuffers function.

That's a shame, if you feel like pursuing it you should report the
error to the pyglet devs, but I'd certainly understand if you didn't.

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


Re: What is the best framework or module in Python for a small GUI based application development?

2009-04-24 Thread CM
On Apr 22, 9:11 am, srinivasan srinivas 
wrote:
> Hi,
> Could you suggest me some modules in Python which can be used to develop GUI 
> based applications? and tell me which could be the best(in terms of 
> efficiency) one for a small GUI based application development?
>
> Thanks,
> Srini
>
>       Bollywood news, movie reviews, film trailers and more! Go 
> tohttp://in.movies.yahoo.com/

For browser-based stuff--that is, web apps--as far as I know the only
options for Python-based web app GUI is Pyjamas, a "python-to-
javascript
compiler and a web widget set", which would allow the GUI to be
written
in Python but then it translates it to javascript:
http://code.google.com/p/pyjamas/
And then you could use one of the aforementioned Python web
frameworks.


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


Re: Large data arrays?

2009-04-24 Thread Ole Streicher
Hi John,

John Machin  writes:
> The Morton layout wastes space if the matrix is not square. Your 100K
> x 4K is very non-square. Looks like you might want to use e.g. 25
> Morton arrays, each 4K x 4K.

What I found was that Morton layout shall be usable, if the shape is
rectangular and both dimensions are powers of two. But, all examples
were done with equal dimensions, so I am a bit confused here.

>From my access pattern, it would be probably better to combine 25 rows
into one slice and have one matrix where every cell contains 25 rows.

Are there any objections about that?

Best regards 

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


Re: sorting two corresponding lists?

2009-04-24 Thread Arnaud Delobelle
On Apr 24, 2:32 am, "Hans DushanthaKumar"
 wrote:
> Just being pedantic here :)
>
> [items[x] for x in [i for i in map(values.index, new_values)]]
>
> Is the same as
>
> [items[x] for x in map(values.index, new_values)]

It's also the same as

[items[x] for x in [values.index(i) for i in new_values]]

Which reduces to

[items[values.index(i)] for i in new_values]

(Although 'i' is not a good choice of variable as it represents a
value, not an index)

Anyway it doesn't work well if the 'values' list has repeated values,
e.g.

items = ['spam', 'eggs', 'wafer']
values = [3, 7, 3]

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


Re: Large data arrays?

2009-04-24 Thread Ole Streicher
Hi Nick,

Nick Craig-Wood  writes:
> I'd start by writing a function which took (x, y) in array
> co-ordinates and transformed that into (z) remapped in the Morton
> layout.

This removes the possibility to use the sum() and similar methods of
numpy. Implementing them myself is probably much worse than using
Numpys own.

> Alternatively you could install a 64bit OS on your machine and use
> my scheme!

Well: I am just the developer. Ofcourse I could just raise the
requirements to use my software, but I think it is good style to keep
them as low as possible. 

Best regards

Ole

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


Re: Regular expression to capture model numbers

2009-04-24 Thread Piet van Oostrum
> John Machin  (JM) wrote:

>JM> On Apr 24, 1:29 am, Piet van Oostrum  wrote:

>>> obj = re.compile(r'(?:[a-z]+[-0-9]|[0-9]+[-a-z]|-+[0-9a-z])[-0-9a-z]*', 
>>> re.I)

>JM> Understandable and maintainable, I don't think. Suppose that instead
>JM> the first character is limited to being alphabetic. You have to go
>JM> through the whole process of elaborating the possibilites again, and I
>JM> don't consider that process qualifies as "express[ing] complicated
>JM> conditions like that".

No, I don't think regular expressions are the best tool for these kind
of tests. I just wanted to show that it *could* be done. By the way,
your additional hypothetical requirement that the first character should
be alphabetic just makes it easier: only the first alternative remains.
But on the other hand, suppose you would have the requirement that the
pattern should not end in a hyphen then it becomes even uglier. Or when
there should never be two hyphens in a row, I wouldn't even think of
using a re, although theoretically it would be possible.

Translating these requirements into re's is not `composable'.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-04-24 Thread Peter Anderson

Sam (I presume),

Like you I am also in the process of learning to program in Python. I 
have been using Python 2.5.2 for quite some time but recently made the 
switch to 3.0.1. Why? Because I read an article where Guido van Rossum 
himself recommended that anyone starting out learning Python now was 
wasting their time if they didn't start with Python 3. Some folks on 
this list will tell you there is not much difference and that seems to 
be true but I pleased that I made the switch.


Now for your question about an IDE. I am presuming you are just 
beginning, perhaps done some programming in another language and 
probably using a Windows based PC. Given that there are some things I 
would recommend you stay away from (this will get the juices going :-) 
): Vi, Vim, Emacs and all those old fashioned UNIX/Linux based editors - 
they are just too hard and why bother anyway, there are much more 
civilised ways of proving your manhood. Eclipse is also an over-kill. I 
would recommend any of the popular text editors; most will recognise 
Python files.


I can tell you what I use:
*EditPad+* - http://www.editplus.com/index.html - A great general 
purpose text editor that has the additional benefit of clip libraries 
(what?). This might not seem important but it is a great time saver. A 
clip library is a text file of code snippets that when you 
'double-click' the required clip the editor inserts that code at the 
current cursor position. For example the following is a clip I use for 
the heading of a short script file:


#T=Short script
^# ^!.py
^# The purpose of this script is

def main():
{code here}

main()

After the clip has been inserted the cursor is positioned where the "^!" 
string is (before ".py") waiting for the script name to be inserted. You 
just build these clips to suit yourself. TextPad is another text editor 
with the same features.


The main drawback with EditPlus is that when you run a Python script 
from within EditPlus and that script uses stdin (eg. an input() 
function) the editor can't handle it and you get an error message. I 
overcome this problem by using easygui (http://easygui.sourceforge.net/) 
dialogs for text input; a piece of cake :-) . Another drawback is that 
EditPlus is shareware and you have to pay for it (US35).


*SciTE* - http://www.scintilla.org/SciTE.html - Scite is a very good 
little editor, it does not have the "bells and whistles" that editors 
like EditPlus have but it does recognise Python files and can run them 
from within the editor. It can also handle stdin (not that elegantly, 
but it works) so you don't need the easygui work-around and its free.


*IDLE* - the built-in Python IDE. I have it configured so that the 
editor panel loads first rather than the Python prompt. Everything runs 
in IDLE!


*PyScripter* - http://code.google.com/p/pyscripter/ - From the web site: 
"PyScripter is a free and open-source Python Integrated Development 
Environment (IDE) created with the ambition to become competitive in 
functionality with commercial Windows-based IDEs available for other 
languages." This is a true IDE with most of the things you would expect. 
However, I find that it gets a bit buggy at times. It does support 
Python 3 and is free so its worth a try.


There are several other good Python editor/IDE's but they require 
wxPython and it has not yet been made available in a Python 3 compatible 
version.


I hope that helps. Give me a reply if you want any more help with any of 
these things. Easygui is something that is really worth getting to know. 
A copy of Python (Second Edition) by Toby Donaldson (ISBN 13: 
978-0-321-58544-8) is another good thing to have when you are learning.


Regards,
Peter
--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Piet van Oostrum
> John Yeung  (JY) wrote:

>JY> It takes care of the duplicates, but so does your initial solution,
>JY> which I like best:

>>> sorted(a)==sorted(b)

>JY> This is concise, clear, and in my opinion, the most Pythonic.  It may
>JY> well even be the fastest.  (If you didn't have to match up the numbers
>JY> of duplicates, the set solution would be most Pythonic and probably
>JY> fastest.)

But it may fail if the list cannot be sorted because it contains
incomparable elements:

>>> a = [1, 2, 3+4j]
>>> b = [2, 3+4j, 1]
>>> set(a) == set(b)
True
>>> sorted(a)==sorted(b)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: no ordering relation is defined for complex numbers

In Python 3 there are even more incomparable objects pairs.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: getter and setter and list appends

2009-04-24 Thread Piet van Oostrum
> dasacc22  (d) wrote:

>d> Ah thank you for clarifying, I did confuse instance and class
>d> attributes from creating the list in the class def. I actually just
>d> spiffed up that class to represent a portion of a much larger class
>d> that needs getter and setter for children. Doing as you said fixed my
>d> problem, heres the code as reference for w/e

>d> class Widget(object):
>d> _children = None
>d> _parent = None

You still have them as class variables here. Now they are only used as
defaults because you assign to them in the instances so the instance
variables will be created then. But I think it is still confusing to
have these class variables here that you never use as such. Maybe this
is some leftover from Java experience where you do declare instance
variables at the class level?

>d> def __init__(self, parent=None):
>d> self.children = []
>d> self.parent = parent

>d> @property
>d> def children(self):
>d> return self._children

>d> @children.setter
>d> def children(self, obj):
>d> self._children = obj

What is the added value of using a property for the children attribute?
Why not just use an instance variable directly? Also a Java inheritance?

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why can function definitions only use identifiers, and not attribute references or any other primaries?

2009-04-24 Thread Marco Mariani

Scott David Daniels wrote:


I am afraid it will make it too easy to define functions in other
modules remotely, a tempting sharp stick to poke your eye out with.


It's not very hard at the moment, and I don't see lots of eyes flying 
by. I don't know about Ruby where monkeypatching seems to be common 
practice, though.



Imagine debugging a pile of code that includes a module with:
import random
def random.random():
return .42


No need to imagine. I can do the same, one line shorter:

>>> import random
>>> random.random = lambda: .42

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


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Steven D'Aprano
On Fri, 24 Apr 2009 06:50:01 +, Lie Ryan wrote:

> Gerhard Häring wrote:
>> len() make it clear that the argument is a sequence.
> 
> Not necessarily. 

len() works on dicts and sets, and they're not sequences.


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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Steven D'Aprano
On Thu, 23 Apr 2009 21:51:42 -0400, Esmail wrote:

>> set(a) == set(b)# test if a and b have the same elements
>> 
>> # check that each list has the same number of each element # i.e.   
>> [1,2,1,2] == [1,1,2,2], but [1,2,2,2] != [1,1,1,2] for elem in set(a):
>>   a.count(elem) == b.count(elem)
> 
> Ah .. this part would take care of different number of duplicates in the
> lists. Cool.

At significant cost of extra work.

Counting the number of times a single element occurs in the list is O(N). 
Counting the number of times every element occurs in the list is O(N**2). 
Sorting is O(N*log N), so for large lists, sorting will probably be much 
cheaper.


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


Re: Why can function definitions only use identifiers, and not attribute references or any other primaries?

2009-04-24 Thread Steven D'Aprano
On Thu, 23 Apr 2009 10:48:57 -0700, Scott David Daniels wrote:

> I am afraid it will make it too easy to define functions in other
> modules remotely, a tempting sharp stick to poke your eye out with. 

It's not terribly difficult to do so already:

>>> def spam():
... return "spam spam spam"
...
>>> import math
>>> math.spam = spam
>>> math.spam()
'spam spam spam'


> Note
> also, that it will not be so easy to find the definition of a function
> provided as a argument to a failing function.  Right now you can get the
> function name and (with a bit more effort) its module. Imagine debugging
> a pile of code that includes a module with:
>  import random
>  def random.random():
>  return .42

Easy-peasy.

>>> import random
>>> random.random = lambda: 0.42
>>>
>>> random.random()
0.41998
>>> random.random.__name__
''
>>> random.random.__module__
'__main__'


Sure, if somebody wants to really work at it, they could create a 
function that looks exactly like the original, including claiming to come 
from the same module, but that's possible now anyway.

I don't think the proposed syntax is useful because it doesn't actually 
gain us anything. Currently, you add a function to a class at class 
creation time:

class Spam(object):
def spam(self):
return "spam spam spam"

Adding functions to a class after the class already exists is rare, but 
not unheard of. Currently you can do this:

def ham(self):
return "ham is not spam"

Spam.ham = ham
del ham  # if you can be bothered


And you're done. The proposal gives us this:

class Spam(object):
pass  # Need to have a class before you can add methods to it.

def Spam.spam(self):
return "spam spam spam"

def Spam.ham(self):
return "ham is not spam"



Whatever benefit there might be from doing this, it's so minor I don't 
think it's worth the effort to implement it. Unlike decorators, I'd be 
surprised if it opens the door to bigger and better things.



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


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Steven D'Aprano
On Thu, 23 Apr 2009 17:18:25 +0800, Leo wrote:

>> There's also the performance issue. I might have a sequence-like
>> structure where calling len() takes O(N**2) time, (say, a graph) but
>> calling __nozero__ might be O(1). Why defeat the class designer's
>> optimizations?
> 
> Is that true?
> Calling len() actually traverses the whole list?

Not for built-in lists, but for sequences created by somebody else, who 
knows what it does?



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


wxpython notebook oddness

2009-04-24 Thread Lawson English

Can anyone tell me why these two behave differfently?

http://pastebin.com/m57bee079 vs  http://pastebin.com/m3c044b29


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


Raw command line arguments

2009-04-24 Thread Enchanter
How to pass the raw command line arguments to the python?

Such as:

 mypython.py  txt -c "Test Only" {Help}


The arguments I hope to get is:

  txt -c "Test Only" {Help}   -- Keep the
quotation marks in the arguments.

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


Re: unicode(lString, "utf8") vs. lString.encode("utf8") vs. ur"jakiś tekst"

2009-04-24 Thread Jax
Sorry, my mistake.
My interntion was post this message on pl.comp.lang.python.

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


Re: Raw command line arguments

2009-04-24 Thread Chris Rebert
On Fri, Apr 24, 2009 at 2:40 AM, Enchanter  wrote:
> How to pass the raw command line arguments to the python?
>
> Such as:
>
>     mypython.py  txt -c "Test Only" {Help}
>
>
> The arguments I hope to get is:
>
>              txt -c "Test Only" {Help}               -- Keep the
> quotation marks in the arguments.

Remember that the quotes are parsed by the shell before python ever
receives the arguments, so you have to deal with it in whatever is
calling python.

Recall/note the differences between:
rm foo bar #delete foo and delete bar
rm "foo bar" #delete one file with a space in its name but no quotes in its name
rm 'foo"bar"baz' #delete one file with double-quotes in its name
rm "foo\"bar\"baz" #delete the same file as in the previous example

Therefore, you need to invoke the script differently to take account
of the shell's quote processing by adding another set of quotes, like
so:
mypython.py  txt -c '"Test Only"' {Help}
#or alternatively:
mypython.py  txt -c "\"Test Only\"" {Help}

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


Convert numpy.ndarray into "normal" array

2009-04-24 Thread Johannes Bauer
Hi group,

I'm confused, kind of. The application I'm writing currently reads data
from a FITS file and should display it on a gtk window. So far I have:

[...]
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
pb_pixels = pb.get_pixels_array()

print(type(fits_pixels))
print(type(pb_pixels))

which gives




So now I want to copy the fits_pixels -> pb_pixels. Doing

pb_pixels = fits_pixels

works and is insanely fast, however the picture looks all screwed-up
(looks like a RGB picture of unititialized memory, huge chunks of 0s
interleaved with lots of white noise).

Doing the loop:

for x in range(width):
for y in range(height):
pb_pixels[y, x] = fits_pixels[y, x]

works as expected, but is horribly slow (around 3 seconds for a 640x480
picture).

So now I've been trying to somehow convert the array in a fast manner,
but just couldn't do it. What exactly is "array" anyways? I know
"array.array", but that's something completely different, right? Does
anyone have hints on how to go do this?

Kind regards,
Johannes

-- 
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
 -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
 <48d8bf1d$0$7510$54022...@news.sunrise.ch>
--
http://mail.python.org/mailman/listinfo/python-list


if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread GC-Martijn
Hello,

I'm trying to do a if statement with a function inside it.
I want to use that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla

--
The long way
t = Test()
if (t == 'Vla':
print t # must contain Vla


Greetings,
GCMartijn
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Steven D'Aprano
On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:

> Hello,
> 
> I'm trying to do a if statement with a function inside it. I want to use
> that variable inside that if loop , without defining it.
> 
> def Test():
> return 'Vla'
> 
> I searching something like this:
> 
> if (t = Test()) == 'Vla':
> print t # Vla
> 
> or
> 
> if (t = Test()):
> print t # Vla

Fortunately, there is no way of doing that with Python. This is one 
source of hard-to-debug bugs that Python doesn't have.


> -- The long way
> t = Test()
> if (t == 'Vla':
> print t # must contain Vla


What's wrong with that?



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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Chris Rebert
On Fri, Apr 24, 2009 at 3:00 AM, GC-Martijn  wrote:
> Hello,
>
> I'm trying to do a if statement with a function inside it.
> I want to use that variable inside that if loop , without defining it.
>
> def Test():
>    return 'Vla'
>
> I searching something like this:
>
> if (t = Test()) == 'Vla':
>    print t # Vla
>
> or
>
> if (t = Test()):
>    print t # Vla
>
> --
> The long way
> t = Test()
> if (t == 'Vla':
>    print t # must contain Vla

Disregarding some ugly hacks, Python does not permit assignment in
expressions, so what you're asking for is not possible.
For the goods of readability, prevention of errors, and simplicity,
Python forces you to do it the "long way" (the Right Way(tm) if you
ask most Python partisans).

If you could explain your situation and the context of your question
in greater detail, someone might be able to suggest an alternate
structure for your code which obviates your desire for such a
construct.

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread GC-Martijn
On 24 apr, 12:11, Steven D'Aprano  wrote:
> On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:
> > Hello,
>
> > I'm trying to do a if statement with a function inside it. I want to use
> > that variable inside that if loop , without defining it.
>
> > def Test():
> >     return 'Vla'
>
> > I searching something like this:
>
> > if (t = Test()) == 'Vla':
> >     print t # Vla
>
> > or
>
> > if (t = Test()):
> >     print t # Vla
>
> Fortunately, there is no way of doing that with Python. This is one
> source of hard-to-debug bugs that Python doesn't have.
>
> > -- The long way
> > t = Test()
> > if (t == 'Vla':
> >     print t # must contain Vla
>
> What's wrong with that?
>
> --
> Steven- Tekst uit oorspronkelijk bericht niet weergeven -
>
> - Tekst uit oorspronkelijk bericht weergeven -

Nothing is wrong with it , but it cost more lines (= more scrolling)
When possible I want to keep my code small.
--
http://mail.python.org/mailman/listinfo/python-list


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Paul Rubin
Steven D'Aprano  writes:
> len() works on dicts and sets, and they're not sequences.

Of course dicts and sets are sequences.  But there are also sequences
on which len doesn't work.

You could use:  sum(1 for x in seq)
Of course iterating through seq may have undesired side effects.
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Paul Rubin
Chris Rebert  writes:
> Python forces you to do it the "long way" (the Right Way(tm) if you
> ask most Python partisans).
> 
> If you could explain your situation and the context of your question
> in greater detail, someone might be able to suggest an alternate
> structure for your code which obviates your desire for such a
> construct.

One very common situation is matching something against a series of
regexps, and "ugly hacks" often end up being more attractive than "the
long way".

If you want to do it "the pointy headed way", start with the article

http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw command line arguments

2009-04-24 Thread Dave Angel

Enchanter wrote:

How to pass the raw command line arguments to the python?

Such as:

 mypython.py  txt -c "Test Only" {Help}


The arguments I hope to get is:

  txt -c "Test Only" {Help}   -- Keep the
quotation marks in the arguments.


  
As Chris has said, the shell (and the C runtime) preprocesses the line 
before python ever sees it.  However, if you're on Windows, there is a 
function GetCommandLine, located in Kernel32.dll, which I *think* keeps 
the raw bytes typed by the user.  Clearly, that would be a non-portable 
answer, but here's some samples if you want to try it:


import sys
print sys.argv#this one loses the quotes

import ctypes
#print ctypes.windll.kernel32.GetModuleHandleA
#hdl = ctypes.windll.kernel32.GetModuleHandleA(0)
#print hdl

func = ctypes.windll.kernel32.GetCommandLineA
print func
func.restype = ctypes.c_char_p

cmd = ctypes.windll.kernel32.GetCommandLineA()
print cmd   #this one gives a single string, such as the one below:

"C:\ProgFiles\Python26\python.exe"  
"M:\Programming\Python\sources\dummy\args.py"  txt -c "Test Only" (Help)


If you do go this route, but still want to be portable, you could make 
this code conditional on platform, then document the user to use 
escaping on Linux and Apple, while you do this approach for Windows.



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


PDB break

2009-04-24 Thread Ricardo Aráoz
Hi, I need to track where a certain condition is met in a program.
Checking on pdb docs I find the break statement :

b(reak) [[/filename/:]/lineno/ | /function/[, /condition/]]

But it requires me to name a line/function where my condition is tested.
Now there are far too many places in a project where this condition may
be set to true, and I might overlook some (and it would take an awful
lot of time to identify them all). Is there a statement that allows me
to stop execution when a condition is met regardless of where this happens?

Thx.

Ricardo.

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

John Yeung wrote:

 so does your initial solution,
which I like best:


sorted(a)==sorted(b)


This is concise, clear, and in my opinion, the most Pythonic.  It may
well even be the fastest.  


Great .. I can live with that :-)

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


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Peter Otten
Paul Rubin wrote:

> Steven D'Aprano  writes:
>> len() works on dicts and sets, and they're not sequences.
> 
> Of course dicts and sets are sequences.  But there are also sequences
> on which len doesn't work.

That was my intuition, too. But Python takes a different stance:

>>> from collections import *
>>> for obj in [(), [], {}, set()]:
... print(("%r: " % (obj,)) + ", ".join(a.__name__ for a in [Iterable,
Container, Sequence] if isinstance(obj, a)))
...
(): Iterable, Container, Sequence
[]: Iterable, Container, Sequence
{}: Iterable, Container
set(): Iterable, Container

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


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Steven D'Aprano
On Fri, 24 Apr 2009 03:22:50 -0700, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> len() works on dicts and sets, and they're not sequences.
> 
> Of course dicts and sets are sequences.

Dicts and sets are explicitly described as "other containers":

http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-
list-tuple-buffer-xrange

Note that addition is included in the table of sequence operations, but 
neither dicts nor sets support it:

>>> {} + {}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

Nor do they support slicing.


> But there are also sequences on which len doesn't work.
>
> You could use:  sum(1 for x in seq)
> Of course iterating through seq may have undesired side effects.

It's also not guaranteed to terminate.

Well, technically no user-defined function is guaranteed to terminate, 
but you know what I mean :)




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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

MRAB wrote:


You could use Raymond Hettinger's Counter class:

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

on both lists and compare them for equality.


thanks for the pointer, I'll study the code provided.

Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread bearophileHUGS
Arnaud Delobelle:
> Thanks to the power of negative numbers, you only need one dict:
>
> d = defaultdict(int)
> for x in a:
>     d[x] += 1
> for x in b:
>     d[x] -= 1
> # a and b are equal if d[x]==0 for all x in d:
> not any(d.itervalues())

Very nice, I'll keep this for future use.
Someday I'll have to study this new new kind of numbers that can
represent borrowed items too.

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


HTTP Authentication using urllib2

2009-04-24 Thread Lakshman
I am trying to authenticate using urllib2. The basic authentication
works if I hard code authheaders.
def is_follows(follower, following):

theurl = 'http://twitter.com/friendships/exists.json?
user_a='+follower+'&user_b='+following
username = 'uname1'
password = 'pwd1'

handle = urllib2.Request(theurl)

authheader =  "Basic %s" % base64.encodestring('%s:%s' %
(username, password))
handle.add_header("Authorization", authheader)

try:
return simplejson.load(urllib2.urlopen(handle))
except IOError, e:
print "Something wrong. This shouldnt happen"


I am trying to refactor this code into how urllib2 expects to do. But
I am getting an error.

def is_follows(follower, following):

url = 'http://twitter.com/friendships/exists.json?user_a=%s&user_b=
%s' %(
follower, following)


#Authenticate once for all
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='',
  uri='http://twitter.com',
  user='scorpion032',
  passwd='123456')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

try:
return simplejson.load(urllib2.urlopen(url))
except:
print "Something wrong. This shouldnt happen"
return False

Can U please point what I am missing. As I understand, the Auth
Headers are put appropriately in either cases, but the latter one
doesnt work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert numpy.ndarray into "normal" array

2009-04-24 Thread MRAB

Johannes Bauer wrote:

Hi group,

I'm confused, kind of. The application I'm writing currently reads data
from a FITS file and should display it on a gtk window. So far I have:

[...]
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
pb_pixels = pb.get_pixels_array()

print(type(fits_pixels))
print(type(pb_pixels))

which gives




So now I want to copy the fits_pixels -> pb_pixels. Doing

pb_pixels = fits_pixels


This simply makes pb_pixels refer to the same object as fits_pixels. It
doesn't copy the values into the existing pb_pixels object.


works and is insanely fast, however the picture looks all screwed-up
(looks like a RGB picture of unititialized memory, huge chunks of 0s
interleaved with lots of white noise).

Doing the loop:

for x in range(width):
for y in range(height):
pb_pixels[y, x] = fits_pixels[y, x]

works as expected, but is horribly slow (around 3 seconds for a 640x480
picture).


This does copy the values into the existing pb_pixels object.


So now I've been trying to somehow convert the array in a fast manner,
but just couldn't do it. What exactly is "array" anyways? I know
"array.array", but that's something completely different, right? Does
anyone have hints on how to go do this?


You should be able to copy the values using array slicing, something
like:

pb_pixels[:] = fits_pixels

or:

pb_pixels[:, :] = fits_pixels

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Ulrich Eckhardt
Steven D'Aprano wrote:
> On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:
>> t = Test()
>> if (t == 'Vla':
>> print t # must contain Vla
> 
> 
> What's wrong with that?

It unnecessarily injects the name 't' into the scope.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread MRAB

GC-Martijn wrote:

On 24 apr, 12:15, Chris Rebert  wrote:

On Fri, Apr 24, 2009 at 3:00 AM, GC-Martijn  wrote:

Hello,
I'm trying to do a if statement with a function inside it.
I want to use that variable inside that if loop , without defining it.
def Test():
   return 'Vla'
I searching something like this:
if (t = Test()) == 'Vla':
   print t # Vla
or
if (t = Test()):
   print t # Vla
--
The long way
t = Test()
if (t == 'Vla':
   print t # must contain Vla

Disregarding some ugly hacks, Python does not permit assignment in
expressions, so what you're asking for is not possible.
For the goods of readability, prevention of errors, and simplicity,
Python forces you to do it the "long way" (the Right Way(tm) if you
ask most Python partisans).

If you could explain your situation and the context of your question
in greater detail, someone might be able to suggest an alternate
structure for your code which obviates your desire for such a
construct.


Oke, thanks.
I will use the (correct) long way.


It's possible in C, but sometimes you might write '=' where you intended
'=='. It happens. I've done it myself. :-(

Sometimes it's an annoying restriction, but it does reduce bugs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Arnaud Delobelle
On Apr 24, 7:12 am, bearophileh...@lycos.com wrote:
[...]
> Another solution is to use frequency dicts, O(n):
>
> from itertools import defaultdict
> d1 = defaultdict(int)
> for el in a:
>     d1[el] += 1
> d2 = defaultdict(int)
> for el in b:
>     d2[el] += 1
> d1 == d2

Thanks to the power of negative numbers, you only need one dict:

d = defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
# a and b are equal if d[x]==0 for all x in d:
not any(d.itervalues())

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread GC-Martijn
On 24 apr, 12:15, Chris Rebert  wrote:
> On Fri, Apr 24, 2009 at 3:00 AM, GC-Martijn  wrote:
> > Hello,
>
> > I'm trying to do a if statement with a function inside it.
> > I want to use that variable inside that if loop , without defining it.
>
> > def Test():
> >    return 'Vla'
>
> > I searching something like this:
>
> > if (t = Test()) == 'Vla':
> >    print t # Vla
>
> > or
>
> > if (t = Test()):
> >    print t # Vla
>
> > --
> > The long way
> > t = Test()
> > if (t == 'Vla':
> >    print t # must contain Vla
>
> Disregarding some ugly hacks, Python does not permit assignment in
> expressions, so what you're asking for is not possible.
> For the goods of readability, prevention of errors, and simplicity,
> Python forces you to do it the "long way" (the Right Way(tm) if you
> ask most Python partisans).
>
> If you could explain your situation and the context of your question
> in greater detail, someone might be able to suggest an alternate
> structure for your code which obviates your desire for such a
> construct.
>
> Cheers,
> Chris
> --
> I have a blog:http://blog.rebertia.com- Tekst uit oorspronkelijk bericht niet 
> weergeven -
>
> - Tekst uit oorspronkelijk bericht weergeven -

Oke, thanks.
I will use the (correct) long way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

Thanks all, after reading all the posting and suggestions for
alternatives, I think I'll be going with

sorted(a)==sorted(b)

it seems fast, intuitive and clean and can deal with
duplicates too.

Best,
Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

Piet van Oostrum wrote:

John Yeung  (JY) wrote:



JY> It takes care of the duplicates, but so does your initial solution,
JY> which I like best:



sorted(a)==sorted(b)



JY> This is concise, clear, and in my opinion, the most Pythonic.  It may
JY> well even be the fastest.  (If you didn't have to match up the numbers
JY> of duplicates, the set solution would be most Pythonic and probably
JY> fastest.)


But it may fail if the list cannot be sorted because it contains
incomparable elements:


Ah .. good point .. something I had not considered. Lucky for me in
this case it's not an issue, but something I'll keep in mind for the
future.

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


unicode(lString, "utf8") vs. lString.encode("utf8") vs. ur"jakiś tekst"

2009-04-24 Thread Jax
Witam

Zakładam, że kod Pythona w drugiej lini ma:
# -*- coding: utf-8 -*-

oraz gdzieś na początku:
reload(sys)
sys.setdefaultencoding('utf8')

No i mam takie pytania odnośnie unicode w utf8:

Czy obie poniższe linie dają ten sam efekt, czyli obiekt unicode zakodowany w
utf8?
lString = unicode(lString, "utf8")
lString = lString.encode("utf8")

Konkretnie chodzi mi czy aby mieć obiekt unicode zakodowany w utf8 muszę robić
coś takiego:
lString = unicode(lString.decode("ISO-8859-15").encode("utf8"), "utf8")
czy może wystarczy:
lString = lString.decode("ISO-8859-15").encode("utf8")

Dodatkowo mam pytanie: Czy aby mieć ze stringu podanego w kodzie pythona obiekt
unicode zakodowany w utf8 zawsze muszę robić:
lString = unicode("jakiś tekst", "utf8")
czy może wystarczy
lString = ur"jakiś tekst"

Pytam, bo ciągłe klepanie unicode(xxx, "utf8") jest męczące.

z góry dzięki

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


Re: Presentation software for Python code

2009-04-24 Thread Sebastian Wiesner


> I'm willing to consider TeX- and HTML-based approaches.

I can recommend latex with the beamer package.  It doesn't directly support 
formatting of code snippets, but the pygments syntax highlighter comes with 
a Latex formatter.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)

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


Re: JSON and Firefox sessionstore.js

2009-04-24 Thread Дамјан Георгиевски
> Unless I'm badly mistaken, the Firefox sessionstore.js file is
> supposed to be JSON.
...
> If it matters, I'm using Firefox 2.0.0.5 under Linux.

maybe it can be parsed with PyYAML?


-- 
дамјан ( http://softver.org.mk/damjan/ )

Well when _I_ was in school, I had to run Netscape on HP/UX, displayed on my 
local X Server running on a Windows 3.1 box. Displayed over a 2400 baud 
modem. Uphill. Both ways. In the rain. With NOBODY to hold my hands. Because 
the life of the geek is a lonely life.
- aclarke on /.

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


Re: Numpy Performance

2009-04-24 Thread timlash
Thanks for your replies.

@Peter - My arrays are not sparse at all, but I'll take a quick look
as scipy.  I also should have mentioned that my numpy arrays are of
Object type as each data point (row) has one or more text labels for
categorization.

@Robert - Thanks for the comments about how numpy was optimized for
bulk transactions.  Most of the processing I'm doing is with
individual elements.

Essentially, I'm testing tens of thousands of scenarios on a
relatively small number of test cases.  Each scenario requires all
elements of each test case to be scored, then summarized, then sorted
and grouped with some top scores captured for reporting.

It seems like I can either work toward a procedure that features
indexed categorization so that my arrays are of integer type and a
design that will allow each scenario to be handled in bulk numpy
fashion, or expand RectangularArray with custom data handling methods.

Any other recommended approaches to working with tabular data in
Python?

Cheers,

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


Python-URL! - weekly Python news and links (Apr 24)

2009-04-24 Thread Gabriel Genellina
QOTW:  "... [C]alling Python Object-Orientated is a bit of an
insult :-).  I would say that Python is Ego-Orientated, it allows
me to do what I want." - Martin P. Hellwig


April 25: Python Bug Day
A perfect opportunity to get involved in Python development, bring your
own issues to attention, discuss them and (hopefully) resolve them
together with the core developers.

http://mail.python.org/pipermail/python-announce-list/2009-April/007401.html

Surprising behavior of `and` with lists:
http://groups.google.com/group/comp.lang.python/t/69f0ff9adbdbbfbe/

Best way to compare two binary files:
http://groups.google.com/group/comp.lang.python/t/70b4ad0605287c28/

Determine if two lists contains the same elements (with duplicates):
http://groups.google.com/group/comp.lang.python/t/3ecc64c918ff776e/

How to transparently add modules to an installed package (without
modifying it):
http://groups.google.com/group/comp.lang.python/t/435bdf86030acc20/

What's a good strategy to write Python code aimed at being rewritten in
C later?
http://groups.google.com/group/comp.lang.python/t/7affed04edcf521c/

python.exe not found - how to fix PATH issues on Windows:
http://groups.google.com/group/comp.lang.python/t/421756cc7875c8b0/

Python, Basic, nostalgia, and goto considered harmful (long thread):
http://groups.google.com/group/comp.lang.python/t/ce6900e499334046/

How to represent table joins in a non-relational database (e.g. BigTable
in Google App Engine)
http://groups.google.com/group/comp.lang.python/t/786770da42168af3/

A mathematical puzzle: express numbers as sum of squares
http://groups.google.com/group/comp.lang.python/t/358bc4893cffc0f4/

This time, the man bites the python:
http://groups.google.com/group/comp.lang.python/t/b2ff4307aca821d5/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channe

Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Marco Mariani

Ulrich Eckhardt wrote:


t = Test()
if (t == 'Vla':
print t # must contain Vla


What's wrong with that?


It unnecessarily injects the name 't' into the scope.


Since there is no concept in Python of a scope local to block 
statements, I don't understant what you would like to happen instead.

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-04-24 Thread Paul McGuire
On Apr 24, 5:00 am, GC-Martijn  wrote:
> Hello,
>
> I'm trying to do a if statement with a function inside it.
> I want to use that variable inside that if loop , without defining it.
>
> def Test():
>     return 'Vla'
>
> I searching something like this:
>
> if (t = Test()) == 'Vla':
>     print t # Vla
>

Here is a thread from 3 weeks ago on this very topic, with a couple of
proposed solutions.

http://groups.google.com/group/comp.lang.python/browse_frm/thread/9f8e79fa28d69905/e934c73ee3c2dbc2?hl=en&q=

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


Failed to build these modules:_ctypes

2009-04-24 Thread PS
Hello all

I can't install neither python 2.6.1 nor 2.6.2 because an error during
compilation of _ctypes module, I don't need the module but I don't
know how to instruct to skip it.

The plattform is Suse 11.0

The steps I performed are the following:

./configure  --prefix $HOME/app/Python-2.6.2
make

The last command from make with its error is the following

gcc -pthread -shared build/temp.linux-i686-2.6/home/ps/soft/
Python-2.6.2/Modules/_ctypes/_ctypes.o build/temp.linux-i686-2.6/home/
ps/soft/Python-2.6.2/Modules/_ctypes/callbacks.o build/temp.linux-
i686-2.6/home/ps/soft/Python-2.6.2/Modules/_ctypes/callproc.o build/
temp.linux-i686-2.6/home/ps/soft/Python-2.6.2/Modules/_ctypes/
stgdict.o build/temp.linux-i686-2.6/home/ps/soft/Python-2.6.2/Modules/
_ctypes/cfield.o build/temp.linux-i686-2.6/home/ps/soft/Python-2.6.2/
Modules/_ctypes/malloc_closure.o build/temp.linux-i686-2.6/home/ps/
soft/Python-2.6.2/Modules/_ctypes/libffi/src/prep_cif.obuild/
temp.linux-i686-2.6/home/ps/soft/Python-2.6.2/Modules/_ctypes/libffi/
src/x86/ffi.o build/temp.linux-i686-2.6/home/ps/soft/Python-2.6.2/
Modules/_ctypes/libffi/src/x86/sysv.o -L/home/ps/app/Python-2.6.2/lib -
L/usr/local/lib -o build/lib.linux-i686-2.6/_ctypes.so
*** WARNING: renaming "_ctypes" since importing it failed: build/
lib.linux-i686-2.6/_ctypes.so: undefined symbol: ffi_prep_cif_machdep

Failed to find the necessary bits to build these modules:
bsddb185   dl imageop
sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for
the module's name.


Failed to build these modules:
_ctypes

running build_scripts

any idea?

Thanks in advance
Pablo
--
http://mail.python.org/mailman/listinfo/python-list


Re: getter and setter and list appends

2009-04-24 Thread dasacc22
On Apr 24, 4:04 am, Piet van Oostrum  wrote:
> > dasacc22  (d) wrote:
> >d> Ah thank you for clarifying, I did confuse instance and class
> >d> attributes from creating the list in the class def. I actually just
> >d> spiffed up that class to represent a portion of a much larger class
> >d> that needs getter and setter for children. Doing as you said fixed my
> >d> problem, heres the code as reference for w/e
> >d> class Widget(object):
> >d>     _children = None
> >d>     _parent = None
>
> You still have them as class variables here. Now they are only used as
> defaults because you assign to them in the instances so the instance
> variables will be created then. But I think it is still confusing to
> have these class variables here that you never use as such. Maybe this
> is some leftover from Java experience where you do declare instance
> variables at the class level?
>
> >d>     def __init__(self, parent=None):
> >d>         self.children = []
> >d>         self.parent = parent
> >d>     @property
> >d>     def children(self):
> >d>         return self._children
> >d>     @children.setter
> >d>     def children(self, obj):
> >d>         self._children = obj
>
> What is the added value of using a property for the children attribute?
> Why not just use an instance variable directly? Also a Java inheritance?
>
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p...@vanoostrum.org

Hi, yes, you are right, this is from previous experience, and thank
you for bringing this out. It would be better suited to move those
class variables to a comment to stay comfortable perhaps or eliminate
them altogether.

The property method of parent and children actually calls a
_set_as_parent() and _set_as_child() method after setting the private
variable to pack the object for display purposes so that children can
be detached from the parent (becoming its own parent) as a gui event.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert numpy.ndarray into "normal" array

2009-04-24 Thread Johannes Bauer
MRAB schrieb:

>> 
>> 
>>
>> So now I want to copy the fits_pixels -> pb_pixels. Doing
>>
>> pb_pixels = fits_pixels
>>
> This simply makes pb_pixels refer to the same object as fits_pixels. It
> doesn't copy the values into the existing pb_pixels object.

Oh okay, I was thinking of C++ std::vector which behaves
differently :-/ Switching between languages back and forth is not
something I'm good in, appearently.

> You should be able to copy the values using array slicing, something
> like:
> 
> pb_pixels[:] = fits_pixels
> 
> or:
> 
> pb_pixels[:, :] = fits_pixels

OK, I hadn't been familiar with that syntax at all - need to catch up
reading on this.

However, it doesn't work (altough probably for another reason):

Traceback (most recent call last):
  File "./guiclient.py", line 433, in on_Result
self.__updateresult()
  File "./guiclient.py", line 385, in __updateresult
pb_pixels[:, :] = fits_pixels
TypeError: Array can not be safely cast to required type

I guess Python fears truncation. However I ensure in advance the values
won't be truncated. How can I convince Python that it may safely assume
that is true?

Kind regards,
Johannes

-- 
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
 -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
 <48d8bf1d$0$7510$54022...@news.sunrise.ch>
--
http://mail.python.org/mailman/listinfo/python-list


Superclass initialization

2009-04-24 Thread Ole Streicher
Hi again,

I am trying to initialize a class inherited from numpy.ndarray:

from numpy import ndarray

class da(ndarray):
def __init__(self, mydata):
ndarray.__init__(self, 0)
self.mydata = mydata

When I now call the constructor of da:
da(range(100))

I get the message:

ValueError: sequence too large; must be smaller than 32

which I do not understand. This message is generated by the
constructor of ndarray, but the ndarray constructor
(ndarray.__init__()) has only "0" as argument, and calling
"ndarray(0)" directly works perfect.

In the manual I found that the constructor of a superclass is not
called implicitely, so there should be no other call to
ndarray.__init__() the the one in my __init__ method.

I am now confused on where does the call to ndarray come from. How do
I correct that?

Best regards

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


Re: Superclass initialization

2009-04-24 Thread Steven D'Aprano
On Fri, 24 Apr 2009 16:04:00 +0200, Ole Streicher wrote:

> I get the message:
> 
> ValueError: sequence too large; must be smaller than 32
> 
> which I do not understand. This message is generated by the constructor
> of ndarray, but the ndarray constructor (ndarray.__init__()) has only
> "0" as argument, and calling "ndarray(0)" directly works perfect.


Perhaps you should post the full trace back instead of just the final 
line.


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


Re: Superclass initialization

2009-04-24 Thread Arnaud Delobelle
On Apr 24, 3:04 pm, Ole Streicher  wrote:
> Hi again,
>
> I am trying to initialize a class inherited from numpy.ndarray:
>
> from numpy import ndarray
>
> class da(ndarray):
>     def __init__(self, mydata):
>         ndarray.__init__(self, 0)
>         self.mydata = mydata
>
> When I now call the constructor of da:
> da(range(100))
>
> I get the message:
>
> ValueError: sequence too large; must be smaller than 32
>
> which I do not understand. This message is generated by the
> constructor of ndarray, but the ndarray constructor
> (ndarray.__init__()) has only "0" as argument, and calling
> "ndarray(0)" directly works perfect.
>
> In the manual I found that the constructor of a superclass is not
> called implicitely, so there should be no other call to
> ndarray.__init__() the the one in my __init__ method.
>
> I am now confused on where does the call to ndarray come from. How do
> I correct that?
>
> Best regards
>
> Ole

numpy.ndarray has a __new__ method (and no __init__).  I guess this is
the one you should override.  Try:

class da(ndarray):
def __new__(cls, mydata):
return ndarray.__new__(cls, 0)
def __init__(self, mydata):
self.mydata = mydata

--
Arnaud


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


Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread Grant Edwards
On 2009-04-23, MRAB  wrote:
> tinn...@isbd.co.uk wrote:
>> It seems to me that mailbox.mbox.add() sets the access time of a mbox
>> file as well as the modification time.  This is not good for MUAs that
>> detect new mail by looking to see if the access time is before the
>> modification time.
>> 
>> Have I done something wrong somewhere or is mailbox.mbox.add() really
>> as broken as it would appear?
>> 
> [snip]
> The access time is the time it was last accessed, ie read or modified.

Usually.

> The modification time is the time it was last modified.

Usually.

> The access time can never be before the modification time because it
> must be accessed in order to be modified!

Nonsense.  You can set atime and mtime to anything you want.

SOP for writing to to an mbox formatted mailbox is to preserve
the atime (changing only the mtime) so that other programs know
that that there is "new" mail in the mbox.  I know mutt works
that way, and I believe that the "you've got new mail" features
in some shells work that way.  AFAIK, atimehttp://www.qmail.org/qmail-manual-html/man5/mbox.html

-- 
Grant Edwards   grante Yow! I put aside my copy
  at   of "BOWLING WORLD" and
   visi.comthink about GUN CONTROL
   legislation...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Superclass initialization

2009-04-24 Thread Ole Streicher
Steven D'Aprano  writes:
> Perhaps you should post the full trace back instead of just the final 
> line.

No Problem, although I dont see the information increase there:

In [318]: class da(ndarray):
   .: def __init__(self, mydata):
   .: ndarray.__init__(self, 0)
   .: self.mydata = mydata
   .:

In [319]: da(range(100))
---
ValueErrorTraceback (most recent call last)

/m3d/src/python/ in ()

ValueError: sequence too large; must be smaller than 32

The same happens if I put the class definition into a file: the
traceback does *not* point to a code line in that source file but to
the input line. Again, full trace:

In [320]: import da

In [321]: da.da(range(100))
---
ValueErrorTraceback (most recent call last)

/m3d/src/python/ in ()

ValueError: sequence too large; must be smaller than 32

(using python instead of ipython also does not give more details).

Best regards

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


Re: Superclass initialization

2009-04-24 Thread Ole Streicher
Arnaud Delobelle  writes:
> numpy.ndarray has a __new__ method (and no __init__).  I guess this is
> the one you should override.  Try:

What is the difference?

best regards

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


Re: Superclass initialization

2009-04-24 Thread Arnaud Delobelle
On Apr 24, 3:46 pm, Ole Streicher  wrote:
> Arnaud Delobelle  writes:
> > numpy.ndarray has a __new__ method (and no __init__).  I guess this is
> > the one you should override.  Try:
>
> What is the difference?
>
> best regards
>
> Ole

Here's an explanation.

http://www.python.org/download/releases/2.2.3/descrintro/#__new__

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


repost: http web page fetch question

2009-04-24 Thread grocery_stocker
Given the following...

[cdal...@localhost oakland]$ more basic.py
#!/usr/bin/python

import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def print_event(name):
print 'EVENT:', time.time(), name

print 'START:', time.time()
scheduler.enter(2, 1, print_event, ('first',))

scheduler.run()
[cdal...@localhost oakland]$ ./basic.py
START: 1240584506.06
EVENT: 1240584508.06 first
[cdal...@localhost oakland]$


How do I modify it so that it runs every hour on the hour.
--
http://mail.python.org/mailman/listinfo/python-list


Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread MRAB

Grant Edwards wrote:

On 2009-04-23, MRAB  wrote:

tinn...@isbd.co.uk wrote:

It seems to me that mailbox.mbox.add() sets the access time of a mbox
file as well as the modification time.  This is not good for MUAs that
detect new mail by looking to see if the access time is before the
modification time.

Have I done something wrong somewhere or is mailbox.mbox.add() really
as broken as it would appear?


[snip]
The access time is the time it was last accessed, ie read or modified.


Usually.


The modification time is the time it was last modified.


Usually.


The access time can never be before the modification time because it
must be accessed in order to be modified!


Nonsense.  You can set atime and mtime to anything you want.


Well, yes, you can always change atime and mtime and make it look like
something happened at a different time to when it actually happened...


SOP for writing to to an mbox formatted mailbox is to preserve
the atime (changing only the mtime) so that other programs know
that that there is "new" mail in the mbox.  I know mutt works
that way, and I believe that the "you've got new mail" features
in some shells work that way.  AFAIK, atime
So atime is used to indicate when it was last read, not last accessed?
Hmm...


Anybody writing to an mbox mailbox has to follow the rules if
they expect to interoperate with other mail applications.  If
mailbox.mbox.add() doesn't preserve the atime when writing to
an mbox, then mailbox.mbox.add is broken.

http://www.qmail.org/qmail-manual-html/man5/mbox.html



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


Re: Failed to build these modules:_ctypes

2009-04-24 Thread Thomas Heller
PS schrieb:
> Hello all
> 
> I can't install neither python 2.6.1 nor 2.6.2 because an error during
> compilation of _ctypes module, I don't need the module but I don't
> know how to instruct to skip it.

You only get a warning, right?  So a subsequent 'make install' should work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large data arrays?

2009-04-24 Thread John Machin
On Apr 24, 5:17 pm, Ole Streicher  wrote:
> Hi John,
>
> John Machin  writes:
> > The Morton layout wastes space if the matrix is not square. Your 100K
> > x 4K is very non-square. Looks like you might want to use e.g. 25
> > Morton arrays, each 4K x 4K.
>
> What I found was that Morton layout shall be usable, if the shape is
> rectangular and both dimensions are powers of two. But, all examples
> were done with equal dimensions, so I am a bit confused here.

Yes, you are right, it can be done in one hit with a rectangular
array. How it is done: in your case you have a 2**17 x 2**12 array, so
the Morton index corresponding to (i, j) would have the top 5 bits of
i followed by the remaining 12 bits of i interleaved with the 12 bits
of j -- scarcely distinguishable from my original suggestion of 25
4Kx4K arrays, once you've ignored the trailing approx 2**17 - 100
elements that you don't need to allocate space for ;-)

>
> From my access pattern, it would be probably better to combine 25 rows
> into one slice and have one matrix where every cell contains 25 rows.
>
> Are there any objections about that?

Can't object, because I'm not sure what you mean ... how many elements
in a "cell"?

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


Re: Help with code! Gamepad?

2009-04-24 Thread DC16
On Apr 23, 4:03 pm, Mike Driscoll  wrote:
> On Apr 23, 6:46 am, DC16  wrote:
>
>
>
>
>
> > I am using pygame and OpenGL.
> > How do I make a gamepad able to move the camera to a side of a cube on
> > screen.
>
> > Here is the code for keyboard use:
>
> > import pygame
> > from pygame.locals import *
> > import sys
> > from OpenGLLibrary import *
>
> > pygame.init()
>
> > Screen = (800,600)
> > Window = glLibWindow(Screen,caption="Camera Test")
> > View3D = glLibView3D((0,0,Screen[0],Screen[1]),45)
> > View3D.set_view()
>
> > Camera = glLibCamera([0,0.5,6],[0,0,0])
>
> > glLibColorMaterial(True)
>
> > drawing = 0
> > Objects = [glLibObjCube(),glLibObjTeapot(),glLibObjSphere
> > (64),glLibObjCylinder(0.5,1.0,64),glLibObjCone(0.5,1.8,64)]
>
> > while True:
> >     key = pygame.key.get_pressed()
> >     for event in pygame.event.get():
> >         if event.type == QUIT:
> >             pygame.quit()
> >             sys.exit()
> >         if event.type == KEYDOWN:
> >             if event.key == K_ESCAPE:
> >                 pygame.quit()
> >                 sys.exit()
> >             if event.key == K_RETURN:
> >                 drawing += 1
> >                 if drawing == 5:
> >                     drawing = 0
> >             if event.key == K_1: glLibColor((255,255,255))
> >             if event.key == K_2: glLibColor((255,0,0))
> >             if event.key == K_3: glLibColor((255,128,0))
> >             if event.key == K_4: glLibColor((255,255,0))
> >             if event.key == K_5: glLibColor((0,255,0))
> >             if event.key == K_6: glLibColor((0,0,255))
> >             if event.key == K_7: glLibColor((128,0,255))
> >     if   key[K_LEFT]: Camera.set_target_pos([-6,0.5,0])
> >     elif key[K_RIGHT]: Camera.set_target_pos([6,0.5,0])
> >     elif key[K_UP]: Camera.set_target_pos([0,6,2])
> >     elif key[K_DOWN]: Camera.set_target_pos([0,-6,2])
> >     else: Camera.set_target_pos([0,0.5,6])
>
> >     Camera.update()
>
> >     Window.clear()
> >     Camera.set_camera()
> >     Objects[drawing].draw()
> >     Window.flip()
>
> > How do I change it so that a gampad can move the camera in the same
> > way.
> > (Ignore the colour changing code)
>
> > Thanks,
> > Dexter (DC16)
>
> > BTW the code was originally by someone else.
>
> Try cross-posting to the pygame guys:http://www.pygame.org/wiki/info
>
> I read that pyglet will have some sort of gamepad support soon too, so
> you might want to check that project out as well.
>
> - Mike- Hide quoted text -
>
> - Show quoted text -

I cannot find any code for gamepad/joypad on there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large data arrays?

2009-04-24 Thread Ole Streicher
Hi John,

John Machin  writes:
>> From my access pattern, it would be probably better to combine 25 rows
>> into one slice and have one matrix where every cell contains 25 rows.
>> Are there any objections about that?
> Can't object, because I'm not sure what you mean ... how many elements
> in a "cell"?

Well, a matrix consists of "cells"? A 10x10 matrix has 100 "cells".

Regards 

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


python list handling and Lisp list handling

2009-04-24 Thread Mark Tarver
This page says that Python lists are often flexible arrays

http://www.brpreiss.com/books/opus7/html/page82.html

but also says that their representation is implementation dependent.
As far as I see this should mean that element access in Python should
run in constant time.  Now if so this is a boon, because generally

'A list is a sequence of elements, but it is not a single primitive
object; it is made of cons cells, one cell per element. Finding the
nth element requires looking through n cons cells, so elements farther
from the beginning of the list take longer to access. But it is
possible to add elements to the list, or remove elements.'

(from http://www.chemie.fu-berlin.de/chemnet/use/info/elisp/elisp_7.html)

But are Python lists also indistinguishable from conventional
Lisplists for list processing.  For example, can I modify a Python
list non-destructively?  Are they equivalent to Lisp lists. Can CAR
and CDR in Lisp be thought of as

def car (x):
  return x[0]

def cdr (x):
  return x[1:]

The idea of a list in which elements can be accessed in constant time
is novel to me.

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


Re: Large data arrays?

2009-04-24 Thread John Machin
On Apr 25, 1:14 am, Ole Streicher  wrote:
> Hi John,
>
> John Machin  writes:
> >> From my access pattern, it would be probably better to combine 25 rows
> >> into one slice and have one matrix where every cell contains 25 rows.
> >> Are there any objections about that?
> > Can't object, because I'm not sure what you mean ... how many elements
> > in a "cell"?
>
> Well, a matrix consists of "cells"? A 10x10 matrix has 100 "cells".

Yes yes but you said "every cell contains 25 rows" ... what's in a
cell? 25 rows, with each row containing what?
--
http://mail.python.org/mailman/listinfo/python-list


Re: gethostbyname blocking

2009-04-24 Thread marc wyburn
On Apr 23, 2:16 pm, Piet van Oostrum  wrote:
> > marc wyburn  (MW) wrote:
> >MW> Hi, I am writing anasynchronousping app to check if 1000s of hosts
> >MW> are alive very quickly.  Everything works extremely quickly unless the
> >MW> host name doesn't have a DNS record.
> >MW> when calling socket.gethostbynameif there is no record for the host
> >MW> the result seems to block all other threads.  As an example I have 6
> >MW> threads running and if I pass the class below a Queue with about 30
> >MW> valid addresses with one invalid address in the middle the thread that
> >MW> the exception occurs in seems to block the others.
>
> What you could do is have two Queues, one with host names, and one with
> results fromgethostbyname. And an additional thread which gets from the
> first queue, callsgethostbynameand puts the results in the second queue.
> The ping threads then should get from the second queue. The lookup
> thread could even do caching of the results if you often have to repeat
> the pings for thew same host.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p...@vanoostrum.org

Hi, I did try this but the socket blocked for so long that this was a
real bottleneck.  It also seemed that whilst the DNS lookup thread was
blocking the other threads were also blocked.  I guess this may have
something to do with the GIL but I'm still fairly new to threading.  I
ended up using DNSPython which flys along.  I have a thread creating
the ping packets and pinging them and another performing a select and
logging + filtering any ICMP replies.  I may put the DNS code into
another thread but the whole script runs faster than I need it to as
it is, I've got time.sleeps in the ping thread as I'm scared of
saturating the local LAN during work hours.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python list handling and Lisp list handling

2009-04-24 Thread MRAB

Mark Tarver wrote:

This page says that Python lists are often flexible arrays

http://www.brpreiss.com/books/opus7/html/page82.html

but also says that their representation is implementation dependent.
As far as I see this should mean that element access in Python should
run in constant time.  Now if so this is a boon, because generally

'A list is a sequence of elements, but it is not a single primitive
object; it is made of cons cells, one cell per element. Finding the
nth element requires looking through n cons cells, so elements farther
from the beginning of the list take longer to access. But it is
possible to add elements to the list, or remove elements.'

(from http://www.chemie.fu-berlin.de/chemnet/use/info/elisp/elisp_7.html)

But are Python lists also indistinguishable from conventional
Lisplists for list processing.  For example, can I modify a Python
list non-destructively?  Are they equivalent to Lisp lists. Can CAR
and CDR in Lisp be thought of as

def car (x):
  return x[0]

def cdr (x):
  return x[1:]

The idea of a list in which elements can be accessed in constant time
is novel to me.


They are usually implemented as resizable arrays. In CPython great care
has been taken to make appending average to constant time; however,
inserting requires the later elements to be shifted up.

In the way they are normally used they are fast.

There are also queues and deques for when you want efficient queue or
deque behaviour.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large data arrays?

2009-04-24 Thread Ole Streicher
Hi John

John Machin  writes:
> On Apr 25, 1:14 am, Ole Streicher  wrote:
>> John Machin  writes:
>> >> From my access pattern, it would be probably better to combine 25 rows
>> >> into one slice and have one matrix where every cell contains 25 rows.
>> >> Are there any objections about that?
>> > Can't object, because I'm not sure what you mean ... how many elements
>> > in a "cell"?
>>
>> Well, a matrix consists of "cells"? A 10x10 matrix has 100 "cells".
>
> Yes yes but you said "every cell contains 25 rows" ... what's in a
> cell? 25 rows, with each row containing what?

I mean: original cells.
I have 100.000x4096 entries:

(0,0) (0,1) ... (0,4095)
(1,0) (1,1) ... (1,4095)
...
(100.000,0) (100.000,1) ... (100.000,4095)

This will be re-organized in a new matrix, containing 4096 columns (as
before) and 4000 rows. The leftmost cell (first row, first col) in the
new matrix then contains the array

(0,0)
(1,0)
...
(24,0)

The second column of the first row contains the array

(0,1)
(1,1)
...
(24,1)

and so on. The first column of the second row contains

(25,0)
...
(49,0)

That way, I get a new matrix where every cell contains an array of 24
"original" cells. Disadvantage (what I see now when I write it down)
is that this is bad for numpy since it deals with arrays instead of
numbers in matrix positions.

Best regards

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


Re: python list handling and Lisp list handling

2009-04-24 Thread Paul Rubin
Mark Tarver  writes:
> But are Python lists also indistinguishable from conventional
> Lisplists for list processing.  

Forgot to add: you might look at http://norvig.com/python-lisp.html

Mark Tarver  writes:

> But are Python lists also indistinguishable from conventional
> Lisplists for list processing.

They are very different.  There is nothing like cons or nconc.
You can't convert two lists to a single longer list with nconc, 
etc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python list handling and Lisp list handling

2009-04-24 Thread Paul Rubin
Mark Tarver  writes:
> But are Python lists also indistinguishable from conventional
> Lisplists for list processing.  For example, can I modify a Python
> list non-destructively?  Are they equivalent to Lisp lists. Can CAR
> and CDR in Lisp be thought of as

Python lists are vectors that automatically resize.  You can append to
the end in amortized constant time in the obvious way (i.e. the
implementation allocates some extra space for expansion, and copies to
an even bigger area if you run out of expansion room).  You can insert
and delete in the middle in linear time.  This isn't as bad as it
sounds because the Python interpreter is pretty slow, but the list
insertion/deletion primitives are in C and are fast.
--
http://mail.python.org/mailman/listinfo/python-list


mod_python form upload: permission denied sometimes...

2009-04-24 Thread psaff...@googlemail.com
I have a mod_python application that takes a POST file upload from a
form. It works fine from my machine, other machines in my office and
my home machine. It does not work from my bosses machine in a
different city - he gets "You don't have permission to access this on
this server".

In the logs, it's returned 403. I also have this error in error.log:

Cannot traverse upload in /pythonapps/wiggle/form/upload because
 is not a traversable object,
referer: ...

Could this be a network level problem? If so, why does it work from my
home machine but not my bosses machine?? The file to upload is quite
large - 7MB.
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Terry Reedy

Steven D'Aprano wrote:

On Thu, 23 Apr 2009 21:51:42 -0400, Esmail wrote:


set(a) == set(b)# test if a and b have the same elements

# check that each list has the same number of each element # i.e.   
[1,2,1,2] == [1,1,2,2], but [1,2,2,2] != [1,1,1,2] for elem in set(a):

  a.count(elem) == b.count(elem)

Ah .. this part would take care of different number of duplicates in the
lists. Cool.


At significant cost of extra work.

Counting the number of times a single element occurs in the list is O(N). 
Counting the number of times every element occurs in the list is O(N**2). 


A frequency dict should be O(n) also, and hence faster than sorting.

Sorting is O(N*log N), so for large lists, sorting will probably be much 
cheaper.





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


Re: Help with code! Gamepad?

2009-04-24 Thread Mike Driscoll
On Apr 24, 10:11 am, DC16  wrote:
> On Apr 23, 4:03 pm, Mike Driscoll  wrote:
>
>
>
> > On Apr 23, 6:46 am, DC16  wrote:
>
> > > I am using pygame and OpenGL.
> > > How do I make a gamepad able to move the camera to a side of a cube on
> > > screen.
>
> > > Here is the code for keyboard use:
>
> > > import pygame
> > > from pygame.locals import *
> > > import sys
> > > from OpenGLLibrary import *
>
> > > pygame.init()
>
> > > Screen = (800,600)
> > > Window = glLibWindow(Screen,caption="Camera Test")
> > > View3D = glLibView3D((0,0,Screen[0],Screen[1]),45)
> > > View3D.set_view()
>
> > > Camera = glLibCamera([0,0.5,6],[0,0,0])
>
> > > glLibColorMaterial(True)
>
> > > drawing = 0
> > > Objects = [glLibObjCube(),glLibObjTeapot(),glLibObjSphere
> > > (64),glLibObjCylinder(0.5,1.0,64),glLibObjCone(0.5,1.8,64)]
>
> > > while True:
> > >     key = pygame.key.get_pressed()
> > >     for event in pygame.event.get():
> > >         if event.type == QUIT:
> > >             pygame.quit()
> > >             sys.exit()
> > >         if event.type == KEYDOWN:
> > >             if event.key == K_ESCAPE:
> > >                 pygame.quit()
> > >                 sys.exit()
> > >             if event.key == K_RETURN:
> > >                 drawing += 1
> > >                 if drawing == 5:
> > >                     drawing = 0
> > >             if event.key == K_1: glLibColor((255,255,255))
> > >             if event.key == K_2: glLibColor((255,0,0))
> > >             if event.key == K_3: glLibColor((255,128,0))
> > >             if event.key == K_4: glLibColor((255,255,0))
> > >             if event.key == K_5: glLibColor((0,255,0))
> > >             if event.key == K_6: glLibColor((0,0,255))
> > >             if event.key == K_7: glLibColor((128,0,255))
> > >     if   key[K_LEFT]: Camera.set_target_pos([-6,0.5,0])
> > >     elif key[K_RIGHT]: Camera.set_target_pos([6,0.5,0])
> > >     elif key[K_UP]: Camera.set_target_pos([0,6,2])
> > >     elif key[K_DOWN]: Camera.set_target_pos([0,-6,2])
> > >     else: Camera.set_target_pos([0,0.5,6])
>
> > >     Camera.update()
>
> > >     Window.clear()
> > >     Camera.set_camera()
> > >     Objects[drawing].draw()
> > >     Window.flip()
>
> > > How do I change it so that a gampad can move the camera in the same
> > > way.
> > > (Ignore the colour changing code)
>
> > > Thanks,
> > > Dexter (DC16)
>
> > > BTW the code was originally by someone else.
>
> > Try cross-posting to the pygame guys:http://www.pygame.org/wiki/info
>
> > I read that pyglet will have some sort of gamepad support soon too, so
> > you might want to check that project out as well.
>
> > - Mike- Hide quoted text -
>
> > - Show quoted text -
>
> I cannot find any code for gamepad/joypad on there.

I guess I was thinking of this: http://pypi.python.org/pypi/jaraco.input/1.0

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


Re: Raw command line arguments

2009-04-24 Thread Gabriel Genellina
En Fri, 24 Apr 2009 06:40:23 -0300, Enchanter   
escribió:



How to pass the raw command line arguments to the python?


That depends on the OS or the shell you're using.


Such as:

 mypython.py  txt -c "Test Only" {Help}


The arguments I hope to get is:

  txt -c "Test Only" {Help}   -- Keep the
quotation marks in the arguments.


I guess you're using Windows:

gg>type show.py
import sys
print sys.argv

gg>python show.py one txt -c """Test Only""" {Help}
['show.py', 'one', 'txt', '-c', '"Test Only"', '{Help}']

Two double quotes represent a single one. And you have to enclose the  
whole argument in quotes too because of the space character.


--
Gabriel Genellina

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


Re: sorting two corresponding lists?

2009-04-24 Thread tiefeng wu
>
> > Just being pedantic here :)
> >
> > [items[x] for x in [i for i in map(values.index, new_values)]]
> >
> > Is the same as
> >
> > [items[x] for x in map(values.index, new_values)]
>
> It's also the same as
>
>[items[x] for x in [values.index(i) for i in new_values]]
>
> Which reduces to
>
>[items[values.index(i)] for i in new_values]



All these variances prove how python amazing is, thanks!



> (Although 'i' is not a good choice of variable as it represents a
> value, not an index)
>


Actually, I think 'i' indeed represents index of each sorted values in
original values list



> Anyway it doesn't work well if the 'values' list has repeated values,
> e.g.
>
> items = ['spam', 'eggs', 'wafer']
> values = [3, 7, 3]


Yes, I didn't even think about this situation!
I'm new to python too, as original poster Esmail, there are a lot of things
to learn to be a real pythoner:)
--
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2009-04-24 Thread Gabriel Genellina
En Thu, 23 Apr 2009 18:50:06 -0300, Scott David Daniels  
 escribió:

Gabriel Genellina wrote:
En Wed, 25 Jul 2007 19:14:28 -0300, James Stroud   
escribió:


[nice recipe to retrieve only certain lines of a file]

I think your time machine needs an adjustment, it spits things almost two  
years later :)


--
Gabriel Genellina

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


Python servlet for Java applet ?

2009-04-24 Thread Linuxguy123
Hi guys.

Is there a way to use a python application as the back end (ie rpc) for
a Java based applet ?

How does it work compared to a Java servlet with a Java applet ?

Thanks

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


confused with so many python package locations for imports

2009-04-24 Thread Krishnakant

hello all,
I was doing my first complete python packaging for my software and I am
totally confused.
I see, /usr/local/lib/python-2.6/site-packages and also dist-packages.
Then I also see a directory called pyshare, then again site-packages in
usr/lib/python (I am not even remembering correct paths for many such
locations ).

Now my question is, which the perfect place?  I would like to know if I
write a distutils based setup.py for my application, then which is the
place which I should choose?

happy hacking.
Krishnakant.


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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread norseman

Esmail wrote:

What is the best way to compare the *contents* of two different
lists regardless of their respective order? The lists will have
the same number of items, and be of the same type.

E.g. a trivial example (my lists will be larger),

a=[1, 2, 3]

b=[2, 3, 1]

should yield true if a==b

I suppose I could sort them and then compare them. I.e.,

sorted(a)==sorted(b)


I am wondering if there is a more efficient/preferred way to do so.

Thanks,
Esmail

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


=
Technically, ==  is reserved for identical, as in byte for byte same

->If sorted(listA) == sorted(listB):
->  etc
Is the preferred.

While there are other ways, the ones I know of are much more computer 
intensive.


Things like:
  get (next) line from file1
  if checking it against each line of file2 yields a found
loop
  else
...
are a real I/O killers.
Indexes are good but introduce a separate maintenance issue.


By the way - does original order of original files count?
If not, sorting AND KEEPING can speed up future things.

Of course each method has its time and place of use and Python has some 
well oiled list search and list maintain routines of its own. List 
comparisons are most accurate when using presorted ones. (Some things 
don't lend themselves to sorting very well. Like paragraphs, books, 
chapters, computer programs, manuals, etc... These need the searchers 
(equivalent to the Unix diff) for checking equivalence.)



HTH

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


PyQt4 - widget signal trouble

2009-04-24 Thread Joacim Thomassen
Hello,

I'm trying to get my first PyQt4 application to work as intended, but it 
seems I'm stuck and out of ideas for now.

The program is a simple GUI showing an image. If the image on disk change 
my intension is that the displayed image in my application also change 
accordingly.

What works: The filesystem change is detected and my program prints out 
"Change happened!"

what is the problem: The image shown in the application is not changed.

What am I doing wrong here? Any ideas and suggestions are appreciated.

Best regards,
Joacim Thomassen

My program:
#!/usr/bin/python
"""
familyframe.py

Simple photo frame for the desktop

Author: Joacim Thomassen, 4/2-2009
License: AGPLv3+

Last change: 24/2-2009
"""

from __future__ import division
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import time
import fcntl
import os
import signal

fname = "/home/joacim/.familyframe"

class Watcher(QObject):
def handler(self, signum, frame):
self.emit(SIGNAL("imageChange"))
def __init__(self, parent=None):
super(Watcher, self).__init__()
signal.signal(signal.SIGIO, self.handler)
fd = os.open(fname, os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY, fcntl.DN_MODIFY | 
fcntl.DN_CREATE | fcntl.DN_MULTISHOT)

class ImageWidget(QLabel):
def __init__(self, parent=None):
super(QLabel, self).__init__(parent)
self.image = QImage("/home/joacim/.familyframe/image.jpg")
self.setMinimumSize(200, 200)
self.setAlignment(Qt.AlignCenter)
self.setPixmap(QPixmap.fromImage(self.image))
def reload(self):
print "Change happened!"
self.image.load("/home/joacim/.familyframe/image.jpg")
self.setPixmap(QPixmap.fromImage(self.image))
self.update()

class CentralWidget(QWidget):
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
self.imagewidget = ImageWidget()
self.box = QHBoxLayout()
self.box.addWidget(self.imagewidget)
self.setLayout(self.box)
def reload(self):
self.imagewidget.reload()

class MainWindow(QMainWindow):
def __init__(self, w, parent=None):
super(MainWindow, self).__init__(parent)
self.centralwidget = CentralWidget()
self.setWindowTitle("Family Frame")
self.setCentralWidget(self.centralwidget)
self.connect(w, SIGNAL("imageChange"), self.updateUi)
self.show()
def updateUi(self):
self.centralwidget.reload()

if __name__ == "__main__":
app = QApplication(sys.argv)
w = Watcher()
main = MainWindow(w)
app.exec_()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert numpy.ndarray into "normal" array

2009-04-24 Thread Aahz
In article <75dgm1f16hqn...@mid.dfncis.de>,
Johannes Bauer   wrote:
>
>So now I want to copy the fits_pixels -> pb_pixels. Doing
>
>pb_pixels = fits_pixels
>
>works and is insanely fast, however the picture looks all screwed-up
>(looks like a RGB picture of unititialized memory, huge chunks of 0s
>interleaved with lots of white noise).
>
>Doing the loop:
>
>for x in range(width):
>   for y in range(height):
>   pb_pixels[y, x] = fits_pixels[y, x]
>
>works as expected, but is horribly slow (around 3 seconds for a 640x480
>picture).
>
>So now I've been trying to somehow convert the array in a fast manner,
>but just couldn't do it. What exactly is "array" anyways? I know
>"array.array", but that's something completely different, right? Does
>anyone have hints on how to go do this?

http://scipy.org/Mailing_Lists
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Help AIX 5.3 build on Python-3.1a2

2009-04-24 Thread pruebauno
OPT=-O2 LDFLAGS=-s ./configure --prefix=/ptst --with-gcc="xlc_r -q64"
--with-cxx="xlC_r -q64" --disable-ipv6 AR="ar -X64" --without-locale --
without-ctypes

checking for --with-universal-archs... 32-bit
checking MACHDEP... aix5
checking machine type as reported by uname -m... 00023AAA4C00
checking for --without-gcc... xlc_r -q64
checking for gcc... xlc_r -q64
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... no
checking whether xlc_r -q64 accepts -g... yes
checking for xlc_r -q64 option to accept ISO C89... none needed
checking for --with-cxx-main=... no
checking for c++... no
checking for g++... no
checking for gcc... no
checking for CC... no
checking for cxx... no
checking for cc++... no
checking for cl... no
checking how to run the C preprocessor... xlc_r -q64 -E
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for AIX... yes
checking for --with-suffix...
checking for case-insensitive build directory... no
checking LIBRARY... libpython$(VERSION).a
checking LINKCC... $(srcdir)/Modules/makexp_aix Modules/python.exp . $
(LIBRARY); $(PURIFY) $(MAINCC)
checking for --enable-shared... no
checking for --enable-profiling...
checking LDLIBRARY... libpython$(VERSION).a
checking for ranlib... ranlib
checking for ar... ar -X64
checking for svnversion... not-found
checking for a BSD-compatible install... ./install-sh -c
checking for --with-pydebug... no
checking whether xlc_r -q64 accepts -OPT:Olimit=0... no
checking whether xlc_r -q64 accepts -Olimit 1500... no
checking whether pthreads are available without options... yes
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking asm/types.h usability... no
checking asm/types.h presence... no
checking for asm/types.h... no
checking conio.h usability... no
checking conio.h presence... no
checking for conio.h... no
checking curses.h usability... yes
checking curses.h presence... yes
checking for curses.h... yes
checking direct.h usability... no
checking direct.h presence... no
checking for direct.h... no
checking dlfcn.h usability... yes
checking dlfcn.h presence... yes
checking for dlfcn.h... yes
checking errno.h usability... yes
checking errno.h presence... yes
checking for errno.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking grp.h usability... yes
checking grp.h presence... yes
checking for grp.h... yes
checking ieeefp.h usability... no
checking ieeefp.h presence... no
checking for ieeefp.h... no
checking io.h usability... no
checking io.h presence... no
checking for io.h... no
checking langinfo.h usability... yes
checking langinfo.h presence... yes
checking for langinfo.h... yes
checking libintl.h usability... yes
checking libintl.h presence... yes
checking for libintl.h... yes
checking ncurses.h usability... no
checking ncurses.h presence... no
checking for ncurses.h... no
checking poll.h usability... yes
checking poll.h presence... yes
checking for poll.h... yes
checking process.h usability... no
checking process.h presence... no
checking for process.h... no
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking shadow.h usability... no
checking shadow.h presence... no
checking for shadow.h... no
checking signal.h usability... yes
checking signal.h presence... yes
checking for signal.h... yes
checking for stdint.h... (cached) yes
checking stropts.h usability... yes
checking stropts.h presence... yes
checking for stropts.h... yes
checking termios.h usability... yes
checking termios.h presence... yes
checking for termios.h... yes
checking thread.h usability... no
checking thread.h presence... no
checking for thread.h... no
checking for unistd.h... (cached) yes
checking utime.h usability... yes
checking utime.h presence... yes
checking for utime.h... yes
checking sys/audioio.h usability... no
checking sys/audioio.h presence... no
checking for sys/audioio.h... no
checking sys/bsdtty.h usability... no
checking sys/bsdtty.h presence... no
checking for sys/bsdtty.h... no
checking sys/epoll.h usability... no
checking sys/epoll.h presence... no
checking for sys/epoll.h... no
checking sys/event.h usability... no
checking sys/event.h presence... no
checking for sys/event.h... no
checking sys/file.h usability... yes
checking sys/file.h presence... yes
checking for sys/file.h... yes
checking sys/loadavg.h usability... no
checking sys/loadavg.h presence... no
checking for sys/loadavg.h... no
checking sys/lock.h

Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread Lawrence D'Oliveiro
In message , Grant Edwards 
wrote:

> AFAIK, atime contains new mail for at least 20 years.

Doesn't apply to maildir though, does it?

Updating atime adds a lot of filesystem overhead; that's why the relatime 
option was invented . But better still is 
not to bother.

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Steven D'Aprano
On Fri, 24 Apr 2009 10:39:39 -0700, norseman wrote:

> Technically, ==  is reserved for identical, as in byte for byte same

Really? Then how do you explain these?

>>> u'abc' == 'abc'
True
>>> 1 == 1.0
True
>>> 2L == 2
True
>>>
>>> import decimal
>>> decimal.Decimal('42') == 42
True


Here's one to think about:

>>> d1 = {-1: None, -2: None}
>>> d2 = {-2: None, -1: None}
>>> print d1, d2
{-2: None, -1: None} {-1: None, -2: None}
>>> d1 == d2
True

If d1 and d2 are equal and both are dictionaries with the same keys and 
same values, why do they print in different orders?



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


Re: python list handling and Lisp list handling

2009-04-24 Thread Mark Tarver
On 24 Apr, 17:19, Paul Rubin  wrote:
> Mark Tarver  writes:
> > But are Python lists also indistinguishable from conventional
> > Lisplists for list processing.  
>
> Forgot to add: you might look athttp://norvig.com/python-lisp.html
>
> Mark Tarver  writes:
> > But are Python lists also indistinguishable from conventional
> > Lisplists for list processing.
>
> They are very different.  There is nothing like cons or nconc.
> You can't convert two lists to a single longer list with nconc,
> etc.

Ah;  so this

def cons (x,y):
  return [x] + y

is not accurate?

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


Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread Grant Edwards
On 2009-04-24, MRAB  wrote:

>>> [snip]
>>> The access time is the time it was last accessed, ie read or modified.
>> 
>> Usually.
>> 
>>> The modification time is the time it was last modified.
>> 
>> Usually.
>> 
>>> The access time can never be before the modification time because it
>>> must be accessed in order to be modified!
>> 
>> Nonsense.  You can set atime and mtime to anything you want.
>
> Well, yes, you can always change atime and mtime and make it
> look like something happened at a different time to when it
> actually happened...

Yup.  And that's what one does when writing to an mbox format
mailbox.

>> SOP for writing to to an mbox formatted mailbox is to preserve
>> the atime (changing only the mtime) so that other programs know
>> that that there is "new" mail in the mbox.  I know mutt works
>> that way, and I believe that the "you've got new mail" features
>> in some shells work that way.  AFAIK, atime> "standard" way to determine when an mbox contains new mail for
>> at least 20 years.
>
> So atime is used to indicate when it was last read, not last
> accessed? Hmm...

Unfortunately, that's how mbox works.  It's an ugly hack, but
if one didn't care about backwards-compatiblity with old e-mail
apps, then one would use a less broken mailbox format like
maildir.

-- 
Grant Edwards   grante Yow! I smell like a wet
  at   reducing clinic on Columbus
   visi.comDay!
--
http://mail.python.org/mailman/listinfo/python-list


Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread Grant Edwards
On 2009-04-24, Lawrence D'Oliveiro  wrote:
> In message , Grant Edwards 
> wrote:
>
>> AFAIK, atime> when an mbox contains new mail for at least 20 years.
>
> Doesn't apply to maildir though, does it?

Nope.  With maildir, there's a completely separate directory
where one puts new messages.

> Updating atime adds a lot of filesystem overhead; that's why
> the relatime option was invented .

The relatime should cut down a great deal on system overhead
and yet still preserves the atime/mtime semantics used by mbox
clients.

> But better still is not to bother.

-- 
Grant Edwards   grante Yow! I wonder if I could
  at   ever get started in the
   visi.comcredit world?
--
http://mail.python.org/mailman/listinfo/python-list


Re: repost: http web page fetch question

2009-04-24 Thread Emile van Sebille

grocery_stocker wrote:

Given the following...

[cdal...@localhost oakland]$ more basic.py




How do I modify it so that it runs every hour on the hour.


I'd probably use cron, but here's one way.

Emile
-

import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def print_event(count,rescheduler):
print 'EVENT:', time.time(), count
rescheduler.enter(2,1,print_event,(count+1,rescheduler))

print 'START:', time.time()
scheduler.enter(2, 1, print_event, (1,scheduler))

scheduler.run()

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


Re: and [True,True] --> [True, True]?????

2009-04-24 Thread Martin v. Löwis

>> Of course dicts and sets are sequences.  But there are also sequences
>> on which len doesn't work.
> 
> That was my intuition, too. But Python takes a different stance:

It's a sequence if it can be indexed by numbers in range(len(seq)).
Neither dicts nor sets can be indexed that way.

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


Re: mailbox.mbox.add() sets access time as well as modification time

2009-04-24 Thread Grant Edwards
On 2009-04-24, Grant Edwards  wrote:

> Anybody writing to an mbox mailbox has to follow the rules if
> they expect to interoperate with other mail applications.  If
> mailbox.mbox.add() doesn't preserve the atime when writing to
> an mbox, then mailbox.mbox.add is broken.

I should qualify that: since the documentation for add()
doesn't specify whether or not it's supposed to add a "new"
message or an "old" message, one could argue that either
behavior is correct.

However, since the maildir add() method adds a "new" message,
one would reasonably expect that the mbox add() method do the
same.  Or, I suppose one might expect the converse: since mbox
add() creates an "old" message, then maildir add() should do
the same.

I have my filesystems mouted with the "noatime" option and use
maildir...

-- 
Grant Edwards   grante Yow! !  The land of the
  at   rising SONY!!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large data arrays?

2009-04-24 Thread Scott David Daniels

Ole Streicher wrote:

Hi John

John Machin  writes:

On Apr 25, 1:14 am, Ole Streicher  wrote:

John Machin  writes:

From my access pattern, it would be probably better to combine 25 rows
into one slice and have one matrix where every cell contains 25 rows.
Are there any objections about that?

Can't object, because I'm not sure what you mean ... how many elements
in a "cell"?

Well, a matrix consists of "cells"? A 10x10 matrix has 100 "cells".

Yes yes but you said "every cell contains 25 rows" ... what's in a
cell? 25 rows, with each row containing what?


I mean: original cells.
I have 100.000x4096 entries:

(0,0) (0,1) ... (0,4095)
(1,0) (1,1) ... (1,4095)
...
(100.000,0) (100.000,1) ... (100.000,4095)


Choose a block size, and place the block in your output.  For example,
using 128K byte blocks (and assuming each cell holds a single 8-byte
number), we could decide each block was a 128 x 128 sub-matrix of your
original.  Then to get to a particular block, seek to its base address,
and use:
src = open('data.file', 'rb') # or wb or...

src.seek(block_number * 128 * 128 * 8)
block = numpy.fromfile(src, count=128 * 128)
block.shape = (128, 128)
and then you've got your sub-block.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why can function definitions only use identifiers, and not attribute references or any other primaries?

2009-04-24 Thread Scott David Daniels

Marco Mariani wrote:

Scott David Daniels wrote:


I am afraid it will make it too easy to define functions in other
modules remotely, a tempting sharp stick to poke your eye out with.
Imagine debugging a pile of code that includes a module with:
import random
def random.random():
return .42


No need to imagine. I can do the same, one line shorter:

 >>> import random
 >>> random.random = lambda: .42


I'm pointing out that that one is called lambda, so function.__name__
works out nicely.  Similarly (and to my min more treacherously), the
def a.b(...):
...
doesn't give you a good clue about where to look for the definition.
That's all, not "monkeypatching is evil", but "monkeypatching should
stand out visually."

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: python list handling and Lisp list handling

2009-04-24 Thread Arnaud Delobelle
Mark Tarver  writes:
> Ah;  so this
>
> def cons (x,y):
>   return [x] + y
>
> is not accurate?

Depends what you mean by accurate!

in lisp, if you do:

(setq a '(1 2))
(setq b (cons 0 a))
(rplaca a 3)

Then
a is now (3 2)
b is now (0 3 2)

In Python, if you do:

a = [1, 2]
b = cons(0, a) # with your definition of cons
a[0] = 3

Then
a is now [3, 2]
b is now [0, 1, 2]

So in this respect, it is not accurate.  But that's because Python lists
are vectors not conses.

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


pythoncom -- ImportError: DLL load failed

2009-04-24 Thread Richard Whidden
I've sniffed around for a solution to this problem but I can't find 
anything.

The simple COM example in the "Programming on Win32" O'Reilly book works 
fine.  However, as soon as I add 'import pgdb' to the object, chaos ensues 
promply.

Here's what I did.

Step 1, write this:
foo.py --
# print pythoncom.CreateGuid()
import pgdb
class PythonUtilities:
  _public_methods_ = [ 'SplitString']
  _reg_progid_ = "FooFoo.Utilities"
  _reg_clsid_ = "
class PythonUtilities:
  File "C:\devel\blip\foo.py", line 5, in PythonUtilities
import pgdb
  File "C:\Python26\Lib\site-packages\pgdb.py", line 66, in 
from _pg import *
ImportError: DLL load failed: The specified module could not be found.
pythoncom error: Unexpected gateway error

Traceback (most recent call last):
  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 136, 
in CreateInstance
return retObj._CreateInstance_(clsid, reqIID)
  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 194, 
in _CreateInstance_
myob = call_func(classSpec)
  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 727, 
in call_func
return resolve_func(spec)(*args)
  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 716, 
in resolve_func
module = _import_module(mname)
  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 735, 
in _import_module
__import__(mname)
  File "C:\devel\blip\foo.py", line 4, in 
class PythonUtilities:
  File "C:\devel\blip\foo.py", line 5, in PythonUtilities
import pgdb
  File "C:\Python26\Lib\site-packages\pgdb.py", line 66, in 
from _pg import *
ImportError: DLL load failed: The specified module could not be found.
pythoncom error: CPyFactory::CreateInstance failed to create instance. 
(80004005)
-  End of Error

I've tried a few things.  If I import foo.py into a python script, it works 
fine.  It only fails if I try things via COM.

I've run depends.exe.  Everything can see everything else.

I've moved libpq.dll to \windows\system32, \scriptpath, \postgres\lib, 
\postgres\bin... Probably other places too to no avail.

I'm sure I've tried other things, I just can't think of them right now.  I 
have this sickening feeling in my gut that the solution is so obvious that a 
blind and dead person would have spotted the solution before me.

Anyway, if anyone has an idea (or a link to an idea) please let me know.

Thanks,
Richard Whidden 


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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread norseman

Steven D'Aprano wrote:

On Fri, 24 Apr 2009 10:39:39 -0700, norseman wrote:


Technically, ==  is reserved for identical, as in byte for byte same


Really? Then how do you explain these?


u'abc' == 'abc'

True

1 == 1.0

True

2L == 2

True

import decimal
decimal.Decimal('42') == 42

True


Here's one to think about:


d1 = {-1: None, -2: None}
d2 = {-2: None, -1: None}
print d1, d2

{-2: None, -1: None} {-1: None, -2: None}

d1 == d2

True

If d1 and d2 are equal and both are dictionaries with the same keys and 
same values, why do they print in different orders?





=
(How do I) ...explain these?
  Python cooks the test function.
  That explains a few things I thought were kinda weird.

...one to think about:
Either someone has a programming glitch or else likes stack use.
LoadA push, read-LILO, readB, compare, loop to read-LILO.
And they decided to just pre-load as a matter of course, but maybe 
forgot to read-LILO in print... ie.. didn't finish cooking print.

(or left it out as a reminder or)

Technically, ==  is reserved for identical, as in byte for byte same
(when == is used to check identical, uncooked)


As a matter of self - I don't favor cooking. I prefer 'cooked' things 
have a different name so I can get what I want, when I want.

Choice on wall:
  fish, deep fried in light beer batter
  sashimi

in case you didn't notice - cooking takes longer :)

I can get the sashimi and take it home and BBQ it, I can roast it, I can 
steam it, I can wok it,..., but the other is what it is. (greasy)


Besides, who says I like your cooking?  :)

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


Re: [Python-Dev] PEP 383: Non-decodable Bytes in System Character Interfaces

2009-04-24 Thread Lino Mastrodomenico
2009/4/22 "Martin v. Löwis" :
> To convert non-decodable bytes, a new error handler "python-escape" is
> introduced, which decodes non-decodable bytes using into a private-use
> character U+F01xx, which is believed to not conflict with private-use
> characters that currently exist in Python codecs.

Why not use U+DCxx for non-UTF-8 encodings too?

Overall I like the PEP: I think it's the best proposal so far that
doesn't put an heavy burden on applications that only want to do
simple things with the API.

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


Python not importing mysqldb

2009-04-24 Thread 83nini
hi guys,

i've been sweating the whole day trying to make python work with mysql
but in vain!
i'm doing the following:
1. visiting http://sourceforge.net/projects/mysql-python
2. dowloading mysql-python-test-1.2.3c1
3. extracting the files to C:\Python26\Lib\site-packages
4. writing "import MySQLdb" in the python prompt

getting

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python26\lib\site-packages\MySQLdb\__init__.py", line 19,
in 

import _mysql
ImportError: No module named _mysql

WHY Y
why does it have to be so complicated what am i doing wrong for
god's sake?


thanks in advance,
cheers,
Lina
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numpy Performance

2009-04-24 Thread Robert Kern

On 2009-04-24 08:05, timlash wrote:

Essentially, I'm testing tens of thousands of scenarios on a
relatively small number of test cases.  Each scenario requires all
elements of each test case to be scored, then summarized, then sorted
and grouped with some top scores captured for reporting.

It seems like I can either work toward a procedure that features
indexed categorization so that my arrays are of integer type and a
design that will allow each scenario to be handled in bulk numpy
fashion, or expand RectangularArray with custom data handling methods.


If you posted a small, self-contained example of what you are doing to 
numpy-discussion, the denizens there will probably be able to help you formulate 
the right way to do this in numpy, if such a way exists.


  http://www.scipy.org/Mailing_Lists

--
Robert Kern

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

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


Re: Python not importing mysqldb

2009-04-24 Thread Emile van Sebille

83nini wrote:

hi guys,

i've been sweating the whole day trying to make python work with mysql
but in vain!
i'm doing the following:
1. visiting http://sourceforge.net/projects/mysql-python
2. dowloading mysql-python-test-1.2.3c1
3. extracting the files to C:\Python26\Lib\site-packages


From that site ... "Python versions 2.3-2.5 are supported"

Is that it?

Emile

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


Re: pythoncom -- ImportError: DLL load failed - Update

2009-04-24 Thread Richard Whidden
By including the following DLLs on a Windows 2000 image I have running 
Python 2.5, my little sample app works...
comerr32.dll krb5_32.dll  libintl-8.dllpython26.dll
gssapi32.dll libeay32.dll libpq.dllssleay32.dll
k5sprt32.dll libiconv-2.dll   python25.dll
msvcm90.dll   msvcp90.dll   msvcr90.dll

However, on my WinXP development machine (running Python 2.6) this doesn't 
work--Instead I receive a message,
"An application has made an attempt to load the C runtime library 
incorrectly..."  Once I remove the msvc* files, it goes back to the original 
problem...

Argh.

The msvc* dlls are in an odd place: 
C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_6f74963e

I've tried including that directory to my system path too, of course.



"Richard Whidden"  wrote in message 
news:002a58fa$0$25248$c3e8...@news.astraweb.com...
> I've sniffed around for a solution to this problem but I can't find 
> anything.
>
> The simple COM example in the "Programming on Win32" O'Reilly book works 
> fine.  However, as soon as I add 'import pgdb' to the object, chaos ensues 
> promply.
>
> Here's what I did.
>
> Step 1, write this:
> foo.py --
> # print pythoncom.CreateGuid()
> import pgdb
> class PythonUtilities:
>  _public_methods_ = [ 'SplitString']
>  _reg_progid_ = "FooFoo.Utilities"
>  _reg_clsid_ = " insert value here."
>
>  def SplitString(self, val, item=None):
>import string
>if item !=None: item = str(item)
>return string.split(str(val), item)
>
> if __name__=='__main__':
>  print "Registering COM server"
>  import win32com.server.register
>  win32com.server.register.UseCommandLine(PythonUtilities)
> - End of foo.py
>
> Step 2, run 'python foo.py'.
>
> Step 3, write this:
> test.vbs - 
> set o = CreateObject("FooFoo.Utilities")
> --- End of test.vbs
>
> Step 4, run 'cscript /nologo test.vbs'
>
> Step 5, watch it fail.
>
> Error --
> C:\devel\blip\test.vbs(1, 1) (null): Unspecified error
>
> pythoncom error: ERROR: server.policy could not create an instance.
>
> Traceback (most recent call last):
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 136, 
> in CreateInstance
>return retObj._CreateInstance_(clsid, reqIID)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 194, 
> in _CreateInstance_
>myob = call_func(classSpec)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 727, 
> in call_func
>return resolve_func(spec)(*args)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 716, 
> in resolve_func
>module = _import_module(mname)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 735, 
> in _import_module
>__import__(mname)
>  File "C:\devel\blip\foo.py", line 4, in 
>class PythonUtilities:
>  File "C:\devel\blip\foo.py", line 5, in PythonUtilities
>import pgdb
>  File "C:\Python26\Lib\site-packages\pgdb.py", line 66, in 
>from _pg import *
> ImportError: DLL load failed: The specified module could not be found.
> pythoncom error: Unexpected gateway error
>
> Traceback (most recent call last):
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 136, 
> in CreateInstance
>return retObj._CreateInstance_(clsid, reqIID)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 194, 
> in _CreateInstance_
>myob = call_func(classSpec)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 727, 
> in call_func
>return resolve_func(spec)(*args)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 716, 
> in resolve_func
>module = _import_module(mname)
>  File "C:\Python26\lib\site-packages\win32com\server\policy.py", line 735, 
> in _import_module
>__import__(mname)
>  File "C:\devel\blip\foo.py", line 4, in 
>class PythonUtilities:
>  File "C:\devel\blip\foo.py", line 5, in PythonUtilities
>import pgdb
>  File "C:\Python26\Lib\site-packages\pgdb.py", line 66, in 
>from _pg import *
> ImportError: DLL load failed: The specified module could not be found.
> pythoncom error: CPyFactory::CreateInstance failed to create instance. 
> (80004005)
> -  End of Error
>
> I've tried a few things.  If I import foo.py into a python script, it 
> works fine.  It only fails if I try things via COM.
>
> I've run depends.exe.  Everything can see everything else.
>
> I've moved libpq.dll to \windows\system32, \scriptpath, \postgres\lib, 
> \postgres\bin... Probably other places too to no avail.
>
> I'm sure I've tried other things, I just can't think of them right now.  I 
> have this sickening feeling in my gut that the solution is so obvious that 
> a blind and dead person would have spotted the solution before me.
>
> Anyway, if anyone has an idea (or a link to an idea) please let me know.
>
> Thanks,
> Richard Whidden
> 


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


  1   2   >