Re: Find the location of a loaded module

2009-02-20 Thread Gabriel Genellina
En Fri, 20 Feb 2009 20:44:21 -0200, Aaron Scott  
 escribió:



So, the problem lies with how Python cached the modules in memory.
Yes, the modules were in two different locations and yes, the one that
I specified using its direct path should be the one loaded. The
problem is, the module isn't always loaded -- if it's already in
memory, it'll use that instead. And since the modules had the same
name, Python wouldn't distinguish between them, even though they
weren't exactly the same.


Yes, that's how import works. It's barely documented, and you finally  
learned it the hard way...



So, loading the module act1/story would load
act1/story. Then, loading the module act2/story would use the story
module already in memory. Of course, this made the problem hard to
pinpoint, since memory is a fickle thing, and the results weren't
always reproducible.

The final solution? Renaming the 'story' modules to 'story_1' and
'story_2'... and importing them via 'exec("from story_"+modulename+"
import game")'.

Will I go to hell for this 'solution'? Probably. But hey, it means I
can go home tonight instead of spending all evening at the office
hitting my head against the wall. I'll come back to it Monday and try
to figure out a more reasonable solution.


Use packages. Make act1 and act2 packages by creating __init__.py files.

--
Gabriel Genellina

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


Re: how to assert that method accepts specific types

2009-02-20 Thread Rhodri James

On Sat, 21 Feb 2009 01:12:01 -, Darren Dale  wrote:


I would like to assert that a method accepts certain types. I have a
short example that works:

from functools import wraps

def accepts(*types):
def check_accepts(f):
@wraps(f)
def new_f(self, other):
assert isinstance(other, types), \
"arg %r does not match %s" % (other, types)
return f(self, other)
return new_f
return check_accepts

class Test(object):

@accepts(int)
def check(self, obj):
print obj

t = Test()
t.check(1)

but now I want Test.check to accept an instance of Test as well. Does
anyone know how this can be accomplished? The following class
definition for Test raises a NameError:

class Test(object):

@accepts(int, Test)
def check(self, obj):
print obj


An icky but relatively clear way to get around this is to gratuitously
subclass Test:

class AcceptableTest(object):
pass

class Test(AcceptableTest):
@accepts(int, AcceptableTest)
def check(self, obj):
print obj


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python won't run

2009-02-20 Thread Scott David Daniels

Chris Rebert wrote:

On Fri, Feb 20, 2009 at 4:52 PM, kevin hayes  wrote:

Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle stopped
opening and running after I ran a few programs.  I installed python 2.6
hoping this would allow me to open idle and start learning to program.  How
do I get Idle running again?


What error do you get when trying to run it from the command line?

Cheers,
Chris


Try from the command line:

$ python -m idlelib.idle -n

If it works, do a bit and see how that goes.  Then try:

$ python -m idlelib.idle

In both cases, you _may_ get error messages to the command window that
help diagnose.

--Scott David Daniels
scott.dani...@acm.org



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


Re: multiprocessing module and os.close(sys.stdin.fileno())

2009-02-20 Thread Joshua Judson Rosen
Jesse Noller  writes:
>
> On Tue, Feb 17, 2009 at 10:34 PM, Graham Dumpleton
>  wrote:
> > Why is the multiprocessing module, ie., multiprocessing/process.py, in
> > _bootstrap() doing:
> >
> >  os.close(sys.stdin.fileno())
> >
> > rather than:
> >
> >  sys.stdin.close()
> >
> > Technically it is feasible that stdin could have been replaced with
> > something other than a file object, where the replacement doesn't have
> > a fileno() method.
> >
> > In that sort of situation an AttributeError would be raised, which
> > isn't going to be caught as either OSError or ValueError, which is all
> > the code watches out for.
> 
> I don't know why it was implemented that way. File an issue on the
> tracker and assign it to me (jnoller) please.

My guess would be: because it's also possible for sys.stdin to be a
file that's open in read+*write* mode, and for that file to have
pending output buffered (for example, in the case of a socketfile).

There's a general guideline, inherited from C, that one should ensure
that the higher-level close() routine is invoked on a given
file-descriptor in at most *one* process after that descriptor has
passed through a fork(); in the other (probably child) processes, the
lower-level close() routine should be called to avoid a
double-flush--whereby buffered data is flushed out of one process, and
then the *same* buffered data is flushed out of the (other)
child-/parent-process' copy of the file-object.

So, if you call sys.stdin.close() in the child-process in
_bootstrap(), then it could lead to a double-flush corrupting output
somewhere in the application that uses the multiprocessing module.

You can expect similar issues with just about /any/ `file-like objects'
that might have `file-like semantics' of buffering data and flushing
it on close, also--because you end up with multiple copies of the same
object in `pre-flush' state, and each copy tries to flush at some point.

As such, I'd recommend against just using .close(); you might use
something like `if hasattr(sys.stdin, "fileno"): ...'; but, if your
`else' clause unconditionally calls sys.stdin.close(), then you still
have double-flush problems if someone's set sys.stdin to a file-like
object with output-buffering.

I guess you could try calling that an `edge-case' and seeing if anyone
screams. It'd be sort-of nice if there was finer granularity in the
file API--maybe if file.close() took a boolean `flush' argument

-- 
Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Byte" type?

2009-02-20 Thread John Nagle

Steve Holden wrote:

John Nagle wrote:

Benjamin Kaplan wrote:

On Sun, Feb 15, 2009 at 11:57 AM, John Nagle  wrote:


...Re "bytes" not behaving as documented in 2.6:


   That's indeed how Python 2.6 works.  But that's not how
PEP 3137 says it's supposed to work.

Guido:

 "I propose the following type names at the Python level:

* bytes is an immutable array of bytes (PyString)
* bytearray is a mutable array of bytes (PyBytes)"

...
(Not true in Python 2.6 


Is this a bug, a feature, a documentation error, or bad design?


It's a feature. In fact all that was done to accommodate easier
migration to 3.x is easily shown in one statement:


str is bytes

True

So that's why bytes works the way it does in 2.6 ... hence my contested
description of it as an "ugly hack". I am happy to withdraw "ugly", but
I think "hack" could still be held to apply.


   Agreed.  But is this a 2.6 thing, making 2.6 incompatible with 3.0, or
what?  How will 3.x do it?  The PEP 3137 way, or the Python 2.6 way?

   The way it works in 2.6 makes it necessary to do "ord" conversions
where they shouldn't be required.

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


Re: function factory question: embed current values of object attributes

2009-02-20 Thread Gabriel Genellina
En Fri, 20 Feb 2009 16:49:21 -0200, Alan Isaac   
escribió:



I have a class `X` where many parameters are set
at instance initialization.  The parameter values
of an instance `x` generally remain unchanged,
but is there way to communicate to a method that
it depends only on the initial values of these parameters
(and does not need to worry about any changes)?

The behavior of method `m` depends on these parameter values.
It turns out `m` gets called a lot, which means
that the pameter values are accessed over and over
(self.p0, self.p1, etc).  I would like to
manufacture a function equivalent to the method
that simply uses fixed values (the values at the
time it is manufactured).  I do not care if this
function is attached to `x` or not.


Not automatically; but you could refactor the method to call an external  
function with arguments:


class X(...):
  ...
  def foo(self):
c = self.a + self.b
return c

Rewrite the method as:

  def foo(self):
return _foo(self.a, self.b)

and define _foo outside the class:

def _foo(a, b):
  c = a + b
  return c

If you want a "frozen" function (that is, a function already set-up with  
the parameters taken from the current values of x.a, x.b) use  
functools.partial:


x = X()
frozen_foo = functools.partial(_foo, a=x.a, b=x.b)
frozen_foo() # equivalent to x.foo() at the time it was defined

But if you call this in a loop, perhaps it's enough to assign x.a, x.b to  
local variables and call _foo with those arguments.


--
Gabriel Genellina

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


Re: can multi-core improve single funciton?

2009-02-20 Thread Kurt Smith
On Fri, Feb 20, 2009 at 4:27 PM, Grant Edwards  wrote:
> On one hand, the upshot of that is that by finding an
> appropriate library module you might gain some of the same
> benefits as removing the GIL.
>
> On the other hand, that doesn't help if you're doing something
> original enough that nobody has written a library to handle
> large chunks of it.
>
> And on the grasping hand, I find that most of us vastly
> overestimate the originality of what we're doing.

+1 The Mote in God's Eye / The Gripping Hand reference!

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


Re: Killing subservient threads

2009-02-20 Thread Gabriel Genellina

En Fri, 20 Feb 2009 16:15:10 -0200, jimzat  escribió:


I am using the thread module and calling thread.start_new_thread
(...).  If I use t=thread.start_new_thread(...) and later set
t.terminate, I get "AttributeError: 'int' object has no attribute
'terminate'"


Use the threading module instead, that provides a higher level interface.  
If you originally had:


thread.start_new_thread(function, args)

then it becomes:

polling_thread = threading.Thread(target=function, args=args)
...
polling_thread.start()


What is the proper way to do this?  I don't want to use globals as I
will have multiple child windows of various classes.


Use an attribute of this Thread instance. Either a simple boolean or a  
Condition/Event object as Christian Heimes suggested.


--
Gabriel Genellina

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


Re: Changing the Image on a button

2009-02-20 Thread odeits
On Feb 17, 7:14 am, John Posner  wrote:
>  >> > Try this change:
>  >> >
>  >> >   from: btn.configure(image = None)
>  >> >     to: img1.blank()
>  >> >
>  >>
>  >> This does in fact clear the image out, however it isn't causing the
>  >> text to display... Do i have have to create a new button and swap it
>  >> out?
>
> I knew you were gonna ask that! :-) I haven't worked in this area before,
> but I
> found this athttp://effbot.org/tkinterbook/button.htm:
>
>     In earlier versions of Tkinter, the image option overrides the text
> option.
>     If you specify both, only the image is displayed. In later versions, you
> can
>     use the compound option to change this behavior. To display text on top
> of
>     an image, set compound to CENTER:
>
>      b = Button(master, text="Click me", image=pattern, compound=CENTER)
>
> So here's a reworking, in which the text and image are both toggled by
> pressing the button:
>
> ### button that toggles both text and image
> from Tkinter import *
>
> def pushed():
>     """callback: button push"""
>
>     global toggle
>
>     if toggle:
>         btn.config(text="", image=img_empty)
>         toggle = not toggle
>     else:
>         btn.config(text=msg, image=img_good)
>         toggle = not toggle
>
> ### main program
> toggle = True
> msg = "hello"
>
> root = Tk()
>
> ### store two versions of an image in global variables:
> # 1. original image
> img_good = PhotoImage(file="bacon.gif")
>
> # 2. blank image, created by copying and erasing
> img_empty = img_good.copy()
> img_empty.blank()
>
> ### create toggle button
> btn = Button(root, compound=CENTER,
>             text="hello", font="helvetica 14 bold",
>             image=img_good,
>             command=pushed)
> btn.pack()
>
> ### go
> root.mainloop()
>
> E-mail message checked by Spyware Doctor (6.0.0.386)
> Database version: 5.11780http://www.pctools.com/en/spyware-doctor-antivirus/

Thank you very much for your help! It is now behaving the way I wanted!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to determine if one char of many in a string

2009-02-20 Thread odeits
On Feb 15, 11:31 pm, odeits  wrote:
> On Feb 15, 9:56 pm, Chris Rebert  wrote:
>
>
>
> > On Sun, Feb 15, 2009 at 9:17 PM,   wrote:
> > > I need to test strings to determine if one of a list of chars is in the
> > > string. A simple example would be to test strings to determine if they 
> > > have
> > > a vowel (aeiouAEIOU) present.
>
> > > I was hopeful that there was a built-in method that operated similar to
> > > startswith where I could pass a tuple of chars to be tested, but I could 
> > > not
> > > find such a method.
>
> > > Which of the following techniques is most Pythonic or are there better 
> > > ways
> > > to perform this type of match?
>
> > > # long and hard coded but short circuits as soon as match found
> > > if 'a' in word or 'e' in word or 'i' in word or 'u' in word or ... :
>
> > > -OR-
>
> > > # flexible, but no short circuit on first match
> > > if [ char for char in word if char in 'aeiouAEIOU' ]:
>
> > Just use the fairly new builtin function any() to make it short-circuit:
>
> > if any(char.lower() in 'aeiou' for char in word):
> >     do_whatever()
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> If you want to generalize it you should look at 
> setshttp://docs.python.org/library/sets.html
>
> It seems what you are actually testing for is if the intersection of
> the two sets is not empty where the first set is the characters in
> your word and the second set is the characters in your defined string.

To expand on what I was saying I thought i should provide a code
snippet:

WORD = 'g' * 100
WORD2 = 'g' * 50 + 'U'
VOWELS = 'aeiouAEIOU'
BIGWORD = 'g' * 1 + 'U'

def set_test(vowels, word):

vowels = set( iter(vowels))
letters = set( iter(word) )

if letters & vowels:
return True
else:
return False

with python 2.5 I got 1.30 usec/pass against the BIGWORD


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


Re: Python won't run

2009-02-20 Thread Ned Deily
In article 
<37c2b0840902201751q5ac4b607n14c90ee0b51c1...@mail.gmail.com>,
 kevin hayes  wrote:
> I installed it...with the package that came with python 2.6. When I had 2.5
> I was using it(idle) successfully, until I ran a few programs that I got off
> the web.  Then, Idle wouldn't open (it just bounced in the dock and then
> disappeared).  So I tried installing 2.6 and the same thing happened.

There may be some clues in the system.log as to why IDLE is not 
launching.  Launch /Applications/Utilities/Console.app and under its 
File menu select Open System Log.  Now try to launch IDLE again by 
double-clicking on its icon and see if any suspicious messages show up 
in the log.  You could also try moving any IDLE preferences files out of 
the way temporarily and see if that helps.  From a Terminal window, type:
cd $HOME
mv .idlerc .idlerc-disabled
then try launching IDLE again.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Framework installation of 2.6 on OS X, with specified prefix

2009-02-20 Thread Evert Rol


On 20 Feb 2009, at 21:48 , Ned Deily wrote:


In article ,
Evert Rol  wrote:
I'm trying to install Python 2.6 from source on Mac OS X.5, in its  
own

directory using a framework install. That goes fine, up to the point
where it wants to install the applications that come with it (eg, the
Wish shell): it tries to install things into /Applications, instead  
of

eg /Applications.
Here's my configure line (the flags are there just to let it find my
own installed readline):

CPPFLAGS=-I/sw/include LDFLAGS=-L/sw/lib ./configure --prefix=/sw --
enable-shared --enable-framework=/sw/Library/Frameworks --with-
readline=/sw --with-pth CC=gcc-4.2  MACOSX_DEPLOYMENT_TARGET=10.5


And the last part of the output of 'make install':

../python.exe ./scripts/BuildApplet.py \
--destroot "" \
--python=/sw/Library/Frameworks/Python.framework/Versions/2.6/
Resources/Python.app/Contents/MacOS/Python`test -f "/sw/Library/
Frameworks/Python.framework/Versions/2.6/Resources/Python.app/ 
Contents/

MacOS/Python-32" && echo "-32"`  \
--output "/sw/Applications/Python 2.6/Build Applet.app" \
./scripts/BuildApplet.py
cd PythonLauncher && make install DESTDIR=
test -d "/Applications/Python 2.6" || mkdir -p "/Applications/Python
2.6"
mkdir: /Applications/Python 2.6: Permission denied
make[2]: *** [install] Error 1
make[1]: *** [install_PythonLauncher] Error 2
make: *** [frameworkinstallapps] Error 2

Is there an option on the configure line that I need to set, or
something in setup.py? Or perhaps hack the Makefile?


FWIW, the OS X build-installer.py script handles this by specifying a
DESTDIR on the make install steps rather than including a --prefix on
the configure.   See Mac/BuildScript/build-installer.py.


That worked: make install DESTDIR=/sw .
Not sure if it's the proper way to do it, but it installed fine now.
I did have to change the configure line:

CPPFLAGS=-I/sw/include LDFLAGS=-L/sw/lib ./configure --
enable-shared --enable-framework=/Library/Frameworks --with-
readline=/sw --with-pth CC=gcc-4.2  MACOSX_DEPLOYMENT_TARGET=10.5

So --prefix has gone, and --enable-framework lost the /sw. Then the  
DESTDIR setting on the make line prepends it as necessary.


I would have hoped an option on the configure line would have taken  
care of this (--exec-prefix doesn't do it, at least), but well, maybe  
next time.


(Actually, checking again, I now also have a /sw/sw/Applications  
directory, next to the /sw/Applications dir. The former contains  
Applet.app; no idea how it ended up there, while IDLE.app and Python  
Launcher.app ended up in /sw/Applications. So, it almost worked; maybe  
there's some double $DESTDIR/$DESTDIR in the Makefile. Good enough for  
my purposes though.)


Thanks!

  Evert

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


Re: Using clock() in threading on Windows

2009-02-20 Thread Christian Heimes
Maxim Khitrov wrote:
> The threading module uses time.time in _Condition and _Thread classes
> to implement timeouts. On Windows, time() typically has a resolution
> of 15.625ms. In addition, if the system clock is changed (though ntp,
> for example) it would reflect that change, causing the timeout to last
> longer or shorter depending on which way the update went.
> 
> Would it not be better to use time.clock() instead? The resolution is
> much better, and the value is not linked to system clock. Right now, I
> replace the threading._time reference with clock in some of my
> programs and everything works perfectly. Condition and Event timeouts
> are precise down to the millisecond (resolution of the sleep
> function), and I see no side-effects.
> 
> Is it possible to make that change part of the module itself (keeping
> time() for linux systems), or can someone think of a reason why using
> clock is a bad idea? I know that it's using QueryPerformanceCounter
> for implementation, which has some known issues, but I still think
> that the advantages outweigh potential faults.

Can you make a feature request? Your proposal seems sensible. A trivial
patch should solve the issue:

from time import sleep as _sleep
if _sys.name == "win32":
from time import clock as _time
else:
from time import time as _time

However I'm not sure about the implications.

Christian

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


Re: Python won't run

2009-02-20 Thread kevin hayes
I installed it...with the package that came with python 2.6. When I had 2.5
I was using it(idle) successfully, until I ran a few programs that I got off
the web.  Then, Idle wouldn't open (it just bounced in the dock and then
disappeared).  So I tried installing 2.6 and the same thing happened.

On Fri, Feb 20, 2009 at 5:41 PM, Chris Rebert  wrote:

> Hmm. How did you install Python/IDLE?
> Also, please use Reply-All as others on the list might have helpful ideas.
>
> - Chris
>
> On Fri, Feb 20, 2009 at 5:34 PM, kevin hayes  wrote:
> > I was clicking on the application.  then the idle/python icon would
> bounce
> > in my
> > dock and then disappear.
> > On Fri, Feb 20, 2009 at 5:28 PM, Chris Rebert  wrote:
> >>
> >> How were you running IDLE previously?
> >>
> >> - Chris
> >>
> >> On Fri, Feb 20, 2009 at 5:24 PM, kevin hayes 
> wrote:
> >> > how do i do that?
> >> >
> >> > On Fri, Feb 20, 2009 at 5:20 PM, Chris Rebert 
> wrote:
> >> >>
> >> >> I meant, what happens when you run *IDLE* from the command line?
> >> >>
> >> >> - Chris
> >> >>
> >> >> On Fri, Feb 20, 2009 at 5:16 PM, kevin hayes 
> >> >> wrote:
> >> >> > When I type "python" into terminal I get >>> but I would like to be
> >> >> > able
> >> >> > to
> >> >> > open it as I would any application.  Thanks.
> >> >> >
> >> >> > On Fri, Feb 20, 2009 at 5:03 PM, Chris Rebert 
> >> >> > wrote:
> >> >> >>
> >> >> >> On Fri, Feb 20, 2009 at 4:52 PM, kevin hayes  >
> >> >> >> wrote:
> >> >> >> > Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle
> >> >> >> > stopped
> >> >> >> > opening and running after I ran a few programs.  I installed
> >> >> >> > python
> >> >> >> > 2.6
> >> >> >> > hoping this would allow me to open idle and start learning to
> >> >> >> > program.
> >> >> >> >  How
> >> >> >> > do I get Idle running again?
> >> >> >>
> >> >> >> What error do you get when trying to run it from the command line?
> >> >> >>
> >> >> >> Cheers,
> >> >> >> Chris
> >> >> >>
> >> >> >> --
> >> >> >> Follow the path of the Iguana...
> >> >> >> http://rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to assert that method accepts specific types

2009-02-20 Thread andrew cooke
Darren Dale wrote:
> I would like to assert that a method accepts certain types. I have a
> short example that works:

just in case it's useful - are you aware that pep3107 (which looks like it
should be leet-speak for something) is implemented in python 3? 
http://www.python.org/dev/peps/pep-3107/

andrew

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


Re: how to assert that method accepts specific types

2009-02-20 Thread Terry Reedy

Darren Dale wrote:

I would like to assert that a method accepts certain types. I have a
short example that works:

from functools import wraps

def accepts(*types):
def check_accepts(f):
@wraps(f)
def new_f(self, other):
assert isinstance(other, types), \
"arg %r does not match %s" % (other, types)
return f(self, other)
return new_f
return check_accepts

class Test(object):

@accepts(int)
def check(self, obj):
print obj

t = Test()
t.check(1)

but now I want Test.check to accept an instance of Test as well. Does
anyone know how this can be accomplished? The following class
definition for Test raises a NameError:

class Test(object):

@accepts(int, Test)
def check(self, obj):
print obj


Because Test does not exist at the time the function is compiled.
Remove '@accepts...' and put Test.check = accepts(int, Test)(Test.check) 
after the class definition and it should work.


tjr

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


Re: how to assert that method accepts specific types

2009-02-20 Thread Darren Dale
On Feb 20, 8:20 pm, Chris Rebert  wrote:
> On Fri, Feb 20, 2009 at 5:12 PM, Darren Dale  wrote:
> > I would like to assert that a method accepts certain types. I have a
> > short example that works:
>
> > from functools import wraps
>
> > def accepts(*types):
> >    def check_accepts(f):
> >       �...@wraps(f)
> >        def new_f(self, other):
> >            assert isinstance(other, types), \
> >                "arg %r does not match %s" % (other, types)
> >            return f(self, other)
> >        return new_f
> >    return check_accepts
>
> > class Test(object):
>
> >   �...@accepts(int)
> >    def check(self, obj):
> >        print obj
>
> > t = Test()
> > t.check(1)
>
> > but now I want Test.check to accept an instance of Test as well. Does
> > anyone know how this can be accomplished? The following class
> > definition for Test raises a NameError:
>
> > class Test(object):
>
> >   �...@accepts(int, Test)
> >    def check(self, obj):
> >        print obj
>
> You're going to have to either inject it after the class definition
> somehow, or give the class name as a string and use eval() or similar.
> The class object doesn't exist until the entire class body has
> finished executing, so you can't refer to the class within its own
> body.

Thats too bad, thanks for clarifying.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python won't run

2009-02-20 Thread Chris Rebert
Hmm. How did you install Python/IDLE?
Also, please use Reply-All as others on the list might have helpful ideas.

- Chris

On Fri, Feb 20, 2009 at 5:34 PM, kevin hayes  wrote:
> I was clicking on the application.  then the idle/python icon would bounce
> in my
> dock and then disappear.
> On Fri, Feb 20, 2009 at 5:28 PM, Chris Rebert  wrote:
>>
>> How were you running IDLE previously?
>>
>> - Chris
>>
>> On Fri, Feb 20, 2009 at 5:24 PM, kevin hayes  wrote:
>> > how do i do that?
>> >
>> > On Fri, Feb 20, 2009 at 5:20 PM, Chris Rebert  wrote:
>> >>
>> >> I meant, what happens when you run *IDLE* from the command line?
>> >>
>> >> - Chris
>> >>
>> >> On Fri, Feb 20, 2009 at 5:16 PM, kevin hayes 
>> >> wrote:
>> >> > When I type "python" into terminal I get >>> but I would like to be
>> >> > able
>> >> > to
>> >> > open it as I would any application.  Thanks.
>> >> >
>> >> > On Fri, Feb 20, 2009 at 5:03 PM, Chris Rebert 
>> >> > wrote:
>> >> >>
>> >> >> On Fri, Feb 20, 2009 at 4:52 PM, kevin hayes 
>> >> >> wrote:
>> >> >> > Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle
>> >> >> > stopped
>> >> >> > opening and running after I ran a few programs.  I installed
>> >> >> > python
>> >> >> > 2.6
>> >> >> > hoping this would allow me to open idle and start learning to
>> >> >> > program.
>> >> >> >  How
>> >> >> > do I get Idle running again?
>> >> >>
>> >> >> What error do you get when trying to run it from the command line?
>> >> >>
>> >> >> Cheers,
>> >> >> Chris
>> >> >>
>> >> >> --
>> >> >> Follow the path of the Iguana...
>> >> >> http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Terry Reedy

Martin v. Löwis wrote:
mehow have picked up a latin-1 encoding.)

I think latin-1 was the default without a coding cookie line.  (May be
uft-8 in 3.0).


It is, but that's irrelevant for the example. In the source

  u'\xb5'

all characters are ASCII (i.e. all of "letter u", "single
quote", "backslash", "letter x", "letter b", "digit 5").
As a consequence, this source text has the same meaning in all
supported source encodings (as source encodings must be ASCII
supersets).


I think I understand now that the coding cookie only matters if I use an 
editor that actually stores *non-ascii* bytes in the file for the Python 
parser to interpret.


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


Re: Python won't run

2009-02-20 Thread Chris Rebert
How were you running IDLE previously?

- Chris

On Fri, Feb 20, 2009 at 5:24 PM, kevin hayes  wrote:
> how do i do that?
>
> On Fri, Feb 20, 2009 at 5:20 PM, Chris Rebert  wrote:
>>
>> I meant, what happens when you run *IDLE* from the command line?
>>
>> - Chris
>>
>> On Fri, Feb 20, 2009 at 5:16 PM, kevin hayes  wrote:
>> > When I type "python" into terminal I get >>> but I would like to be able
>> > to
>> > open it as I would any application.  Thanks.
>> >
>> > On Fri, Feb 20, 2009 at 5:03 PM, Chris Rebert  wrote:
>> >>
>> >> On Fri, Feb 20, 2009 at 4:52 PM, kevin hayes 
>> >> wrote:
>> >> > Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle stopped
>> >> > opening and running after I ran a few programs.  I installed python
>> >> > 2.6
>> >> > hoping this would allow me to open idle and start learning to
>> >> > program.
>> >> >  How
>> >> > do I get Idle running again?
>> >>
>> >> What error do you get when trying to run it from the command line?
>> >>
>> >> Cheers,
>> >> Chris
>> >>
>> >> --
>> >> Follow the path of the Iguana...
>> >> http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to assert that method accepts specific types

2009-02-20 Thread Chris Rebert
On Fri, Feb 20, 2009 at 5:12 PM, Darren Dale  wrote:
> I would like to assert that a method accepts certain types. I have a
> short example that works:
>
> from functools import wraps
>
> def accepts(*types):
>def check_accepts(f):
>@wraps(f)
>def new_f(self, other):
>assert isinstance(other, types), \
>"arg %r does not match %s" % (other, types)
>return f(self, other)
>return new_f
>return check_accepts
>
> class Test(object):
>
>@accepts(int)
>def check(self, obj):
>print obj
>
> t = Test()
> t.check(1)
>
> but now I want Test.check to accept an instance of Test as well. Does
> anyone know how this can be accomplished? The following class
> definition for Test raises a NameError:
>
> class Test(object):
>
>@accepts(int, Test)
>def check(self, obj):
>print obj

You're going to have to either inject it after the class definition
somehow, or give the class name as a string and use eval() or similar.
The class object doesn't exist until the entire class body has
finished executing, so you can't refer to the class within its own
body.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


how to assert that method accepts specific types

2009-02-20 Thread Darren Dale
I would like to assert that a method accepts certain types. I have a
short example that works:

from functools import wraps

def accepts(*types):
def check_accepts(f):
@wraps(f)
def new_f(self, other):
assert isinstance(other, types), \
"arg %r does not match %s" % (other, types)
return f(self, other)
return new_f
return check_accepts

class Test(object):

@accepts(int)
def check(self, obj):
print obj

t = Test()
t.check(1)

but now I want Test.check to accept an instance of Test as well. Does
anyone know how this can be accomplished? The following class
definition for Test raises a NameError:

class Test(object):

@accepts(int, Test)
def check(self, obj):
print obj

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


python-list@python.org

2009-02-20 Thread John Machin
On Feb 21, 3:46 am, Allen  wrote:
> I am using Python with cx_oracle to load an excel spreadsheet into an
> Oracle table. There are lots of text on the spreadsheet that have "&"
> in them which I want to keep in the table. But inserting those text
> will fail.

"Will fail" (future tense) or have failed (past tense)??

> Is there a work around for this? I can filter out the
> failed insert statements and in SQLPLUS set define off  to run those
> statements, but it would be nice to insert "&" directly in PYTHON.
>

We don't have crystal balls. More information please:

1. How are you digging the data out of the spreadsheet?

2. What does print repr(text_on_the_spreadsheet) show for the failing
cases?

3. Show us your code for inserting.

4. What is the failure message?

5. What does "set define off" do for you in SQLPLUS?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python won't run

2009-02-20 Thread Chris Rebert
On Fri, Feb 20, 2009 at 4:52 PM, kevin hayes  wrote:
> Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle stopped
> opening and running after I ran a few programs.  I installed python 2.6
> hoping this would allow me to open idle and start learning to program.  How
> do I get Idle running again?

What error do you get when trying to run it from the command line?

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Python won't run

2009-02-20 Thread kevin hayes
Hi, I had python 2.5 installed on my Mac osx 10.4.11 and idle stopped
opening and running after I ran a few programs.  I installed python 2.6
hoping this would allow me to open idle and start learning to program.  How
do I get Idle running again?
--
http://mail.python.org/mailman/listinfo/python-list


Re: "import" not working?

2009-02-20 Thread Lionel
On Feb 20, 4:15 pm, Matimus  wrote:
> On Feb 20, 3:56 pm, Lionel  wrote:
>
>
>
>
>
> > On Feb 20, 3:52 pm, Chris Rebert  wrote:
>
> > > On Fri, Feb 20, 2009 at 3:33 PM, Lionel  wrote:
> > > > Hello all:
>
> > > > I've crafted several classes and exceptions which I've stored in a
> > > > file called "DataFileType.py". I then invoke them from within other
> > > > files like this:
>
> > > > # Top of file
>
> > > > import sys
> > > > sys.path.append("c:\DataFileTypes")
>
> > > Recall that the backslash is the escape character in Python and that
> > > therefore you need to put \\ to get a backslash in the resulting path
> > > string. Thus, the path you think you're adding isn't the path that's
> > > getting added.
> > > Alternatively, you can just use forward slashes instead (yes, that
> > > works on Windows from Python).
>
> > > Cheers,
> > > Chris
>
> > > --
> > > Follow the path of the Iguana...http://rebertia.com
>
> > But I'm only using a single backslash in the first example I gave, and
> > it works just fine there. How can this be?
>
> You must be running the python script from a directory where the file
> you are trying to import is already in the path. It never tries to
> look in the (bad) path because it found a file with the same name
> locally. My guess is that you are running the wx example from another
> location, and that is when you run into problems.
>
> Matt- Hide quoted text -
>
> - Show quoted text -

Okay, moving the wx example into the same directory containing the
first example that was working fixed it. This directory only contains
these two modules and nothing else. The old directory which contained
the example that wasn't working did not contain a module with the same
name as the one I was trying to import, so i don't know why this "fix"
worked.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "import" not working?

2009-02-20 Thread Steve Holden
Chris Rebert wrote:
> On Fri, Feb 20, 2009 at 3:33 PM, Lionel  wrote:
>> Hello all:
>>
>> I've crafted several classes and exceptions which I've stored in a
>> file called "DataFileType.py". I then invoke them from within other
>> files like this:
>>
>>
>> # Top of file
>>
>> import sys
>> sys.path.append("c:\DataFileTypes")
> 
> Recall that the backslash is the escape character in Python and that
> therefore you need to put \\ to get a backslash in the resulting path
> string. Thus, the path you think you're adding isn't the path that's
> getting added.
> Alternatively, you can just use forward slashes instead (yes, that
> works on Windows from Python).
> 
In fact "\D" isn't a defined escape character, so this particular usage
does give the right path, though your general point is good.

>>> "\D"
'\\D'
>>> len("\D")
2

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: "import" not working?

2009-02-20 Thread Matimus
On Feb 20, 3:56 pm, Lionel  wrote:
> On Feb 20, 3:52 pm, Chris Rebert  wrote:
>
>
>
> > On Fri, Feb 20, 2009 at 3:33 PM, Lionel  wrote:
> > > Hello all:
>
> > > I've crafted several classes and exceptions which I've stored in a
> > > file called "DataFileType.py". I then invoke them from within other
> > > files like this:
>
> > > # Top of file
>
> > > import sys
> > > sys.path.append("c:\DataFileTypes")
>
> > Recall that the backslash is the escape character in Python and that
> > therefore you need to put \\ to get a backslash in the resulting path
> > string. Thus, the path you think you're adding isn't the path that's
> > getting added.
> > Alternatively, you can just use forward slashes instead (yes, that
> > works on Windows from Python).
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> But I'm only using a single backslash in the first example I gave, and
> it works just fine there. How can this be?

You must be running the python script from a directory where the file
you are trying to import is already in the path. It never tries to
look in the (bad) path because it found a file with the same name
locally. My guess is that you are running the wx example from another
location, and that is when you run into problems.

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


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Ron Garret
In article <499f397c.7030...@v.loewis.de>,
 "Martin v. Löwis"  wrote:

> > Yes, I know that.  But every concrete representation of a unicode string 
> > has to have an encoding associated with it, including unicode strings 
> > produced by the Python parser when it parses the ascii string "u'\xb5'"
> > 
> > My question is: what is that encoding?
> 
> The internal representation is either UTF-16, or UTF-32; which one is
> a compile-time choice (i.e. when the Python interpreter is built).
> 
> > Put this another way: I would have thought that when the Python parser 
> > parses "u'\xb5'" it would produce the same result as calling 
> > unicode('\xb5'), but it doesn't.
> 
> Right. In the former case, \xb5 denotes a Unicode character, namely
> U+00B5, MICRO SIGN. It is the same as u"\u00b5", and still the same
> as u"\N{MICRO SIGN}". By "the same", I mean "the very same".
> 
> OTOH, unicode('\xb5') is something entirely different. '\xb5' is a
> byte string with length 1, with a single byte with the numeric
> value 0xb5, or 181. It does not, per se, denote any specific character.
> It only gets a character meaning when you try to decode it to unicode,
> which you do with unicode('\xb5'). This is short for
> 
>   unicode('\xb5', sys.getdefaultencoding())
> 
> and sys.getdefaultencoding() is (or should be) "ascii". Now, in
> ASCII, byte 0xb5 does not have a meaning (i.e. it does not denote
> a character at all), hence you get a UnicodeError.
> 
> > Instead it seems to produce the same 
> > result as calling unicode('\xb5', 'latin-1').
> 
> Sure. However, this is only by coincidence, because latin-1 has the same
> code points as Unicode (for 0..255).
> 
> > But my default encoding 
> > is not latin-1, it's ascii.  So where is the Python parser getting its 
> > encoding from?  Why does parsing "u'\xb5'" not produce the same error as 
> > calling unicode('\xb5')?
> 
> Because \xb5 *directly* refers to character U+00b5, with no
> byte-oriented encoding in-between.
> 
> Regards,
> Martin

OK, I think I get it now.  Thanks!

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


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Ron Garret
In article <499f3a8f.9010...@v.loewis.de>,
 "Martin v. Löwis"  wrote:

> > u'\xb5'
> >> u'\xb5'
> > print u'\xb5'
> >> ?
> > 
> > Unicode literals are *in the source file*, which can only have one
> > encoding (for a given source file).
> > 
> >> (That last character shows up as a micron sign despite the fact that
> >> my default encoding is ascii, so it seems to me that that unicode
> >> string must somehow have picked up a latin-1 encoding.)
> > 
> > I think latin-1 was the default without a coding cookie line.  (May be
> > uft-8 in 3.0).
> 
> It is, but that's irrelevant for the example. In the source
> 
>   u'\xb5'
> 
> all characters are ASCII (i.e. all of "letter u", "single
> quote", "backslash", "letter x", "letter b", "digit 5").
> As a consequence, this source text has the same meaning in all
> supported source encodings (as source encodings must be ASCII
> supersets).
> 
> The Unicode literal shown here does not get its interpretation
> from Latin-1. Instead, it directly gets its interpretation from
> the Unicode coded character set. The string is a short-hand
> for
> 
>  u'\u00b5'
> 
> and this denotes character U+00B5 (just as u'\u20ac" denotes
> U+20AC; the same holds for any other u'\u').
> 
> HTH,
> Martin

Ah, that makes sense.  Thanks!

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


Using clock() in threading on Windows

2009-02-20 Thread Maxim Khitrov
Greetings,

The threading module uses time.time in _Condition and _Thread classes
to implement timeouts. On Windows, time() typically has a resolution
of 15.625ms. In addition, if the system clock is changed (though ntp,
for example) it would reflect that change, causing the timeout to last
longer or shorter depending on which way the update went.

Would it not be better to use time.clock() instead? The resolution is
much better, and the value is not linked to system clock. Right now, I
replace the threading._time reference with clock in some of my
programs and everything works perfectly. Condition and Event timeouts
are precise down to the millisecond (resolution of the sleep
function), and I see no side-effects.

Is it possible to make that change part of the module itself (keeping
time() for linux systems), or can someone think of a reason why using
clock is a bad idea? I know that it's using QueryPerformanceCounter
for implementation, which has some known issues, but I still think
that the advantages outweigh potential faults.

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


Re: "import" not working?

2009-02-20 Thread Lionel
On Feb 20, 3:52 pm, Chris Rebert  wrote:
> On Fri, Feb 20, 2009 at 3:33 PM, Lionel  wrote:
> > Hello all:
>
> > I've crafted several classes and exceptions which I've stored in a
> > file called "DataFileType.py". I then invoke them from within other
> > files like this:
>
> > # Top of file
>
> > import sys
> > sys.path.append("c:\DataFileTypes")
>
> Recall that the backslash is the escape character in Python and that
> therefore you need to put \\ to get a backslash in the resulting path
> string. Thus, the path you think you're adding isn't the path that's
> getting added.
> Alternatively, you can just use forward slashes instead (yes, that
> works on Windows from Python).
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

But I'm only using a single backslash in the first example I gave, and
it works just fine there. How can this be?
--
http://mail.python.org/mailman/listinfo/python-list


Re: "import" not working?

2009-02-20 Thread Chris Rebert
On Fri, Feb 20, 2009 at 3:33 PM, Lionel  wrote:
> Hello all:
>
> I've crafted several classes and exceptions which I've stored in a
> file called "DataFileType.py". I then invoke them from within other
> files like this:
>
>
> # Top of file
>
> import sys
> sys.path.append("c:\DataFileTypes")

Recall that the backslash is the escape character in Python and that
therefore you need to put \\ to get a backslash in the resulting path
string. Thus, the path you think you're adding isn't the path that's
getting added.
Alternatively, you can just use forward slashes instead (yes, that
works on Windows from Python).

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: "import" not working?

2009-02-20 Thread Emile van Sebille

Lionel wrote:

from DataFileTypes import *


That's an import where you don't know what's getting import'd -- ie, 
namespace pollution



[snip]


from wx import *



and more here.  Try being explicit with your naming.

HTH,

Emile



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


Re: count secton of data in list

2009-02-20 Thread Emile van Sebille

brianrpsgt1 wrote:


def step1(val):

  data2_row = []


for d1r in data1_row:
if d1r[1] >= val:
switch = 0
data2_row = d1r[0],d1r[1],d1r[2],switch

  data2_row.append([d1r[0],d1r[1],d1r[2],switch])


HTH,

Emile

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


"import" not working?

2009-02-20 Thread Lionel
Hello all:

I've crafted several classes and exceptions which I've stored in a
file called "DataFileType.py". I then invoke them from within other
files like this:


# Top of file

import sys
sys.path.append("c:\DataFileTypes")
from DataFileTypes import *

data = None

try:
   # Note: "INTData" is a class defined in "DataFileTypes"
data = INTData("C:\SomeRawDataFile.int")

except DataFileError:
print("Error opening data file")

except ResourceFileError:
print("Error opening resource file")


The above works very well. No complaints. However, I'm experimenting
with the wxPython gui library and found that this no longer seems to
work when I add the crucial bits to one of their examples. I've copied
and run an example that came with wxPython and verified that, with no
modification on my part, it runs with no problem. I then add ONLY my
import instructions and try to instantiate an object as follows (I'm
only showing a portion of the file):


#!/usr/bin/env python

from numpy import arange, sin, pi

import matplotlib

matplotlib.use('WX')
from matplotlib.backends.backend_wx import FigureCanvasWx as
FigureCanvas

from matplotlib.figure import Figure

from wx import *

# The following 4 lines are my additions to the example code:
import sys
sys.path.append("c:\DataFileTypes")
from DataFileTypes import *
data = INTData("C:\SomeRawDataFile.int")


class CanvasFrame(Frame):
.
.
etc
.
.



Running the above program (which I've called "guiplottest.py")
generates an immediate error with the following traceback:

C:\Guiplottest.py
Traceback :
   File "C:\GuiPlotTest.py", line 19, in 
  data = INTData("C:\SomeRawDataFile.int")
NameError: name 'INTData' is not defined


But "INTData" is defined...it's defined in "DataFileTypes" from which
I've imported everything. What's happening here? Thanks in advance!

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


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Martin v. Löwis

> u'\xb5'
>> u'\xb5'
> print u'\xb5'
>> �
> 
> Unicode literals are *in the source file*, which can only have one
> encoding (for a given source file).
> 
>> (That last character shows up as a micron sign despite the fact that
>> my default encoding is ascii, so it seems to me that that unicode
>> string must somehow have picked up a latin-1 encoding.)
> 
> I think latin-1 was the default without a coding cookie line.  (May be
> uft-8 in 3.0).

It is, but that's irrelevant for the example. In the source

  u'\xb5'

all characters are ASCII (i.e. all of "letter u", "single
quote", "backslash", "letter x", "letter b", "digit 5").
As a consequence, this source text has the same meaning in all
supported source encodings (as source encodings must be ASCII
supersets).

The Unicode literal shown here does not get its interpretation
from Latin-1. Instead, it directly gets its interpretation from
the Unicode coded character set. The string is a short-hand
for

 u'\u00b5'

and this denotes character U+00B5 (just as u'\u20ac" denotes
U+20AC; the same holds for any other u'\u').

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


count secton of data in list

2009-02-20 Thread brianrpsgt1
I have a list of three columns of data.  I run the following code:

def step1(val):
for d1r in data1_row:
if d1r[1] >= val:
switch = 0
data2_row = d1r[0],d1r[1],d1r[2],switch
print d1r[0],d1r[1],d1r[2],switch
else:
switch = 1
print d1r[0],d1r[1],d1r[2],switch

step1(95)

After running that code I get four columns with either a '0' or '1' in
the 4th column, as shown below

2009-01-09 13:17:30 96 123456 0
2009-01-09 13:17:31 95 123456 0
2009-01-09 13:17:32 95 123456 0
2009-01-09 13:17:33 95 123456 0
2009-01-09 13:17:34 94 123456 1
2009-01-09 13:17:35 94 123456 1
2009-01-09 13:17:36 94 123456 1
2009-01-09 13:17:37 94 123456 1
2009-01-09 13:17:38 94 123456 1
2009-01-09 13:17:39 94 123456 1
2009-01-09 13:17:40 94 123456 1
2009-01-09 13:17:41 94 123456 1
2009-01-09 13:17:42 95 123456 0
2009-01-09 13:17:43 95 123456 0
2009-01-09 13:17:44 95 123456 0
2009-01-09 13:17:45 95 123456 0

Where I am getting stuck is that I now need to get the individual
counts for the various consecutive areas in the list where the values
are '1'.  I was trying to run a FOR Loop on the variable data2_row
but that does not work.  Any assistance would be great.

Thanks:
B

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


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Martin v. Löwis
> Yes, I know that.  But every concrete representation of a unicode string 
> has to have an encoding associated with it, including unicode strings 
> produced by the Python parser when it parses the ascii string "u'\xb5'"
> 
> My question is: what is that encoding?

The internal representation is either UTF-16, or UTF-32; which one is
a compile-time choice (i.e. when the Python interpreter is built).

> Put this another way: I would have thought that when the Python parser 
> parses "u'\xb5'" it would produce the same result as calling 
> unicode('\xb5'), but it doesn't.

Right. In the former case, \xb5 denotes a Unicode character, namely
U+00B5, MICRO SIGN. It is the same as u"\u00b5", and still the same
as u"\N{MICRO SIGN}". By "the same", I mean "the very same".

OTOH, unicode('\xb5') is something entirely different. '\xb5' is a
byte string with length 1, with a single byte with the numeric
value 0xb5, or 181. It does not, per se, denote any specific character.
It only gets a character meaning when you try to decode it to unicode,
which you do with unicode('\xb5'). This is short for

  unicode('\xb5', sys.getdefaultencoding())

and sys.getdefaultencoding() is (or should be) "ascii". Now, in
ASCII, byte 0xb5 does not have a meaning (i.e. it does not denote
a character at all), hence you get a UnicodeError.

> Instead it seems to produce the same 
> result as calling unicode('\xb5', 'latin-1').

Sure. However, this is only by coincidence, because latin-1 has the same
code points as Unicode (for 0..255).

> But my default encoding 
> is not latin-1, it's ascii.  So where is the Python parser getting its 
> encoding from?  Why does parsing "u'\xb5'" not produce the same error as 
> calling unicode('\xb5')?

Because \xb5 *directly* refers to character U+00b5, with no
byte-oriented encoding in-between.

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


Re: Implementaion of random.shuffle

2009-02-20 Thread Scott David Daniels

Steven D'Aprano wrote:

On Wed, 18 Jul 2007 19:32:35 +, George Sakkis wrote:
...

Wow, can you make a coffee in.. 57ms ?

[snip demonstration of xrange raising an exception]
Of course! Can't you?

And if I use a microwave oven, 

[*** deleted section outlining Guido's time machine structure ***]

Steve, consider yourself warned!!!

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


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
And finally, an epilogue.

So, the problem lies with how Python cached the modules in memory.
Yes, the modules were in two different locations and yes, the one that
I specified using its direct path should be the one loaded. The
problem is, the module isn't always loaded -- if it's already in
memory, it'll use that instead. And since the modules had the same
name, Python wouldn't distinguish between them, even though they
weren't exactly the same. So, loading the module act1/story would load
act1/story. Then, loading the module act2/story would use the story
module already in memory. Of course, this made the problem hard to
pinpoint, since memory is a fickle thing, and the results weren't
always reproducible.

The final solution? Renaming the 'story' modules to 'story_1' and
'story_2'... and importing them via 'exec("from story_"+modulename+"
import game")'.

Will I go to hell for this 'solution'? Probably. But hey, it means I
can go home tonight instead of spending all evening at the office
hitting my head against the wall. I'll come back to it Monday and try
to figure out a more reasonable solution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Matthew Woodcraft
Ron Garret  writes:
> Put this another way: I would have thought that when the Python parser
> parses "u'\xb5'" it would produce the same result as calling
> unicode('\xb5'), but it doesn't. Instead it seems to produce the same
> result as calling unicode('\xb5', 'latin-1'). But my default encoding
> is not latin-1, it's ascii. So where is the Python parser getting its
> encoding from? Why does parsing "u'\xb5'" not produce the same error
> as calling unicode('\xb5')?

There is no encoding involved other than ascii, only processing of a
backslash escape.

The backslash escape '\xb5' is converted to the unicode character whose
ordinal number is B5h. This gives the same result as
"\xb5".decode("latin-1") because the unicode numbering is the same as
the 'latin-1' numbering in that range.

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


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Dan Goodman
This sounds kind of similar to a problem I posted to this list last 
year, you might find that thread gives you some ideas:


http://mail.python.org/pipermail/python-list/2008-January/474071.html

Dan

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


Re: Threading and tkinter

2009-02-20 Thread Craig Allen

> The statement
>
>     x=x+1
>
> (which, by the way, should stylistically be written
>
>     x = x + 1
>

yes I was wondering what "x=x+1" meant until you translated it... oh,
"x = x + 1" of course! I thought to myself.

Oh wait no I'm sarcastic.
--
http://mail.python.org/mailman/listinfo/python-list


Re: can multi-core improve single funciton?

2009-02-20 Thread Grant Edwards
On 2009-02-20, Robert Kern  wrote:
>
>> Do the crunchy bits of scipy/numpy, scientific python, vtk and
>> other compute-intensive libraries tend to release the GIL
>> while they're busy "computing"?
>
> Often. Not as often as they could, sometimes.

On one hand, the upshot of that is that by finding an
appropriate library module you might gain some of the same
benefits as removing the GIL.

On the other hand, that doesn't help if you're doing something
original enough that nobody has written a library to handle
large chunks of it.

And on the grasping hand, I find that most of us vastly
overestimate the originality of what we're doing.

-- 
Grant Edwards   grante Yow! This is a NO-FRILLS
  at   flight -- hold th' CANADIAN
   visi.comBACON!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread andrew cooke
from subsequent posts i think you were looking for something "smarter"
than my streams, but i was interested in the idea, so i wrote an
implementation.  hope this is ok - if you don't want to see a worked
solution, read no further...

i have been using generators a lot recently; now that i understand them
better i really like the "laziness" they give.  this code is perhaps more
like you would see in haskell than in python...

some results from the code as below:

 -725 = (((1)+(1))+((1)+(1)))-(((1)+(2))^((2)*(3)))  (length 8)
...
   -2 = (1)-(3)   (length 2)
   -1 = (1)-(2)   (length 2)
0 = (1)-(1)   (length 2)
1 = 1 (length 1)
2 = 2 (length 1)
3 = 3 (length 1)
4 = (1)+(3)   (length 2)
...
  972 = (((1)+(1))+((1)+(1)))*(((1)+(2))^((2)+(3)))  (length 8)

note that because this is a brute-force search it is limited in the number
of combinations it considers (for a given "take", below), and not at all
"smart" (in preferring pow over other values for example), so the extreme
values are nothing like optimal (the final invocation, commented out, uses
sorting to improve things).

also, complex and float values are generated; i discard those with a
filter, but you can drop that if you are curious.


#!/usr/bin/python3

'''
See
http://groups.google.com/group/comp.lang.python/browse_thread/thread/b387f99deb376392

This is a brute force approach using streams, implemented
with generators.
'''

from operator import add, sub, mul, truediv as div, pow


OPERATORS = [('+', add), ('-', sub), ('*', mul),
 ('/', div), ('^', pow)]
START = [(str(i), 1, i) for i in [1,2,3]]


def all_operators(stream):
'''
Generate new values by combining the values in 'stream' in
all the different ways possible.
'''
for (exprn, length, value) in stream:
for (symbol, op) in OPERATORS:
for (exprn2, length2, value2) in stream:
try:
yield ('({0}){1}({2})'.format(
exprn, symbol, exprn2),
   length + length2,
   op(value, value2))
except Exception as e:
#print('Ignoring {}',format(e))
pass


def repeat(generator, preproc=lambda x: x):
'''
Make a generator 'eat its own tail', primed with 'start'.
All output is kept and fed back into the generator as input.   Note
that memory use increases steadily.
'''
def repeater(start):
start = preproc(start)
for value in start:
yield value
while True:
finish = []
for value in generator(start):
yield value
finish.append(value)
start = finish
return repeater



def value(elv):
'''
Pick the value from an elv triplet.
'''
(exprn, length, value) = elv
return value


def take(n):
'''
Build a filter that takes the first n values from a stream.
'''
def taker(stream, n=n):
while n > 0:
yield next(stream)
n -= 1
return taker


def mkfilter(predicate):
'''
Curry Python's filter function.
'''
def myfilter(stream):
return filter(lambda elv: predicate(value(elv)), stream)
return myfilter


def compose(*filters):
'''
Compose several filters to give a new filter.
(Is there a better way to write this?)
'''
def composer(iter1, iter2):
def composed(stream):
for value in iter1(iter2(stream)):
yield value
return composed
if len(filters) == 1:
return filters[0]
else:
return composer(filters[0], compose(*filters[1:]))


def summarise(stream):
'''
Group values by value, keeping the shortest expression,
then print everything.
'''
exprns = {}
lengths = {}
for (exprn, length, value) in stream:
if value not in exprns or length < lengths[value]:
exprns[value] = exprn
lengths[value] = length
values = [value for value in exprns if type(value) is int]
for value in sorted(values):
print('{0:>5} = {1:20}  (length {2})'.format(
value, exprns[value], lengths[value]))


if __name__ == '__main__':
ints = mkfilter(lambda x: type(x) is int)
small = mkfilter(lambda x: abs(x) < 1000)
# this gets very slow after 2 values
#summarise(compose(take(2),
#  repeat(compose(ints,
# all_operators)))(START))
# clipping values to below 1000 makes things much faster
# note 200,000 below, 20,000 above!
summarise(compose(take(20),
  repeat(compose(ints, small,
 all_operators)))(START))
# get to larger values faster by sorting in the repeat
#sort = lambda x: sorted(x, ke

python-list@python.org

2009-02-20 Thread Steve Holden
Allen wrote:
> I am using Python with cx_oracle to load an excel spreadsheet into an
> Oracle table. There are lots of text on the spreadsheet that have "&"
> in them which I want to keep in the table. But inserting those text
> will fail.

Why do you say that?

> Is there a work around for this? I can filter out the
> failed insert statements and in SQLPLUS set define off  to run those
> statements, but it would be nice to insert "&" directly in PYTHON.
> 
regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: can multi-core improve single funciton?

2009-02-20 Thread Robert Kern

On 2009-02-20 13:20, Unknown wrote:

On 2009-02-20, Aahz  wrote:

Steven D'Aprano  wrote:


As I understand it, there's very little benefit to multi-cores
in Python due to the GIL.

As phrased, your statement is completely wrong.  Here's a more
correct phrasing: "For threaded compute-bound applications
written in pure Python, there's very little benefit to
multiple cores." But threaded I/O-bound applications do
receive some benefit from multiple cores, and using multiple
processes certainly leverages multiple cores.  If boosting the
performance of a threaded compute-bound application is
important, one can always write the critical parts in C/C++.


Do the crunchy bits of scipy/numpy, scientific python, vtk and
other compute-intensive libraries tend to release the GIL while
they're busy "computing"?


Often. Not as often as they could, sometimes.

--
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: What encoding does u'...' syntax use?

2009-02-20 Thread Terry Reedy

Ron Garret wrote:
I would have thought that the answer would be: the default encoding 
(duh!)  But empirically this appears not to be the case:



unicode('\xb5')

Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: 
ordinal not in range(128)


The unicode function is usually used to decode bytes read from *external 
sources*, each of which can have its own encoding.  So the function 
(actually, developer crew) refuses to guess and uses the ascii common 
subset.



u'\xb5'

u'\xb5'

print u'\xb5'

�


Unicode literals are *in the source file*, which can only have one 
encoding (for a given source file).


(That last character shows up as a micron sign despite the fact that my 
default encoding is ascii, so it seems to me that that unicode string 
must somehow have picked up a latin-1 encoding.)


I think latin-1 was the default without a coding cookie line.  (May be 
uft-8 in 3.0).


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


Re: function factory question: embed current values of object attributes

2009-02-20 Thread Terry Reedy

Alan Isaac wrote:

I have a class `X` where many parameters are set
at instance initialization.  The parameter values
of an instance `x` generally remain unchanged,


'Parameters' are the function local names in the header that get bound 
to argument objects when the function is called.  What you are 
describing are 'attributes'.



but is there way to communicate to a method that
it depends only on the initial values of these parameters
(and does not need to worry about any changes)?


In the terms stated, no.


The behavior of method `m` depends on these parameter values.
It turns out `m` gets called a lot, which means
that the pameter values are accessed over and over
(self.p0, self.p1, etc).  I would like to
manufacture a function equivalent to the method
that simply uses fixed values (the values at the
time it is manufactured).


You are now describing a function closure.  Here is an example that 
might help.


def f_maker(a1, a2):
  def _(b): return a1*b + a2
  return _

class C:
  def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
self.f = f_maker(attr1, attr2)

c = C(2,3)
print(*(c.f(i) for i in range(5)))

# 3 5 7 9 11

Having f use both initial and 'current' attribute values would be a bit 
trickier ;-)


Terry Jan Reedy

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


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
>
> 'req.write(story.game.Save())' returns '/home/www/--/docs/act2/
> storylab/game.pyc' as the file being accessed.
>

Sorry, that should have read:
> 'req.write(story.game.Save())' returns 
> '/home/www/--/docs/act2/story/game.pyc' as the file being accessed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
Son of a bitch. It gets worse.

> Executed from inside 'act1', which contains the directory / module
> 'story':
>
>         directory = os.path.dirname(__file__)
>         req.write(str(directory))
>         story = apache.import_module('story', path=[directory])
>
> Results:
>
>   /home/www/---/docs/act1
>
>   File "/home/www/---/docs/act1/play.py", line 24, in Rebuild
>     storylab = apache.import_module('story', path=[directory])
>
>   File "/usr/local/python2.5.2/lib/python2.5/site-packages/mod_python/
> importer.py", line 304, in import_module
>     return __import__(module_name, {}, {}, ['*'])
>
> ImportError: No module named story
>

If I execute the exact same code from the 'act1' directory after
running it from the 'act2' directory, it successfully loads the
'story' module... from 'act2'. Even though I used the Apache importer
to specify the EXACT LOCATION of the module to import.

'req.write(str(os.path.dirname(__file__)))' returns '/home/www/---/
docs/act1'.

'req.write(story.game.Save())' returns '/home/www/--/docs/act2/
storylab/game.pyc' as the file being accessed.

BLOODY HELL.

Okay, deep breath.

Does anyone know what's going on? Am I just not understanding how
module importing in mod_python works? I'd really appreciate help,
since I'll be stuck at work today until I can get this sorted out, and
I've long since run out of ideas.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
And more madness...

Executed from inside 'act1', which contains the directory / module
'story':


directory = os.path.dirname(__file__)
req.write(str(directory))
story = apache.import_module('story', path=[directory])


Results:


  File "/home/www/---/docs/act1/play.py", line 24, in Rebuild
storylab = apache.import_module('story', path=[directory])

  File "/usr/local/python2.5.2/lib/python2.5/site-packages/mod_python/
importer.py", line 304, in import_module
return __import__(module_name, {}, {}, ['*'])

ImportError: No module named story


Awesome. I'm going to go stick my head through a wall.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Ron Garret
In article <499f18bd$0$31879$9b4e6...@newsspool3.arcor-online.net>,
 Stefan Behnel  wrote:

> Ron Garret wrote:
> > I would have thought that the answer would be: the default encoding 
> > (duh!)  But empirically this appears not to be the case:
> > 
>  unicode('\xb5')
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: 
> > ordinal not in range(128)
>  u'\xb5'
> > u'\xb5'
>  print u'\xb5'
> > µ
> > 
> > (That last character shows up as a micron sign despite the fact that my 
> > default encoding is ascii, so it seems to me that that unicode string 
> > must somehow have picked up a latin-1 encoding.)
> 
> You are mixing up console output and internal data representation. What you
> see in the last line is what the Python interpreter makes of your unicode
> string when passing it into stdout, which in your case seems to use a
> latin-1 encoding (check your environment settings for that).
> 
> BTW, Unicode is not an encoding. Wikipedia will tell you more.

Yes, I know that.  But every concrete representation of a unicode string 
has to have an encoding associated with it, including unicode strings 
produced by the Python parser when it parses the ascii string "u'\xb5'"

My question is: what is that encoding?  It can't be ascii.  So what is 
it?

Put this another way: I would have thought that when the Python parser 
parses "u'\xb5'" it would produce the same result as calling 
unicode('\xb5'), but it doesn't.  Instead it seems to produce the same 
result as calling unicode('\xb5', 'latin-1').  But my default encoding 
is not latin-1, it's ascii.  So where is the Python parser getting its 
encoding from?  Why does parsing "u'\xb5'" not produce the same error as 
calling unicode('\xb5')?

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


Re: Python 3D CAD -- need collaborators, or just brave souls :)

2009-02-20 Thread Dotan Cohen
> Even 3DS or Maya is easier to learn that Blender.
>

Notepad is easier to learn that VI. Not a good program does simple make.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Stefan Behnel
Stefan Behnel wrote:
> print u'\xb5'
>> µ
> 
> What you
> see in the last line is what the Python interpreter makes of your unicode
> string when passing it into stdout, which in your case seems to use a
> latin-1 encoding (check your environment settings for that).

The "seems to" is misleading. The example doesn't actually tell you
anything about the encoding used by your console, except that it can
display non-ASCII characters.

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


Re: What encoding does u'...' syntax use?

2009-02-20 Thread Stefan Behnel
Ron Garret wrote:
> I would have thought that the answer would be: the default encoding 
> (duh!)  But empirically this appears not to be the case:
> 
 unicode('\xb5')
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: 
> ordinal not in range(128)
 u'\xb5'
> u'\xb5'
 print u'\xb5'
> µ
> 
> (That last character shows up as a micron sign despite the fact that my 
> default encoding is ascii, so it seems to me that that unicode string 
> must somehow have picked up a latin-1 encoding.)

You are mixing up console output and internal data representation. What you
see in the last line is what the Python interpreter makes of your unicode
string when passing it into stdout, which in your case seems to use a
latin-1 encoding (check your environment settings for that).

BTW, Unicode is not an encoding. Wikipedia will tell you more.

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


Re: Framework installation of 2.6 on OS X, with specified prefix

2009-02-20 Thread Ned Deily
In article ,
 Evert Rol  wrote:
> I'm trying to install Python 2.6 from source on Mac OS X.5, in its own  
> directory using a framework install. That goes fine, up to the point  
> where it wants to install the applications that come with it (eg, the  
> Wish shell): it tries to install things into /Applications, instead of  
> eg /Applications.
> Here's my configure line (the flags are there just to let it find my  
> own installed readline):
> 
> CPPFLAGS=-I/sw/include LDFLAGS=-L/sw/lib ./configure --prefix=/sw -- 
> enable-shared --enable-framework=/sw/Library/Frameworks --with- 
> readline=/sw --with-pth CC=gcc-4.2  MACOSX_DEPLOYMENT_TARGET=10.5
> 
> 
> And the last part of the output of 'make install':
> 
> ../python.exe ./scripts/BuildApplet.py \
>   --destroot "" \
>   --python=/sw/Library/Frameworks/Python.framework/Versions/2.6/ 
> Resources/Python.app/Contents/MacOS/Python`test -f "/sw/Library/ 
> Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/ 
> MacOS/Python-32" && echo "-32"`  \
>   --output "/sw/Applications/Python 2.6/Build Applet.app" \
>   ./scripts/BuildApplet.py
> cd PythonLauncher && make install DESTDIR=
> test -d "/Applications/Python 2.6" || mkdir -p "/Applications/Python  
> 2.6"
> mkdir: /Applications/Python 2.6: Permission denied
> make[2]: *** [install] Error 1
> make[1]: *** [install_PythonLauncher] Error 2
> make: *** [frameworkinstallapps] Error 2
> 
> Is there an option on the configure line that I need to set, or  
> something in setup.py? Or perhaps hack the Makefile?

FWIW, the OS X build-installer.py script handles this by specifying a 
DESTDIR on the make install steps rather than including a --prefix on 
the configure.   See Mac/BuildScript/build-installer.py.

-- 
 Ned Deily,
 n...@acm.org

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


Re: To unicode or not to unicode

2009-02-20 Thread Martin v. Löwis
Ron Garret wrote:
> In article <499f0cf0.8070...@v.loewis.de>,
>  "Martin v. Löwis"  wrote:
> 
> 
> I'm the OP.  I'm using MT-Newswatcher 3.5.1.  I thought I had it 
> configured properly, but I guess I didn't.

Probably you did. However, it then means that the newsreader is crap.

> Under 
> Preferences->Languages->Send Messages with Encoding I had selected 
> latin-1.

That sounds like early nineties, before the invention of MIME.

> I didn't know I also needed to have MIME turned on for that to 
> work.  I've turned it on now.  Is this better?
> 
> This should be a micro sign: µ

Not really (it's worse, from my point of view - but might be better
for others). You are now sending in UTF-8, but there is still no
MIME declaration in the news headers. As a consequence, my newsreader
continues to interpret it as Latin-1 (which it assumes as the default
encoding), and it comes out as moji-bake (in responding, my reader
should declare the encoding properly, so you should see what I see,
namely A-circumflex, micro sign)

If you look at the message headers / message source as sent e.g.
by MRAB, you'll notice lines like

MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

These lines are missing from your posting.

Assuming the newsreader is not crap, it might help to set the default
send encoding to ASCII. When sending micro sign, the newsreader might
infer that ASCII is not good enough, and use MIME - although it then
still needs to pick an encoding.

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


Re: Will multithreading make python less popular?

2009-02-20 Thread rushenaly
I want to correct my last post where i said that there is not any
intend to remove GIL from python. There is an intend actually i wish
from a wizard :).
On the pypy blog there is an explanation about gil and pypy
"Note that multithreading in PyPy is based on a global interpreter
lock, as in CPython. I imagine that we will get rid of the global
interpreter lock at some point in the future -- I can certainly see
how this might be done in PyPy, unlike in CPython -- but it will be a
lot of work nevertheless. Given our current priorities, it will
probably not occur soon unless someone steps in."
Nothing new about GIL and Cpython and even PyPy

Thank you...
Rushen

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


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
Here's another clue: if I'm trying to run the script from the
directory 'act1', but it's loading the module from 'act2', if I rename
the module directory in 'act2' and refresh, the module still reports
that it's running from '/home/www/---/docs/act2/story/game.pyc'...
even though that files no longer exists. If I refresh a few more
times, both 'act1' and 'act2' will load the module from 'act1's
directory (even though the directory doesn't appear in sys.path when
you try to load it from 'act2').

So, Python is trying to import a module from a directory that isn't in
sys.path, and will generally default to running the module from the
directory where it was last run. If I run it from 'act1', then 'act2',
both times it will load the module from 'act1'. If I do it the other
way around, it will load the module from 'act2' both times.

The question now is... why is it loading from a directory that isn't
in sys.path? How can I avoid this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: To unicode or not to unicode

2009-02-20 Thread Ron Garret
In article <499f0cf0.8070...@v.loewis.de>,
 "Martin v. Löwis"  wrote:

> MRAB wrote:
> > Thorsten Kampe wrote:
> >> * Ron Garret (Thu, 19 Feb 2009 18:57:13 -0800)
> >>> I'm writing a little wiki that I call µWiki.  That's a lowercase
> >>> Greek mu at the beginning (it's pronounced micro-wiki). 
> >>
> >> No, it's not. I suggest you start your Unicode adventure by
> >> configuring your newsreader.
> >>
> > It looked like mu to me, but you're correct: it's "MICRO SIGN", not
> > "GREEK SMALL LETTER MU".
> 
> I don't think that was the complaint. Instead, the complaint was
> that the OP's original message did not have a Content-type header,

I'm the OP.  I'm using MT-Newswatcher 3.5.1.  I thought I had it 
configured properly, but I guess I didn't.  Under 
Preferences->Languages->Send Messages with Encoding I had selected 
latin-1.  I didn't know I also needed to have MIME turned on for that to 
work.  I've turned it on now.  Is this better?

This should be a micro sign: µ

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


Re: To unicode or not to unicode

2009-02-20 Thread Martin v. Löwis
MRAB wrote:
> Thorsten Kampe wrote:
>> * Ron Garret (Thu, 19 Feb 2009 18:57:13 -0800)
>>> I'm writing a little wiki that I call µWiki.  That's a lowercase
>>> Greek mu at the beginning (it's pronounced micro-wiki). 
>>
>> No, it's not. I suggest you start your Unicode adventure by
>> configuring your newsreader.
>>
> It looked like mu to me, but you're correct: it's "MICRO SIGN", not
> "GREEK SMALL LETTER MU".

I don't think that was the complaint. Instead, the complaint was
that the OP's original message did not have a Content-type header,
and that it was thus impossible to tell what the byte in front of
"Wiki" meant. To properly post either MICRO SIGN or GREEK SMALL LETTER
MU in a usenet or email message, you really must use MIME. (As both
your article and Thorsten's did, by choosing UTF-8)

Regards,
Martin

P.S. The difference between MICRO SIGN and GREEK SMALL LETTER MU
is nit-picking, IMO:

py> unicodedata.name(unicodedata.normalize("NFKC", u"\N{MICRO SIGN}"))
'GREEK SMALL LETTER MU'
--
http://mail.python.org/mailman/listinfo/python-list


What encoding does u'...' syntax use?

2009-02-20 Thread Ron Garret
I would have thought that the answer would be: the default encoding 
(duh!)  But empirically this appears not to be the case:

>>> unicode('\xb5')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: 
ordinal not in range(128)
>>> u'\xb5'
u'\xb5'
>>> print u'\xb5'
µ

(That last character shows up as a micron sign despite the fact that my 
default encoding is ascii, so it seems to me that that unicode string 
must somehow have picked up a latin-1 encoding.)

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


Re: To unicode or not to unicode

2009-02-20 Thread Ron Garret
In article ,
 MRAB  wrote:

> Thorsten Kampe wrote:
> > * Ron Garret (Thu, 19 Feb 2009 18:57:13 -0800)
> >> I'm writing a little wiki that I call µWiki.  That's a lowercase Greek 
> >> mu at the beginning (it's pronounced micro-wiki). 
> > 
> > No, it's not. I suggest you start your Unicode adventure by configuring 
> > your newsreader.
> > 
> It looked like mu to me, but you're correct: it's "MICRO SIGN", not
> "GREEK SMALL LETTER MU".

Heh, I didn't know that those two things were distinct.  Learn something 
new every day.

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


Re: can multi-core improve single funciton?

2009-02-20 Thread Grant Edwards
On 2009-02-20, Aahz  wrote:
> Steven D'Aprano   wrote:
>
>> As I understand it, there's very little benefit to multi-cores
>> in Python due to the GIL. 
>
> As phrased, your statement is completely wrong.  Here's a more
> correct phrasing: "For threaded compute-bound applications
> written in pure Python, there's very little benefit to
> multiple cores." But threaded I/O-bound applications do
> receive some benefit from multiple cores, and using multiple
> processes certainly leverages multiple cores.  If boosting the
> performance of a threaded compute-bound application is
> important, one can always write the critical parts in C/C++.

Do the crunchy bits of scipy/numpy, scientific python, vtk and
other compute-intensive libraries tend to release the GIL while
they're busy "computing"?

[Perhaps using them doesn't count as "pure Python", but...]

-- 
Grant Edwards   grante Yow! NEWARK has been
  at   REZONED!!  DES MOINES has
   visi.combeen REZONED!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression bug?

2009-02-20 Thread umarpy

More elegant way

>>> [x for x in re.split('([A-Z]+[a-z]+)', a) if x ]
['foo', 'Bar', 'Baz']

R.

On Feb 20, 2:03 pm, Lie Ryan  wrote:
> On Thu, 19 Feb 2009 13:03:59 -0800, Ron Garret wrote:
> > In article ,
> >  Peter Otten <__pete...@web.de> wrote:
>
> >> Ron Garret wrote:
>
> >> > I'm trying to split a CamelCase string into its constituent
> >> > components.
>
> >> How about
>
> >> >>> re.compile("[A-Za-z][a-z]*").findall("fooBarBaz")
> >> ['foo', 'Bar', 'Baz']
>
> > That's very clever.  Thanks!
>
> >> > (BTW, I tried looking at the source code for the re module, but I
> >> > could not find the relevant code.  re.split calls
> >> > sre_compile.compile().split, but the string 'split' does not appear
> >> > in sre_compile.py.  So where does this method come from?)
>
> >> It's coded in C. The source is Modules/sremodule.c.
>
> > Ah.  Thanks!
>
> > rg
>
> This re.split() doesn't consume character:
>
> >>> re.split('([A-Z][a-z]*)', 'fooBarBaz')
>
> ['foo', 'Bar', '', 'Baz', '']
>
> it does what the OP wants, albeit with extra blank strings.

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


Re: Find the location of a loaded module

2009-02-20 Thread Aaron Scott
Okay, I'm going out of my mind. I have three directories -- 'act1',
'act2', and 'act3'. Each of these has a module named 'story'.

Through mod_python, I need to load 'story' in the directory 'act1'. I
do it like this:

req.content_type = "text/html"
sys.path.append(os.path.dirname( __file__ ))
req.write(str(sys.path))
import story
req.write(story.game.Save())
sys.path.pop()

According to sys.path, these are Python's paths:

['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/
plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-
dynload', '/usr/lib/python2.5/site-packages', '/usr/local/python2.5.2/
lib/python2.5/', '/home/www/---/docs/act1']

story.game.Save() returns the location of the story.game module, which
is reported as '/home/www/---/docs/act1/story/game.pyc'. So far so
good.

Now, I'll try the same thing from the 'act2' directory. These are the
paths reported in sys.path:

['/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/
plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-
dynload', '/usr/lib/python2.5/site-packages', '/usr/local/python2.5.2/
lib/python2.5/', '/home/www/---/docs/act2']

All good, right? Not so fast. Here's what story.game.Save() returns as
its location: '/home/www/---/docs/act1/story/game.pyc'.

Which means it's loading the 'story' module from the old location,
even though that location is no longer in the path.

If I refresh a couple times, eventually it loads the module from the
proper directory ('act2'). Then, I'll go back to the first directory,
and find that it too will be loading the module from 'act2'. I'll
refresh, and it'll load from 'act1' again. I'll refresh a couple
times, and suddenly it's loading from 'act2' again.

I'm seriously going insane. If anyone has any insight, please, please
share it with me.

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


function factory question: embed current values of object attributes

2009-02-20 Thread Alan Isaac

I have a class `X` where many parameters are set
at instance initialization.  The parameter values
of an instance `x` generally remain unchanged,
but is there way to communicate to a method that
it depends only on the initial values of these parameters
(and does not need to worry about any changes)?

The behavior of method `m` depends on these parameter values.
It turns out `m` gets called a lot, which means
that the pameter values are accessed over and over
(self.p0, self.p1, etc).  I would like to
manufacture a function equivalent to the method
that simply uses fixed values (the values at the
time it is manufactured).  I do not care if this
function is attached to `x` or not.

I have a feeling that I am turning something simple
into something complex, perhaps for lack of an
afternoon coffee or lack of CS training.  Suggestions
appreciated.

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


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Paddy O'Loughlin
2009/2/20 Bruno Desthuilliers :
> Check by yourself:
>
 import inspect
 inspect.isfunction(property)
> False
Using this, every single builtin function returns False. That's a
pretty limited definition to be being pedantic over, especially when
they are in the "Built-in Functions" section of the manual.

 property()
> 
I never said that calling it didn't return a property object :)

>>> property


So it's a type.
I think I didn't make such a bad error on my part. My intent in what I
was saying was to indicate that I hadn't created a property type. It's
fair enough to consider type constructors as functions given how they
are listed as such by the python documentation.
I don't think that your correction was much help, unless you just want
to say that everything is an object. Maybe you'd be right, but it's
not much use to use the term that way, imo



 dir(property)
> ['__class__', '__delattr__', '__delete__', '__doc__', '__get__',
> '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__str__', 'fdel',
> 'fget', 'fset']

Doesn't prove a whole lot. So types have attributes...
So do functions:
>>> def myfunc():
... pass
...
>>> dir(myfunc)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']


>> Hmm, it doesn't seem to me like it's much of a big deal, for it to
>> described as anything like a "GoldenRule"
>
> One could say the same for each and any of the usual GoldenRules(tm).
Not really. To do so would be over-generalising and not useful to discussion
I guess it's your pedantry that I'm questioning.
Something like "don't use goto's" works as a GoldenRule because it's
been observed that without it, people start using goto statements in
places where it's not really appropriate.
When you said that "[you] usually shouldn't [use properties] - unless
you have a very compelling reason", your tone implied that properties
are easy to misuse and tend to be.
Not being familiar with properties and seeing them as being pretty
harmless, I was intrigued by this, which is why I asked for an
explanation.
Your explanation seems to show that your tone was likely to be more
personal bias than any real issue with properties.

Paddy

-- 
"Ray, when someone asks you if you're a god, you say YES!"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find the location of a loaded module

2009-02-20 Thread Christian Heimes
Aaron Scott schrieb:
> I'm running into a problem that's rapidly reaching keyboard-smashing
> levels. I'm trying to import a module into Python, but it seems like
> Python is almost randomly loading the module from an entirely
> different directory, one that shouldn't be in the module search path.
> 
> When I tell Python to load a module, is there a way to tell which
> directory the module was loaded from?

All except builtin modules have an attribute __file__ that points to the
file.

Christian

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


Find the location of a loaded module

2009-02-20 Thread Aaron Scott
I'm running into a problem that's rapidly reaching keyboard-smashing
levels. I'm trying to import a module into Python, but it seems like
Python is almost randomly loading the module from an entirely
different directory, one that shouldn't be in the module search path.

When I tell Python to load a module, is there a way to tell which
directory the module was loaded from?
--
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to add a property to an instance?

2009-02-20 Thread Alan Isaac

Darren Dale wrote to GHUM:

Sorry, that's an attribute, not a property.



This is a question about terminology.
In contrast to Darren's recommended usage,
I have run into the following.

If hasattr(x,'a') is True, for instance object `x`,
then `a` is an attribute of `x`.
Attributes are data attributes or callable attributes.
Data attributes are variables or properties.
Callable attributes are usually method attributes.

This seemed about right to me, but a better
(or "official") taxonomy would be welcome.

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


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Tim Wintle
On Fri, 2009-02-20 at 16:38 +, Nigel Rantor wrote:
> Luke Dunn wrote:



That was my initial thought when I read this too - but I'm not certain
that is guaranteed to find a solution (i.e. a solution that's optimal).

I'd welcome a proof that it will though, a few minutes thought hasn't
found a counter-example.

> > yes power towers are allowed
> 
> right, okay, without coding it here's my thought.
> 
> factorise the numbers you have but only allowing primes that exist in 
> your digit set.
> 
> then take that factorisation and turn any repeated runs of digits 
> multiplied by themselves into power-towers
> 
> any remainder can then be created in other ways, starting with a way 
> other than exponentiation that is able to create the largest number, 
> i.e. multiplication, then addition...
> 
> I've not got time to put it into code right now  but it shouldn't be too 
> hard...
> 
> e.g.
> 
> digits : 3, 2, 1
> 
> n : 10
> 10 = 2*5 - but we don't have 5...
> 10 = 3*3 + 1
> 10 = 3^2+1
> 3 digits
> 
> n : 27
> 27 = 3*3*3
> 27 = 3^3
> 2 digits
> 
> n : 33
> 33 = 3*3*3 + 6
> 33 = 3*3*3 + 3*2
> 33 = 3^3+3*2
> 4 digits
> 
> > exponentiation, multiplication, division, addition and subtraction. 
> > Brackets when necessary but length is sorted on number of digits not 
> > number of operators plus digits.
> >  
> > I always try my homework myself first. in 38 years of life I've 
> > learned only to do what i want, if I wanted everyone else to do my work 
> > for me I'd be a management consultant !
> > On Fri, Feb 20, 2009 at 3:52 PM, Luke Dunn  > > wrote:
> > 
> > I am teaching myself coding. No university or school, so i guess its
> > homework if you like. i am interested in algorithms generally, after
> > doing some of Project Euler. Of course my own learning process is
> > best served by just getting on with it but sometimes you will do
> > that while other times you might just choose to ask for help. if no
> > one suggests then i will probably shelve it and come back to it
> > myself when I'm fresh.
> >  
> > no it's not a real world problem but my grounding is in math so i
> > like pure stuff anyway. don't see how that is a problem, as a math
> > person i accept the validity of pure research conducted just for
> > curiosity and aesthetic satisfaction. it often finds an application
> > later anyway
> >  
> > Thanks for your helpful suggestion of trying other methods and i
> > will do that in time. my motive was to share an interesting problem
> > because a human of moderate math education can sit down with this
> > and find minimal solutions easily but the intuition they use is
> > quite subtle, hence the idea of converting the human heuristic into
> > an algorithm became of interest, and particularly a recursive one. i
> > find that the development of a piece of recursion usually comes as
> > an 'aha', and since i hadn't had such a moment, i thought i'd turn
> > the problem loose on the public. also i found no online reference to
> > this problem so it seemed ripe for sharing.
> > 
> > On Fri, Feb 20, 2009 at 3:39 PM, Nigel Rantor  > > wrote:
> > 
> > Trip Technician wrote:
> > 
> > anyone interested in looking at the following problem.
> > 
> > 
> > if you can give me a good reason why this is not homework I'd
> > love to hear it...I just don't see how this is a real problem.
> > 
> > 
> > we are trying to express numbers as minimal expressions
> > using only the
> > digits one two and three, with conventional arithmetic. so for
> > instance
> > 
> > 33 = 2^(3+2)+1 = 3^3+(3*2)
> > 
> > are both minimal, using 4 digits but
> > 
> > 33 = ((3+2)*2+1)*3
> > 
> > using 5 is not.
> > 
> > I have tried coding a function to return the minimal
> > representation
> > for any integer, but haven't cracked it so far. The naive first
> > attempt is to generate lots of random strings, eval() them
> > and sort by
> > size and value. this is inelegant and slow.
> > 
> > 
> > Wow. Okay, what other ways have you tried so far? Or are you
> > beating your head against the "search the entire problem space"
> > solution still?
> > 
> > This problem smells a lot like factorisation, so I would think
> > of it in terms of wanting to reduce the target number using as
> > few operations as possible.
> > 
> > If you allow exponentiation that's going to be your biggest
> > hitter so you know that the best you can do using 2 digits is
> > n^n where n is the largest digit you allow yourself.
> > 
> > Are you going to allow things like n^n^n or not?
> > 
> >  n
> > 
> > 
> > 
> > 
> 
> --
> http://m

Re: How Can I run some Python Scripts in VS C++?

2009-02-20 Thread david
On Feb 20, 11:12 am, "Gabriel Genellina" 
wrote:
> En Fri, 20 Feb 2009 15:47:06 -0200, david  escribió:
>
> > Basically I have some python scripts to do some document processing,
> > all in command line tho.
> > I want to have an C++ application so that my scripts can run in dialogs
> > (API).
> > I saw a post before using c# to run python scripts within the c# main.
> > I am willing to run my python scripts within c++.
> > Thanks.
>
> So you want to execute a Python script, in a different process, as if you  
> typed the command line?
> That's not different to executing any other external program in C# - in  
> fact is a C# question, no Python involved. Try something like this:
>
>      Process p = new Process();
>      p.StartInfo.FileName = "path\to\python.exe";
>      p.StartInfo.Arguments = "path\to\your\script.py other arguments";
>      p.Start();
>      p.WaitForExit();
>      p.Close()
>
> There are other properties you may want to use, like  
> RedirectStandardOutput; see the C# documentation.
>
> --
> Gabriel Genellina

Thanks so much. I'll give it a try :)
Best Regards.

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


Re: Killing subservient threads

2009-02-20 Thread jimzat
On Feb 20, 11:21 am, "Gabriel Genellina" 
wrote:
> 1) make the child window set a flag in the thread (let's say, t.terminate  
> = True). And make the polling thread check the flag periodically (you  
> possibly already have a loop there - just break the loop when you detect  
> that self.terminate became true)
>
> 2) catching an exception is as easy as enclosing the code in a try/except  
> block. And "commit suicide" is just "exit from the run() method".

Gabriel,

I am using the thread module and calling thread.start_new_thread
(...).  If I use t=thread.start_new_thread(...) and later set
t.terminate, I get "AttributeError: 'int' object has no attribute
'terminate'"

What is the proper way to do this?  I don't want to use globals as I
will have multiple child windows of various classes.


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


Re: Killing subservient threads

2009-02-20 Thread jimzat
On Feb 20, 11:22 am, koranthala  wrote:
>
> thread.setDaemon(True)
> Makes it a daemon thread which means that interpreter will not stay
> alive if only that thread is alive.

My main window is used to launch multiple children and therefore when
one is dismissed the interpreter will remain active.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How Can I run some Python Scripts in VS C++?

2009-02-20 Thread Gabriel Genellina

En Fri, 20 Feb 2009 15:47:06 -0200, david  escribió:


Basically I have some python scripts to do some document processing,
all in command line tho.
I want to have an C++ application so that my scripts can run in dialogs
(API).
I saw a post before using c# to run python scripts within the c# main.
I am willing to run my python scripts within c++.
Thanks.


So you want to execute a Python script, in a different process, as if you  
typed the command line?
That's not different to executing any other external program in C# - in  
fact is a C# question, no Python involved. Try something like this:


Process p = new Process();
p.StartInfo.FileName = "path\to\python.exe";
p.StartInfo.Arguments = "path\to\your\script.py other arguments";
p.Start();
p.WaitForExit();
p.Close()

There are other properties you may want to use, like  
RedirectStandardOutput; see the C# documentation.


--
Gabriel Genellina

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


Re: can multi-core improve single funciton?

2009-02-20 Thread Aahz
In article ,
Steven D'Aprano   wrote:
>
>As I understand it, there's very little benefit to multi-cores in Python 
>due to the GIL. 

As phrased, your statement is completely wrong.  Here's a more correct
phrasing: "For threaded compute-bound applications written in pure
Python, there's very little benefit to multiple cores."  But threaded
I/O-bound applications do receive some benefit from multiple cores, and
using multiple processes certainly leverages multiple cores.  If boosting
the performance of a threaded compute-bound application is important, one
can always write the critical parts in C/C++.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: To unicode or not to unicode

2009-02-20 Thread MRAB

Thorsten Kampe wrote:

* Ron Garret (Thu, 19 Feb 2009 18:57:13 -0800)
I'm writing a little wiki that I call µWiki.  That's a lowercase Greek 
mu at the beginning (it's pronounced micro-wiki). 


No, it's not. I suggest you start your Unicode adventure by configuring 
your newsreader.



It looked like mu to me, but you're correct: it's "MICRO SIGN", not
"GREEK SMALL LETTER MU".
--
http://mail.python.org/mailman/listinfo/python-list


Re: To unicode or not to unicode

2009-02-20 Thread Thorsten Kampe
* Ron Garret (Thu, 19 Feb 2009 18:57:13 -0800)
> I'm writing a little wiki that I call µWiki.  That's a lowercase Greek 
> mu at the beginning (it's pronounced micro-wiki). 

No, it's not. I suggest you start your Unicode adventure by configuring 
your newsreader.

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


Re: How Can I run some Python Scripts in VS C++?

2009-02-20 Thread david
>
> No: please explain in more detail what you want to do.
>
> --
> Gabriel Genellina

Thanks for the fast reply Gabriel,
Basically I have some python scripts to do some document processing,
all in command line tho.
I want to have an C++ application so that my scripts can run in dialogs
(API).
I saw a post before using c# to run python scripts within the c# main.
I am willing to run my python scripts within c++.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Bruno Desthuilliers

Paddy O'Loughlin a écrit :

2009/2/20 Bruno Desthuilliers :

Interesting. Why shouldn't you?
I haven't used the property() function

s/function/object/


Nice try, but what I wrote was what I intended to say:
http://docs.python.org/library/functions.html#property


Check by yourself:

>>> import inspect
>>> inspect.isfunction(property)
False
>>> property()

>>> dir(property)
['__class__', '__delattr__', '__delete__', '__doc__', '__get__', 
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__set__', '__setattr__', '__str__', 
'fdel', 'fget', 'fset']

>>>



The case is that the whole point of using a computed attribute is to perform
some computation on the value. IOW, except for a couple corner cases, only
the accessors should directly access the implementation(s) attributes(s).

And of course, like for any other GoldenRule(tm), it's not meant to be
blindly followed. It's just that most of the times, going thru the accessors
is really what you want - even from within the class code.


Hmm, it doesn't seem to me like it's much of a big deal, for it to
described as anything like a "GoldenRule"


One could say the same for each and any of the usual GoldenRules(tm).
--
http://mail.python.org/mailman/listinfo/python-list


pymssql text type

2009-02-20 Thread marc wyburn
Hi, I'm trying to pass a text blob to MS SQL Express 2008 but get the
follwoing error.

(, OperationalError("SQL Server
message 102, severity 15, state 1, line 1:\nIncorrect syntax near
'assigned'.\n",), )

the string it is having an issue with is

(\r\n\r\n\tLogon ID:\t\t(0x0,0xE892A8)\r\n\r\n\tLogon Type:\t2\r\n\r
\n')

It looks like SQL is reading the blob, finding the newline codes and
generating an error.  Is there anyway I can get it to ignore the text
and just enter the whole sentance as a string.  I think that some
automatic character encodign might be taking place hence the string is
being read but I can work out whether I need to character encode in
Python, change a table setting in SQL or do something to pymssql.

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


Re: Killing subservient threads

2009-02-20 Thread Christian Heimes
Gabriel Genellina wrote:
> 1) make the child window set a flag in the thread (let's say,
> t.terminate = True). And make the polling thread check the flag
> periodically (you possibly already have a loop there - just break the
> loop when you detect that self.terminate became true)

threading.Condition() and threading.Event() are especially designed for
the job. Please use them appropriately.

Christian

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


Re: Keeping the Console Open with IDLE

2009-02-20 Thread W. eWatson

W. eWatson wrote:

David Smith wrote:

W. eWatson wrote:

I'm not sure whether I should feel old or write a smart alec comment --
I suppose there are people in the world who don't know what to do 
with a

command prompt

Assuming a Windows system:

2. Type 'cd ' (as in Change Directory) in the command prompt window 
(w/o

the single quote characters)
3. Drag/drop the folder containing your python script to your command
prompt window
4. Hit enter in your command prompt window.
5. Type python my_script_name.py to execute my_script_name.py.

--David

If I enter just cd, then it tells me cd is not defined. If I enter
c:/python25, it tells me I have a syntax error at c in c:. The title of
the black background window I have up with a >>> prompt shown in it is
"Python(command line)". Maybe this isn't the real Python console window?

What I want is that if I execute the program by double clicking on its
name to display the console window with the program or syntax errors
shown without it closing in a split second. Putting read_raw in it
doesn't work, since some error prevents it from ever being seen.



What I meant was open open the command prompt, type cd, space, DO NOT
hit enter yet.  Drag the folder with your script into the command prompt
window.  Then go to the command prompt window and hit enter.  This
should compose a command similar to the following:

C:\Documents and Settings\user> cd "C:\Documents and Settings\user\My
Documents\My Project"

C:\Documents and Settings\user\My Documents\My Project> _

--David
Ah, I thought I'd be clever and do a copy on the path name in the 
address area at the top of the folder. That doesn't work. I'm quite 
surprised though that one can do the drag as you say. But, hey, it 
works. Thanks. I wonder what else non-DOS things can be done in it?


Well, there is a difficulty with this method. The path is very long, and one 
must change the property width of the window. However, putting the name of a 
long py file further complicates this.


The negative surprise here is that I'm trying to avoid executing the program 
in IDLE, because I'm told elsewhere it produced erroneous error msgs. They 
are exactly the same here. I'll take this up on another thread.




--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: How Can I run some Python Scripts in VS C++?

2009-02-20 Thread Gabriel Genellina

En Fri, 20 Feb 2009 15:14:52 -0200, bing  escribió:


Hi, I have some simple python scripts, anyone knows how to run the
Python Scripts in C++?
Any code example would be really helpful and appreciated.


Do you want to write a C++ application, and allow your users to write  
scripts in Python, possibly exposing some objects from you application?


Yes: read the "Extending and Embedding" document, specially the "Embedding  
part" (last)



No: please explain in more detail what you want to do.

--
Gabriel Genellina

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


Re: Killing subservient threads

2009-02-20 Thread koranthala
On Feb 20, 9:47 pm, jimzat  wrote:
> I am trying to create an app which will have a main window from which
> the user will launch other (children) windows.
>
> When I launch the child window I start a new thread which periodically
> polls another device and updates the child window accordingly.  When I
> dismiss the child window the "polling" thread stays alive and then
> crashes with an exception when trying to write to the now defunct
> child window.
>
> How can I handle this?  I want to either 1) have the destructor for
> the child window kill the spawned thread or 2) catch the exception
> within the "polling" thread and see that the child window is gone and
> then commit suicide.
>
> I am an experienced embedded C programmer but have VERY little
> experience with GUI programming and no experience in the Micro$oft
> programming world.

thread.setDaemon(True)
Makes it a daemon thread which means that interpreter will not stay
alive if only that thread is alive.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing subservient threads

2009-02-20 Thread Gabriel Genellina

En Fri, 20 Feb 2009 14:47:27 -0200, jimzat  escribió:


I am trying to create an app which will have a main window from which
the user will launch other (children) windows.

When I launch the child window I start a new thread which periodically
polls another device and updates the child window accordingly.  When I
dismiss the child window the "polling" thread stays alive and then
crashes with an exception when trying to write to the now defunct
child window.

How can I handle this?  I want to either 1) have the destructor for
the child window kill the spawned thread or 2) catch the exception
within the "polling" thread and see that the child window is gone and
then commit suicide.


1) make the child window set a flag in the thread (let's say, t.terminate  
= True). And make the polling thread check the flag periodically (you  
possibly already have a loop there - just break the loop when you detect  
that self.terminate became true)


2) catching an exception is as easy as enclosing the code in a try/except  
block. And "commit suicide" is just "exit from the run() method".


--
Gabriel Genellina

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


How Can I run some Python Scripts in VS C++?

2009-02-20 Thread bing
Hi, I have some simple python scripts, anyone knows how to run the
Python Scripts in C++?
Any code example would be really helpful and appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Keeping the Console Open with IDLE

2009-02-20 Thread MRAB

Catherine Heathcote wrote:

W. eWatson wrote:

Catherine Heathcote wrote:

W. eWatson wrote:




I'm not sure whether I should feel old or write a smart alec 
comment --
I suppose there are people in the world who don't know what to do 
with a

command prompt

Assuming a Windows system:

2. Type 'cd ' (as in Change Directory) in the command prompt window 
(w/o

the single quote characters)
3. Drag/drop the folder containing your python script to your command
prompt window
4. Hit enter in your command prompt window.
5. Type python my_script_name.py to execute my_script_name.py.

--David
If I enter just cd, then it tells me cd is not defined. If I enter 
c:/python25, it tells me I have a syntax error at c in c:. The title 
of the black background window I have up with a >>> prompt shown in 
it is "Python(command line)". Maybe this isn't the real Python 
console window?


What I want is that if I execute the program by double clicking on 
its name to display the console window with the program or syntax 
errors shown without it closing in a split second. Putting read_raw 
in it doesn't work, since some error prevents it from ever being seen.




you need to open a dos prompt before doing the steps above. Go to 
start->run and hit "cmd"  without the quotes.
Something is amiss here. There's the MS Command Prompt, which I'm 
looking at right now. Yes, it has cd, and so on. I'm also looking at 
the Python command line window. It allow one to run interactively.


If I write a simple python program with just raw_input, by clicking on 
the file name, I get a window with the the title "\Python25\pythonexe" 
that shows the prompt. If I deliberately put a syntax error in the 
program, and run it by clicking the file, then A window appears and 
disappears so quickly that I have no idea what it said. How do I keep 
that window up?


Which, if any, of these is the real Python console? What is the window 
called in the example I gave with raw_input?




Run the program from within the MS command line, not by double clicking it.


Or create a .bat file containing the commands to run the Python program,
ending with the command "pause", which will wait for you to press a key
when the program has quit.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Paddy O'Loughlin
2009/2/20 Bruno Desthuilliers :
>> Interesting. Why shouldn't you?
>> I haven't used the property() function
>
> s/function/object/

Nice try, but what I wrote was what I intended to say:
http://docs.python.org/library/functions.html#property

For all I know I could have used property objects several times in modules :)

> The case is that the whole point of using a computed attribute is to perform
> some computation on the value. IOW, except for a couple corner cases, only
> the accessors should directly access the implementation(s) attributes(s).
>
> And of course, like for any other GoldenRule(tm), it's not meant to be
> blindly followed. It's just that most of the times, going thru the accessors
> is really what you want - even from within the class code.

Hmm, it doesn't seem to me like it's much of a big deal, for it to
described as anything like a "GoldenRule" or to advise against its
overuse.
You use it when its appropriate and don't use it when you it's not,
like any other feature.

Paddy


-- 
"Ray, when someone asks you if you're a god, you say YES!"
--
http://mail.python.org/mailman/listinfo/python-list


Killing subservient threads

2009-02-20 Thread jimzat
I am trying to create an app which will have a main window from which
the user will launch other (children) windows.

When I launch the child window I start a new thread which periodically
polls another device and updates the child window accordingly.  When I
dismiss the child window the "polling" thread stays alive and then
crashes with an exception when trying to write to the now defunct
child window.

How can I handle this?  I want to either 1) have the destructor for
the child window kill the spawned thread or 2) catch the exception
within the "polling" thread and see that the child window is gone and
then commit suicide.

I am an experienced embedded C programmer but have VERY little
experience with GUI programming and no experience in the Micro$oft
programming world.

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


python-list@python.org

2009-02-20 Thread Allen
I am using Python with cx_oracle to load an excel spreadsheet into an
Oracle table. There are lots of text on the spreadsheet that have "&"
in them which I want to keep in the table. But inserting those text
will fail. Is there a work around for this? I can filter out the
failed insert statements and in SQLPLUS set define off  to run those
statements, but it would be nice to insert "&" directly in PYTHON.

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


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Nigel Rantor

Trip Technician wrote:


yes n^n^n would be fine. agree it is connected to factorisation.
building a tree of possible expressions is my next angle.


I think building trees of the possible expressions as a couple of other 
people have suggested is simply a more structured way of doing what 
you're currnetly doing.


Right now you're throwing darts at the problem space, and hoping that 
the next one point you hit will be a more optimal solution.


If you enumerate all the expression trees you are just ensuring you 
don't miss any solutions.


I think the algorithm/hueristic I just posted should get you to the 
answer quicker though...


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


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Nigel Rantor

Luke Dunn wrote:

yes power towers are allowed


right, okay, without coding it here's my thought.

factorise the numbers you have but only allowing primes that exist in 
your digit set.


then take that factorisation and turn any repeated runs of digits 
multiplied by themselves into power-towers


any remainder can then be created in other ways, starting with a way 
other than exponentiation that is able to create the largest number, 
i.e. multiplication, then addition...


I've not got time to put it into code right now  but it shouldn't be too 
hard...


e.g.

digits : 3, 2, 1

n : 10
10 = 2*5 - but we don't have 5...
10 = 3*3 + 1
10 = 3^2+1
3 digits

n : 27
27 = 3*3*3
27 = 3^3
2 digits

n : 33
33 = 3*3*3 + 6
33 = 3*3*3 + 3*2
33 = 3^3+3*2
4 digits

exponentiation, multiplication, division, addition and subtraction. 
Brackets when necessary but length is sorted on number of digits not 
number of operators plus digits.
 
I always try my homework myself first. in 38 years of life I've 
learned only to do what i want, if I wanted everyone else to do my work 
for me I'd be a management consultant !
On Fri, Feb 20, 2009 at 3:52 PM, Luke Dunn > wrote:


I am teaching myself coding. No university or school, so i guess its
homework if you like. i am interested in algorithms generally, after
doing some of Project Euler. Of course my own learning process is
best served by just getting on with it but sometimes you will do
that while other times you might just choose to ask for help. if no
one suggests then i will probably shelve it and come back to it
myself when I'm fresh.
 
no it's not a real world problem but my grounding is in math so i

like pure stuff anyway. don't see how that is a problem, as a math
person i accept the validity of pure research conducted just for
curiosity and aesthetic satisfaction. it often finds an application
later anyway
 
Thanks for your helpful suggestion of trying other methods and i

will do that in time. my motive was to share an interesting problem
because a human of moderate math education can sit down with this
and find minimal solutions easily but the intuition they use is
quite subtle, hence the idea of converting the human heuristic into
an algorithm became of interest, and particularly a recursive one. i
find that the development of a piece of recursion usually comes as
an 'aha', and since i hadn't had such a moment, i thought i'd turn
the problem loose on the public. also i found no online reference to
this problem so it seemed ripe for sharing.

On Fri, Feb 20, 2009 at 3:39 PM, Nigel Rantor mailto:wig...@wiggly.org>> wrote:

Trip Technician wrote:

anyone interested in looking at the following problem.


if you can give me a good reason why this is not homework I'd
love to hear it...I just don't see how this is a real problem.


we are trying to express numbers as minimal expressions
using only the
digits one two and three, with conventional arithmetic. so for
instance

33 = 2^(3+2)+1 = 3^3+(3*2)

are both minimal, using 4 digits but

33 = ((3+2)*2+1)*3

using 5 is not.

I have tried coding a function to return the minimal
representation
for any integer, but haven't cracked it so far. The naive first
attempt is to generate lots of random strings, eval() them
and sort by
size and value. this is inelegant and slow.


Wow. Okay, what other ways have you tried so far? Or are you
beating your head against the "search the entire problem space"
solution still?

This problem smells a lot like factorisation, so I would think
of it in terms of wanting to reduce the target number using as
few operations as possible.

If you allow exponentiation that's going to be your biggest
hitter so you know that the best you can do using 2 digits is
n^n where n is the largest digit you allow yourself.

Are you going to allow things like n^n^n or not?

 n






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


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Trip Technician
On 20 Feb, 15:39, Nigel Rantor  wrote:
> Trip Technician wrote:
> > anyone interested in looking at the following problem.
>
> if you can give me a good reason why this is not homework I'd love to
> hear it...I just don't see how this is a real problem.
>
>
>
>
>
> > we are trying to express numbers as minimal expressions using only the
> > digits one two and three, with conventional arithmetic. so for
> > instance
>
> > 33 = 2^(3+2)+1 = 3^3+(3*2)
>
> > are both minimal, using 4 digits but
>
> > 33 = ((3+2)*2+1)*3
>
> > using 5 is not.
>
> > I have tried coding a function to return the minimal representation
> > for any integer, but haven't cracked it so far. The naive first
> > attempt is to generate lots of random strings, eval() them and sort by
> > size and value. this is inelegant and slow.
>
> Wow. Okay, what other ways have you tried so far? Or are you beating
> your head against the "search the entire problem space" solution still?
>
> This problem smells a lot like factorisation, so I would think of it in
> terms of wanting to reduce the target number using as few operations as
> possible.
>
> If you allow exponentiation that's going to be your biggest hitter so
> you know that the best you can do using 2 digits is n^n where n is the
> largest digit you allow yourself.
>
> Are you going to allow things like n^n^n or not?
>
>    n- Hide quoted text -
>
> - Show quoted text -

yes n^n^n would be fine. agree it is connected to factorisation.
building a tree of possible expressions is my next angle.
--
http://mail.python.org/mailman/listinfo/python-list


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread Trip Technician
On 20 Feb, 16:02, Paul Rubin  wrote:
> Trip Technician  writes:
> > I have a dim intuition that it could be done with a very clever bit of
> > recursion, but the exact form so far eludes me.
>
> This sounds a little like a homework assignment, or maybe a challenge
> you are trying to solve for yourself, rather than be given a complete
> answer for.  Anyway, the basic idea is to enumerate the expression
> trees with 1 digit, then 2 digits, then 3 digits, etc, and compute the
> value expressed by each tree.

Thanks will get onto it. It's just a challenge I set myself so hints
only are cool.
--
http://mail.python.org/mailman/listinfo/python-list


Re: code challenge: generate minimal expressions using only digits 1,2,3

2009-02-20 Thread andrew cooke

this is a neat problem.

here is what i would do: use generators that extend an input.  a stream
approach.  the initial input would be the numbers themselves.

[('1', 1),('2', 2),('3', 3)]

those are (expression, value) pairs

then an initial attempt at the next function would be to extend that list
with additions:

def additions(pairs):
  for (expr1, value1) in pairs:
# first, pass through unchanged
yield (expr1, value1)
# then generate all possible additions
for (expr2, value2) in pairs:
  yield ('%s+%s'%(value1, value2), value1 + value2))

this would give you:

[('1', 1),('2', 2),('3', 3), ('1+1', 2), ...]

(you may need to add parentheses to expressions to preserve meaning
correctly)

you could extend that with an extra loop over different operations.
(subtraction, multiplication, etc)

then you could repeat that as often as you want (eating its own tail, in a
sense, i think).  an infinite list is ok because these are generators.

then you could filter that to group expressions that give a certain value,
and find the shortest.

andrew



Trip Technician wrote:
> anyone interested in looking at the following problem.
>
> we are trying to express numbers as minimal expressions using only the
> digits one two and three, with conventional arithmetic. so for
> instance
>
> 33 = 2^(3+2)+1 = 3^3+(3*2)
>
> are both minimal, using 4 digits but
>
> 33 = ((3+2)*2+1)*3
>
> using 5 is not.
>
> I have tried coding a function to return the minimal representation
> for any integer, but haven't cracked it so far. The naive first
> attempt is to generate lots of random strings, eval() them and sort by
> size and value. this is inelegant and slow.
>
> I have a dim intuition that it could be done with a very clever bit of
> recursion, but the exact form so far eludes me.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Re: get most common number in a list with tolerance

2009-02-20 Thread Tim Rowe
2009/2/20 Astan Chee :
> Hi,
> I have a list that has a bunch of numbers in it and I want to get the most
> common number that appears in the list. This is trivial because i can do a
> max on each unique number. What I want to do is to have a tolerance to say
> that each number is not quite unique and if the difference from other
> numbers is small, than it can be counted together. This is what I have to
> get the common number (taken from the internet somewhere):
>
> l = [10,30,20,20,11,12]
> d = {}
> tolerance = 5
> for elm in l:
>   d[elm] = d.get(elm, 0) + 1
> counts = [(j,i) for i,j in d.items()]
>
>
>
> This of course returns a list where each of them is unique
>
> [(1, 12), (1, 10), (1, 11), (2, 20), (1, 30)]
>
> but I am expecting a list that looks like this:
>
> [(3, 10), (2, 20), (1, 30)]

Why only the points 10, 20 and 30? what has happened to (3,11), for
example? (10, 11 and 12 are all within 11+/-5)

It seems you are trying to do one of two things. Either you are trying
to form a histogram with data bands +/-tolerance, or you are trying to
do something like kernel smoothing with a rectangular kernel.

What would you expect the output to be if the data set were
[10,30,20,20,11,12,13] and the tolerance were 2?

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


  1   2   >