Re: Advice on how to get started with 2D-plotting ?

2011-09-06 Thread CM
> Now, for my work, I would need to learn the basics fast, for a one-time
> quick-n-dirty job.
>
> This involves a graphic comparison of RFC1918 IP subnets allocation across
> several networks.
>
> The idea is to draw parallel lines, with segments (subnets) coloured green,
> yellow or red depending on the conflicts between the networks.
>
> What would be the simplest/fastest way of getting this done ?
> (the graphic parts, the IP stuff I know how to handle)

AFAIK, probably Matplotlib.  I'm not sure what
quite to imagine for your plot but below is code
that makes an attempt at (maybe) something like
you are describing, shown here:

http://www.flickr.com/photos/67254913@N07/6123112552/in/photostream#/

There are smarter ways to do this in matplotlib, but
this is pretty quick and dirty.  I'm just plotting
lines over-top other lines.  The pic I put is the
plot as a .png, which matplotlib makes if you want,
but you can also view it in a frame that matplotlib
generates and then pan/zoom/etc...


from pylab import *

x = [1,2,3,4,5,6,7,8]
y = [2 for num in x]

#plot the parallel lines themselves in green
for num in range(6):
y = [num for item in x]
plot(x,y,color='g',lw='4')

#plot any conflict sections in red or yellow
#some hard data to give the idea:
x2 = [3,4]
y2 = [2 for num in x2]
x3 = [5,6,7]
y3 = [4 for num in x3]
x4 = [2,3]
y4 = [3 for num in x4]

#plot these three colored parts over the green lines
plot(x2,y2,color='r',lw='12')
plot(x3,y3,color='yellow',lw='12')
plot(x4,y4,color='r',lw='12')

pos = arange(6)
yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6'))

show()

#-

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


Re: Representation of floats (-> Mark Dickinson?)

2011-09-06 Thread jmfauth
On 7 sep, 05:58, casevh  wrote:

> ...

>
> Also note that 1.1 * 1.1 is not the same as 1.21.
>
> >>> (1.1 * 1.1).as_integer_ratio()
>
> (5449355549118301, 4503599627370496)>>> (1.21).as_integer_ratio()
>
> (1362338887279575, 1125899906842624)
>
> This doesn't explain why 2.7.2 displayed a different result on your
> computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and
> (1.21)?
>


Sure. I just picked up these numbers/expressions by chance. They
came to my mind following the previous discussion.

Sticking with the latest versions:


>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> (1.1 * 1.1).as_integer_ratio()
(5449355549118301L, 4503599627370496L)
>>> (1.21).as_integer_ratio()
(1362338887279575L, 1125899906842624L)
>>>



>>> sys.version
'3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]'
>>> (1.1 * 1.1).as_integer_ratio()
(5449355549118301, 4503599627370496)
>>> (1.21).as_integer_ratio()
(1362338887279575, 1125899906842624)
>>>


Has "long" not disappeared 2.7?
I have not the skill to dive into the machinery. I have
only some theroretical understanding and I'm a little bit
confused and have to face "there something strange
somewhere".

Test on Windows 7, 32 bits.


jmf

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


Re: Advice on how to get started with 2D-plotting ?

2011-09-06 Thread CM
On Sep 6, 2:27 pm, Fred Pacquier  wrote:
> Hi,
>
> I'm a Python long-timer, but I've never had to use tools like Matplotlib &
> others before.
>
> Now, for my work, I would need to learn the basics fast, for a one-time
> quick-n-dirty job.
>
> This involves a graphic comparison of RFC1918 IP subnets allocation across
> several networks.
>
> The idea is to draw parallel lines, with segments (subnets) coloured green,
> yellow or red depending on the conflicts between the networks.
>
> What would be the simplest/fastest way of getting this done ?
> (the graphic parts, the IP stuff I know how to handle)


> Now, for my work, I would need to learn the basics fast, for a one-time
> quick-n-dirty job.
>
> This involves a graphic comparison of RFC1918 IP subnets allocation across
> several networks.
>
> The idea is to draw parallel lines, with segments (subnets) coloured green,
> yellow or red depending on the conflicts between the networks.
>
> What would be the simplest/fastest way of getting this done ?
> (the graphic parts, the IP stuff I know how to handle)

One fairly simple way is with Matplotlib.  Not sure
what quite to imagine for your plot but below is code
that makes an attempt at (maybe) something like
you are describing, shown here:

http://www.flickr.com/photos/67254913@N07/6123112552/in/photostream#/

There are fancier ways to do this in Matplotlib, but
this is pretty quick and dirty--I'm just plotting
lines over-top other lines.  The pic I put is the
plot as a .png, which matplotlib makes if you want,
but you can also view it in a frame that matplotlib
generates and then pan/zoom/etc... This is using the
pylab module, but you could also embed your plots in
a GUI if you prefer.


from pylab import *

#plot the parallel lines in green
x = [1,2,3,4,5,6,7,8]
y = [2 for num in x]
for num in range(6):
y = [num for item in x]
plot(x,y,color='g',lw='4')

#plot any conflict sections in red or yellow
#...some data to give the idea:
x2 = [3,4]
y2 = [2 for num in x2]
x3 = [5,6,7]
y3 = [4 for num in x3]
x4 = [2,3]
y4 = [3 for num in x4]

#plot three colored parts over the green lines
plot(x2,y2,color='r',lw='12')
plot(x3,y3,color='yellow',lw='12')
plot(x4,y4,color='r',lw='12')

#change y labels to meaningful labels
pos = arange(6)
yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6'))

show()

#-

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


Re: strange thing:

2011-09-06 Thread W. eWatson

On 9/6/2011 7:48 PM, Chris Angelico wrote:

On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson  wrote:

CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in
my spam on the net.


No, I didn't; as someone else pointed out, you'll get better results
asking on a dedicated Fortran list.

ChrisA

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


Re: Floating point multiplication in python

2011-09-06 Thread Steven D'Aprano
On Wed, 7 Sep 2011 02:07 am Thomas 'PointedEars' Lahn wrote:

> Thomas Rachel wrote:
> 
>> Now if you multiply two values with an error, the error also propagates
>> into the result - PLUs the result can have its own error source - in the
>> same order of magnitude.
>> 
>> (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e
>> or (2*a + e) * e.
> 
> Your explanation about floating-point precision, which I already knew
> about but have only scanned here – so it might be flawed as well –,
> notwithstanding, it is not clear to me at all what you are trying to prove
> there.
> 
> Computers (well, perhaps outside of mathematical software) do NOT compute
> an equation as humans would do, so the binomial theorem does NOT apply. 

I think you have misunderstood. The binomial theorem always applies. Any
time you multiply two numbers, both numbers can always be re-written as a
sum of two numbers:

10*5 = (6+4)*(2+3)

So a perfect square can always be re-written in the form where the binomial
theorem applies:

5*5 = (2+3)*(2+3)
25 = 2*2 + 2*3 + 3*2 + 3*3
25 = 4 + 6 + 6 + 9
25 = 25

The binomial theorem is not a part of the algorithm for performing
multiplication. It is part of the analysis of the errors that occur during
multiplication. The actual mechanics of how bits are flipped is irrelevant.

Any floating point number x should be considered as equal to (a+e), where a
is the number actually wanted by the user, and e the error term forced upon
the user by the use of binary floats. (If you're lucky, e=0.) Generally,
both a and e are unknown, but of course their sum is known -- it's just the
float x.

So given a float x, when you square it you get this:

Exact values: a*a = a**2

Float values: x*x = (a+e)(a+e)
  = a**2 + 2*a*e + e**2

So the error term has increased from e to (2*a*e+e**2). It is usual to
assume that e**2 is small enough that it underflows to zero, so we have the
error term e increasing to 2*a*e as a fairly simple estimate of the new
error.


> In an algorithm of the real implementation,
> 
>   (a + e) * (a + e)
> 
> would be computed as follows:
> 
>   b := a + e
>   c := b * b
> or
>   c := b + … + b
> 
> [add the value of `b' to the value of `b' (b−1) times, since binary logic
> does not support multiplication]

What you probably mean to say is that binary hardware usually implements
multiplication via repeated addition.

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

If you don't mean that, I can't imagine what you are trying to say.
Multiplication of numbers exists in any base, binary no less than decimal.


> IOW, the error does propagate into the result indeed, but not as you
> described.  Indeed, thanks to rounding on assignment and multiplication
> (i. e., setting register values or IEEE-754 floating-point mantissa and
> exponent), the error will be different, probably greater than you compute
> here.

There may be other sources of error, particularly when multiplying two
numbers of greatly different magnitudes, but that doesn't invalidate Thomas
Rachel's point (which is only an estimate, of course).

We can see how much error is actually there by using exact arithmetic:

Error in float 1.1:

>>> from fractions import Fraction as F
>>> >>> a = F(11, 10) 
>>> x = F.from_float(1.1)
>>> e = x - a
>>> print e
1/11258999068426240

Error in float 1.1*1.1:

>>> b = F(11, 10)**2
>>> y = F.from_float(1.1**2)
>>> f = y - b
>>> print f
21/112589990684262400

which is slightly more than double e above, and slightly less than our
estimate of 2*a*e = 11/56294995342131200

So we can conclude that, at least for 1.1**2, Python floats are more
accurate than we would expect from a simple application of the binomial
theorem. (For implementations using IEEE doubles.)


-- 
Steven

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


Re: sqlite3 with context manager

2011-09-06 Thread Tim Arnold

On 9/3/2011 3:03 AM, Carl Banks wrote:

On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote:

Hi,
I'm using the 'with' context manager for a sqlite3 connection:

with sqlite3.connect(my.database,timeout=10) as conn:
  conn.execute('update config_build set datetime=?,result=?
where id=?',
(datetime.datetime.now(), success,
self.b['id']))

my question is what happens if the update fails? Shouldn't it throw an
exception?


If you look at the sqlite3 syntax documentation, you'll see it has a SQL 
extension that allows you to specify error semantics.  It looks something like 
this:

UPDATE OR IGNORE
UPDATE OR FAIL
UPDATE OR ROLLBACK

I'm not sure exactly how this interacts with pysqlite3, but using one of these 
might help it throw exceptions when you want it to.


Carl Banks


I see now. You can use 'update or fail' if you have the extensions built 
in: http://docs.python.org/library/sqlite3.html#f1


example of use, line 76:
http://projects.developer.nokia.com/TECwidget/browser/data/montreal/updsqlite.py?rev=7ca2ebd301ed1eff0e2c28283470db060b872cd6

For my case, however, I'll follow Ian's advice and check on the rowcount 
after the update.


thanks for the explanation and advice,
--Tim
--
http://mail.python.org/mailman/listinfo/python-list


Re: Representation of floats (-> Mark Dickinson?)

2011-09-06 Thread casevh
On Sep 6, 6:37 am, jmfauth  wrote:
> This is just an attempt to put 
> thehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
> discussion at a correct level.
>
> With Python 2.7 a new float number representation (the David Gay's
> algorithm)
> has been introduced. If this is well honored in Python 2.7, it
> seems to me, there are some missmatches in the Py3 series.
>
> >>> sys.version
>
> '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)]'
>
> >>> 0.1
> 0.10001
> >>> print 0.1
> 0.1
> >>> 1.1 * 1.1
> 1.2102
> >>> print 1.1 * 1.1
> 1.21
> >>> print repr(1.1 * 1.1)
> 1.2102
>
> >>> sys.version
>
> 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
>
>
>
> >>> 0.1
> 0.1
> >>> print 0.1
> 0.1
> >>> 1.1 * 1.1
> 1.21
> >>> print 1.1 * 1.1
> 1.21
> >>> print repr(1.1 * 1.1)
> 1.2102
>

I tried this with the same version of Python and I get:

>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> 1.1 * 1.1
1.2102
>>> print 1.1 * 1.1
1.21
>>> print repr(1.1 * 1.1)
1.2102
>>>

> >>> sys.version
>
> '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]'>>> 0.1
> 0.1
> >>> print(0.1)
> 0.1
> >>> 1.1 * 1.1
> 1.2102
> >>> print(1.1 * 1.1)
> 1.21
> >>> print(repr(1.1 * 1.1))
> 1.2102
> >>> '{:g}'.format(1.1 * 1.1)
>
> '1.21'
>
> >>> sys.version
>
> '3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]'
>
> >>> 0.1
> 0.1
> >>> print(0.1)
> 0.1
> >>> 1.1 * 1.1
> 1.2102
> >>> print (1.1 * 1.1)
> 1.2102
> >>> print(repr((1.1 * 1.1)))
> 1.2102
>
> >>> '{:g}'.format(1.1 * 1.1)
> '1.21'
>

I get same results as you do for Python 3.1.4 and 3.2.2. IIRC, Python
3.2 changed (for floats) __str__ to call __repr__. That should explain
the difference between 3.1.4 and 3.2.2

Also note that 1.1 * 1.1 is not the same as 1.21.

>>> (1.1 * 1.1).as_integer_ratio()
(5449355549118301, 4503599627370496)
>>> (1.21).as_integer_ratio()
(1362338887279575, 1125899906842624)

This doesn't explain why 2.7.2 displayed a different result on your
computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and
(1.21)?

casevh


> jmf

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


Re: import os or import os.path

2011-09-06 Thread Joe Riopel
On Tue, Sep 6, 2011 at 5:25 PM, Jabba Laci  wrote:
> Hi,
>
> If I want to use the 'os.path' module, it's enought to import 'os':
>
> import os
> if os.path.isfile('/usr/bin/bash'):
>    print 'got it'
>
> In other source codes I noticed that people write 'import os.path' in
> this case. Which is better practice?

I just followed what the help said:

""
DESCRIPTION
Instead of importing this module directly, import os and refer to
this module as os.path.
""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange thing:

2011-09-06 Thread Chris Angelico
On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson  wrote:
> CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in
> my spam on the net.

No, I didn't; as someone else pointed out, you'll get better results
asking on a dedicated Fortran list.

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


Re: strange thing:

2011-09-06 Thread W. eWatson
CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught 
in my spam on the net.

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


Looking for open-source Python projects to help out with

2011-09-06 Thread Littlefield, Tyler

Hello:
I've got a bit of time on my hands, so I'm curious what sorts of 
projects there are that people needs help with. I'd like to choose 
something that doesn't have a ton of red tape, but is stable, which is 
why I ask here instead of just Googling open source projects. My main 
interests lie in accessibility, Utilities and security.


--

Take care,
~Ty
Web: http://tds-solutions.net

Sent from my toaster.

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


Re: PEP 20 - Silly Question?

2011-09-06 Thread Joshua Miller
You sure it wasn't the invisible one? you know the one in the white
text that blends into the background?

On Tue, Sep 6, 2011 at 9:25 PM, MRAB  wrote:
> On 07/09/2011 01:36, Ben Finney wrote:
>>
>> Zero Piraeus  writes:
>>
>>> On 6 September 2011 12:17, Joseph Armbruster
>>>  wrote:

 I noticed that it says only 19 of 20 have been written down.  Which
 one was not written down?
>>>
>>> The last one.
>>
>> I always thought it was the first one. Or the 6.25th one, I forget.
>>
> Or the zeroth one.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 20 - Silly Question?

2011-09-06 Thread MRAB

On 07/09/2011 01:36, Ben Finney wrote:

Zero Piraeus  writes:


On 6 September 2011 12:17, Joseph Armbruster  wrote:

I noticed that it says only 19 of 20 have been written down.  Which
one was not written down?


The last one.


I always thought it was the first one. Or the 6.25th one, I forget.


Or the zeroth one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: import os or import os.path

2011-09-06 Thread Mark Hammond

On 7/09/2011 7:47 AM, Ian Kelly wrote:

On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci  wrote:

Hi,

If I want to use the 'os.path' module, it's enought to import 'os':

import os
if os.path.isfile('/usr/bin/bash'):
print 'got it'

In other source codes I noticed that people write 'import os.path' in
this case. Which is better practice?


"import os.path" is better practice.  There is no guarantee in general
that the os module will automatically import os.path, and in future
versions or different implementations it might not.


That's probably a matter of opinion - eg, 
http://docs.python.org/tutorial/interpreter.html has an example of 
importing the os module then accessing os.path.


Personally I think directly importing os.path is a waste of precious 
keystrokes ;)


Cheers,

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


Re: Can't use subprocess.Popen() after os.chroot() - why?

2011-09-06 Thread Nobody
On Sun, 04 Sep 2011 07:22:07 -0700, Erik wrote:

> I'm trying to do the following: 

> os.chroot("/tmp/my_chroot")
> p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE)

> but the Popen call is dying with the following exception:

> LookupError: unknown encoding: string-escape
> 
> Am I missing something here? does the chroot environment need to be
> populated with more than just the date executable in this case?

Yes. It also needs to include any parts of the Python run-time which
Python will try to load while executing subsequent code. In this case, the
module which implements the string-escape encoding.

But fixing that will probably show up yet more files which need to exist
within the pseudo-root. E.g. any shared libraries which the executable
needs (probably at least libc), and any data files which those libraries
need (in the case of /bin/date, it may need /etc/timezone; many programs
may require locale data if you aren't in the "C" locale, and so on).

Whether from Python or from C, chroot() requires a good understanding of
the low-level details of your operating system. If you don't know how to
build a minimal Linux distribution from scratch, you're going to have to
learn many of those details in order to use chroot().

For any non-trivial chroot() usage, it's often easier to install a small
newlib+busybox-based Linux distribution under the pseudo-root than to try
to re-use files from and existing (presumably glibc+coreutils-based)
desktop/server distribution.

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


Re: PEP 20 - Silly Question?

2011-09-06 Thread Ben Finney
Zero Piraeus  writes:

> On 6 September 2011 12:17, Joseph Armbruster  
> wrote:
> > I noticed that it says only 19 of 20 have been written down.  Which
> > one was not written down?
>
> The last one.

I always thought it was the first one. Or the 6.25th one, I forget.

-- 
 \“When in doubt tell the truth. It will confound your enemies |
  `\   and astound your friends.” —Mark Twain, _Following the Equator_ |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread Bart Kastermans
rantingrick  writes:

> On Sep 6, 5:00 pm, Bart Kastermans  wrote:
>> rantingrick  writes:
>> > Hmm, i can replace all that code with this...
>>
>> Because I stupidly forgot to repeat the original problem I had, and my
>> code doesn't show it (and doesn't show the correct use of the function I
>> wrote).
>
> Oh NOW i see! This new code you posted is like night and day compared
> to the original  :o)

Quite, I should know better (I deal with students thinking what is in
their mind should be clear to me all the time):


##
# run through all the data we have, compute the maximum height
max_ht = 0
for i in range(0,len(data)):
# lin.count is the line counting function
ct = lin.count(data[i], 450)
if ct > max_ht:
max_ht = ct

for i in range(0,min(len(data),5)):
# l is the Tkinter.Label with all formatting applied and data[i]
# set for text
l['height'] = max_ht# use this maximum height for all Labels.

###

Thinking on this some more, the first computation should surely be

max_ht = max (map (lambda x: lin.count(x, 450), data))


The second one could then be

labels = map (label_prepare_pack, data[:5])

where label_prepare_pack prepares (sets all attributes and data), packs,
and returns the new label.  The first (for max_ht) is a clear
improvement to me, the second (for labels) uses too many side-effects to
be very appealing to me.

> Anyway, i did not read the code to find the difference because i want
> to know why you insist on using multiple labels for this when a
> scrolled text will suffice. Are you trying to create some sort of
> textual "animation frames" that you can flip through on demand?

I don't follow precisely, but I am indeed looking to flip through all of
data while showing only 5 or 10 at a time.  The problem I wanted to
solve was that my window kept changing size while doing this.

> If not
> i would use the scrolled text (and even the scrolled text can "feel"
> like animation frames whist scrolling).
>
> Take your input data and replace ALL single newlines with null strings
> (thereby preserving paragraphs) and let the textbox control the line
> wrapping. The benefits are enormous using my way; your way is limited
> and requires re-inventing the wheel. Tell me WHY the textbox approach
> is not a viable solution and THEN i'll listen to you.

The reason I thought this, was that I didn't realize I could bind
actions to tags (to get different actions for different bits of text).
Now that I do know this I could use code like my lin.count to get the
maximum height still (to get a constant location for the i-th item as
the items are changed; more importantly to get a constant height for the
whole list of items), and then use tags to bind the corresponding
actions.

> Until then; you can lead a horse to water...

I certainly appreciate your trying.  I might not see the fresh stream
yet, but I do see liquid (possibly a shallow muddy pool, but big
progress from the dry sandy dunes before).  I will keep both approaches
in mind as I further develop.

Again, thanks for the help, greatly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
On Sep 6, 5:40 pm, rantingrick  wrote:
> On Sep 6, 5:00 pm, Bart Kastermans  wrote:

> Take your input data and replace ALL single newlines with null strings

CORRECTION: Take your input data and replace ALL single newlines with
A SINGLE SPACE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
On Sep 6, 5:00 pm, Bart Kastermans  wrote:
> rantingrick  writes:
> > Hmm, i can replace all that code with this...
>
> Because I stupidly forgot to repeat the original problem I had, and my
> code doesn't show it (and doesn't show the correct use of the function I
> wrote).

Oh NOW i see! This new code you posted is like night and day compared
to the original  :o)

Anyway, i did not read the code to find the difference because i want
to know why you insist on using multiple labels for this when a
scrolled text will suffice. Are you trying to create some sort of
textual "animation frames" that you can flip through on demand? If not
i would use the scrolled text (and even the scrolled text can "feel"
like animation frames whist scrolling).

Take your input data and replace ALL single newlines with null strings
(thereby preserving paragraphs) and let the textbox control the line
wrapping. The benefits are enormous using my way; your way is limited
and requires re-inventing the wheel. Tell me WHY the textbox approach
is not a viable solution and THEN i'll listen to you.

Until then; you can lead a horse to water...

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


Re: MIMEText encode error - Python 2.6.6

2011-09-06 Thread MRAB

On 06/09/2011 22:52, neubyr wrote:

I am trying to write a program which can email file's content using
smtplib. I am getting following error while using Python 2.6.6
version.

{{{
File "./killed_jobs.py", line 88, in sendmail
msg = MIMEText(ipfile.read, 'plain')
  File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py",
line 30, in __init__
self.set_payload(_text, _charset)
  File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py",
line 224, in set_payload
self.set_charset(charset)
  File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py",
line 266, in set_charset
cte(self)
  File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py",
line 73, in encode_7or8bit
orig.encode('ascii')
AttributeError: 'builtin_function_or_method' object has no attribute 'encode'

}}}


I am referring to email examples on the doc site
http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples
. Following is the msg object part in my code:

{{{
...
...
def sendmail(inputfile):
 ipfile = open(inputfile, 'r')
 msg = MIMEText(ipfile.read, 'plain')
 ipfile.close()

...
...
}}}

I have tried setting subtype and chartype separately as mentioned here
- http://docs.python.org/release/2.6.6/library/email.mime.html, but
the error remains same. Any help on what might be wrong here?


The docs say:

MIMEText(_text[, _subtype[, _charset]])

... _text is the string for the payload ...

You're passing ipfile.read, which is the read method of the file. You
should be passing the string returned by calling ipfile.read, ie
ipfile.read().
--
http://mail.python.org/mailman/listinfo/python-list


Re: Advice on how to get started with 2D-plotting ?

2011-09-06 Thread rantingrick
On Sep 6, 1:27 pm, Fred Pacquier  wrote:
> I'm a Python long-timer, but I've never had to use tools like Matplotlib &
> others before.
>
> Now, for my work, I would need to learn the basics fast, for a one-time
> quick-n-dirty job.

##
## START SCRIPT ##
##
#
# Easy_as.py
#
import Tkinter as tk
# Create a main window and a canvas.
app = tk.Tk()
can = tk.Canvas(
app,
width=500,
height=500,
#bd=1,
#relief=tk.SOLID,
)
can.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
# Create some gridlines on the canvas.
W,H = 500, 500
row, col = 0,0
for _ in range(10):
can.create_line(0, row, W, row, fill='red')
print 0, row, W, row
can.create_line(col, 0, col, H, fill='green')
row += 50
col += 50
can.create_line(
0,500,300,300,
350,200,400,450,
fill='magenta',
width=5,
)
# Start the event loop.
app.mainloop()

## END SCRIPT ##


Any questions?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread Bart Kastermans
rantingrick  writes:

> Hmm, i can replace all that code with this...

Because I stupidly forgot to repeat the original problem I had, and my
code doesn't show it (and doesn't show the correct use of the function I
wrote).  The code shows that I now know how to compute the number of
lines and item will have; in the actual program I am developing I will
take the max of these numbers and make all items that height.

This means the code I should have shown is as follows (here I first
compute the maximum height needed for any item, and then show all items
using this height).  Also in the actual program there will be scrolling
options to change the item shown by the different labels.

import Tkinter as Tk
import tkFont
import random
import sys

def genstr (j):
rno = random.randint(4,50)
ret_val = str(j) + ":"
for i in range (0, rno):
ret_val += "hello" + str(i)
return ret_val

def gendata (lh):
ret_val = []
for i in range(0,lh):
ret_val.append (genstr (i))
return ret_val

data = gendata (100)

root = Tk.Tk()
font = tkFont.Font(family='times', size=13)

class lines:
def __init__ (self):
self.lastct = 1   # remember where the cutoff was last work from there

def count (self, text, cutoff = 400):
global font
no_lines = 1
start_idx = 0
idx = self.lastct

while True:
if idx > len (text):
idx = len (text)

# shrink from guessed value
while font.measure (text[start_idx:idx - 1]) > cutoff:
if idx <= start_idx:
print "error"
sys.exit ()
else:
idx -= 1
self.lastct = idx - start_idx # adjust since was too big

# increase from guessed value (note: if first shrunk then done)
while (idx < len (text)
   and font.measure (text[start_idx:idx]) < cutoff):
idx += 1
self.lastct = idx - start_idx # adjust since was too small

# next line has been determined
print "*" + text[start_idx:idx-1] + "*"
if idx == len(text) and font.measure (text[start_idx:]) < cutoff:
return no_lines
elif idx == len(text):
return no_lines + 1
else:
no_lines += 1
start_idx = idx - 1
idx = start_idx + self.lastct

lin = lines()

max_ht = 0
for i in range(0,len(data)):
ct = lin.count(data[i], 450)
if ct > max_ht:
max_ht = ct

for i in range(0,min(len(data),5)):
l = Tk.Label(root)
l.pack()
l['text'] = data[i]
l['width'] = 50
l['justify'] = Tk.LEFT
l['anchor'] = 'w'
l['wraplength'] = 450
l['padx']=10
l['pady'] = 5
l['height'] = max_ht
l['font'] = font
if i % 2 == 0:
l['background'] = 'grey80'
else:
l['background'] = 'grey70'

root.mainloop()



>
> #
> # Easy_as.py
> #
> import Tkinter as tk
> from ScrolledText import ScrolledText
> import tkFont
> import random
> # Create some puesdo data.
> data = [
> '{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
> for x in range(100)
> ]
> ##print data
> # Create the main window and a scrolled text widget.
> root = tk.Tk()
> font = tkFont.Font(family='times', size=13)
> textbox = ScrolledText(
> root,
> width=60,
> height=20,
> font=('Times', 10),
> wrap=tk.WORD,
> )
> textbox.pack(
> fill=tk.BOTH,
> expand=True,
> padx=5,
> pady=5,
> )
> textbox.insert(1.0, '\n\n'.join(data))
> # Start the event loop.
> root.mainloop()
> #
> # End
> #
-- 
http://mail.python.org/mailman/listinfo/python-list


MIMEText encode error - Python 2.6.6

2011-09-06 Thread neubyr
I am trying to write a program which can email file's content using
smtplib. I am getting following error while using Python 2.6.6
version.

{{{
File "./killed_jobs.py", line 88, in sendmail
   msg = MIMEText(ipfile.read, 'plain')
 File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py",
line 30, in __init__
   self.set_payload(_text, _charset)
 File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py",
line 224, in set_payload
   self.set_charset(charset)
 File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py",
line 266, in set_charset
   cte(self)
 File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py",
line 73, in encode_7or8bit
   orig.encode('ascii')
AttributeError: 'builtin_function_or_method' object has no attribute 'encode'

}}}


I am referring to email examples on the doc site
http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples
. Following is the msg object part in my code:

{{{
...
...
def sendmail(inputfile):
ipfile = open(inputfile, 'r')
msg = MIMEText(ipfile.read, 'plain')
ipfile.close()

...
...
}}}

I have tried setting subtype and chartype separately as mentioned here
- http://docs.python.org/release/2.6.6/library/email.mime.html, but
the error remains same. Any help on what might be wrong here?

thanks,
neuby.r
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import os or import os.path

2011-09-06 Thread Ian Kelly
On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci  wrote:
> Hi,
>
> If I want to use the 'os.path' module, it's enought to import 'os':
>
> import os
> if os.path.isfile('/usr/bin/bash'):
>    print 'got it'
>
> In other source codes I noticed that people write 'import os.path' in
> this case. Which is better practice?

"import os.path" is better practice.  There is no guarantee in general
that the os module will automatically import os.path, and in future
versions or different implementations it might not.

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


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
Or if you prefer the alternating background approach...


##
# Easy_as.py
##
import Tkinter as tk
from ScrolledText import ScrolledText
import tkFont
import random
END = 'end'
INSERT = 'insert'
#
# Create some puesdo data.
data = [
'{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
for x in range(100)
]
##print data
#
# Create the main window and a scrolled text widget.
root = tk.Tk()
font = tkFont.Font(family='times', size=13)
textbox = ScrolledText(
root,
width=60,
height=20,
font=('Times', 10),
wrap=tk.WORD,
)
textbox.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
#
# Add a tag to the very end of the widget and
# configure the tag only once!
textbox.tag_add('one', END)
textbox.tag_config('one', background='gray')
#
# Iterate over the lines stuffing them into the textbox.
idata = iter(data)
sidx = 1.0
while True:
try:
textbox.insert(END, idata.next()+"\n")
textbox.tag_add('one', sidx, INSERT)
textbox.insert(END, idata.next()+"\n")
print sidx, textbox.index(END)
sidx = textbox.index(INSERT)
except StopIteration:
break
#
# Start the event loop.
root.mainloop()
##
# End
##

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


import os or import os.path

2011-09-06 Thread Jabba Laci
Hi,

If I want to use the 'os.path' module, it's enought to import 'os':

import os
if os.path.isfile('/usr/bin/bash'):
print 'got it'

In other source codes I noticed that people write 'import os.path' in
this case. Which is better practice?

Thanks,

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


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
Hmm, i can replace all that code with this...

#
# Easy_as.py
#
import Tkinter as tk
from ScrolledText import ScrolledText
import tkFont
import random
# Create some puesdo data.
data = [
'{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
for x in range(100)
]
##print data
# Create the main window and a scrolled text widget.
root = tk.Tk()
font = tkFont.Font(family='times', size=13)
textbox = ScrolledText(
root,
width=60,
height=20,
font=('Times', 10),
wrap=tk.WORD,
)
textbox.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
textbox.insert(1.0, '\n\n'.join(data))
# Start the event loop.
root.mainloop()
#
# End
#
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable locale usage

2011-09-06 Thread garabik-news-2005-05
Thomas Jollans  wrote:
 
> It looks like you don't actually care about the encoding: in your first
> example, you use the default system encoding, which you do not control,
> and in your second example, you're using two different encodings on the
> two platforms. So why do you care whether or not the default uses ISO
> 8859-2 ?
>

Maybe because using 8859-2 locale, (unicode) strings not representable in the
encodings will be sorted - how? 

I would care, I prefer not to have undefined behaviour.

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Relative seeks on string IO

2011-09-06 Thread Terry Reedy

On 9/6/2011 3:18 AM, Pierre Quentel wrote:


I am wondering why relative seeks fail on string IO in Python 3.2


Good question.


 from io import StringIO
 txt = StringIO('Favourite Worst Nightmare')
 txt.seek(8) # no problem with absolute seek


Please post code without non-code indents, like so:

from io import StringIO
txt = StringIO('Favourite Worst Nightmare')
txt.seek(8,0) # no problem with absolute seek
txt.seek(0,1) #  0 characters from current position ok, and useless
txt.seek(-2,2) # end-relative gives error message for cur-relative

so someone can copy and paste without deleting indents.
I verified with 3.2.2 on Win7. I am curious what 2.7 and 3.1 do.

What system are you using? Does it have a narrow or wide unicode build? 
(IE, what is the value of sys.maxunicode?)



 txt.seek(2,1) # 2 characters from current position

raises "IOError: Can't do nonzero cur-relative seeks" (tested with
Python3.2.2 on WindowsXP)

A seek relative to the end of the string IO raises the same IOError



Is there any reason why relative seeks on string IO are not allowed in
Python3.2, or is it a bug that could be fixed in a next version ?


Since StringIO seeks by fixed-size code units (depending on the build), 
making seeking from the current position and end trivial, I consider 
this a behavior bug. At minimum, it is a doc bug. I opened

http://bugs.python.org/issue12922

As noted there, I suspect the limitation in inherited from TextIOBase. 
But I challenge that it should be.


I was somewhat surprised that seeking (from the start) is not limited to 
the existing text. Seeking past the end fills in with nulls. (They are 
typically a nuisance though.)


from io import StringIO
txt = StringIO('0123456789')
txt.seek(15,0) # no problem with absolute seek
txt.write('xxx')
s  = txt.getvalue()
print(ord(s[12]))
# 0
--
Terry Jan Reedy

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


Re: Tkinter label height to fit content

2011-09-06 Thread Bart Kastermans

I build on the suggestion by rantingrick, but took it in a bit
different direction.

I now have working code that performs reasonable.  The reason for
the class lines (as opposed to just a function) is b/c font.measure
appears not that fast.  So I want to remember between different
calls to lines.count where the cutoff was, and then start looking
from there.  This one step of "optimization" was enough to make it
run reasonable on my system.

There are one important thing skipped, Tkinter.Label takes whitespace
into account.  This code does not yet.  Also I just hacked this
together as an example solution to work further from.

import Tkinter as Tk
import tkFont
import random
import sys

def genstr (j):
rno = random.randint(4,50)
ret_val = str(j) + ":"
for i in range (0, rno):
ret_val += "hello" + str(i)
return ret_val

def gendata (lh):
ret_val = []
for i in range(0,lh):
ret_val.append (genstr (i))
return ret_val

data = gendata (100)

root = Tk.Tk()
font = tkFont.Font(family='times', size=13)

class lines:
def __init__ (self):
self.lastct = 1   # remember where the cutoff was last work from there

def count (self, text, cutoff = 400):
global font
no_lines = 1
start_idx = 0
idx = self.lastct

while True:
if idx > len (text):
idx = len (text)

# shrink from guessed value
while font.measure (text[start_idx:idx - 1]) > cutoff:
if idx <= start_idx:
print "error"
sys.exit ()
else:
idx -= 1
self.lastct = idx - start_idx # adjust since was too big

# increase from guessed value (note: if first shrunk then done)
while (idx < len (text)
   and font.measure (text[start_idx:idx]) < cutoff):
idx += 1
self.lastct = idx - start_idx # adjust since was too small

# next line has been determined
print "*" + text[start_idx:idx-1] + "*"
if idx == len(text) and font.measure (text[start_idx:]) < cutoff:
return no_lines
elif idx == len(text):
return no_lines + 1
else:
no_lines += 1
start_idx = idx - 1
idx = start_idx + self.lastct

lin = lines()

# for testing speed compute for all data
for i in range(0,len(data)):
lin.count(data[i], 450)

# show only first 10
for i in range(0,min(len(data),10)):
l = Tk.Label(root)
l.pack()
l['text'] = data[i]
print i
no = lin.count (data[i], 450)
print "computed lines", no
l['width'] = 50
l['justify'] = Tk.LEFT
l['anchor'] = 'w'
l['wraplength'] = 450
l['padx']=10
l['pady'] = 5
l['height'] = no
l['font'] = font
if i % 2 == 0:
l['background'] = 'grey80'
else:
l['background'] = 'grey70'

root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing WebDAV server

2011-09-06 Thread Fokke Nauta
"Dennis Lee Bieber"  wrote in message 
news:mailman.809.1315328739.27778.python-l...@python.org...
> On Tue, 6 Sep 2011 16:46:17 +0200, "Fokke Nauta"
>  declaimed the following in
> gmane.comp.python.general:
>
>
>> ---
>> Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] 
>> on
>> win32
>> Type "copyright", "credits" or "license()" for more information.
>> >>> import os.path
>> >>> os.path.isdir(path_name)
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> os.path.isdir(path_name)
>> NameError: name 'path_name' is not defined
>> >>>
>> ---
>>
> "path_name" is a placeholder -- you're supposed to put in the exact
> string(s) you have been trying in the configuration file (wrap the
> string in quotes).
>
 import os.path
 os.path.isdir("e:\webdav")
> False
 os.mkdir("e:\webdav")
 os.path.isdir("e:\webdav")
> True
 os.path.isdir("e:\webdav\\")
> Traceback (  File "", line 1
>os.path.isdir("e:\webdav\")
>  ^
> SyntaxError: EOL while scanning single-quoted string
 os.path.isdir("e:\webdav\\")
> True
 os.path.isdir("e:\webdav/")
> True
 os.path.isdir("e:/webdav/")
> True
 os.path.isdir("e:/webdav")
> True
 os.rmdir("e:/webdav")
 os.path.isdir("e:\webdav")
> False

>
> Note that Python itself (and the C-runtime) doesn't care if the
> separator is \ or / or even mixed; it is just the Windows command line
> that uses \ for separator and / for options. (Python, however, uses \ as
> an escape and \" is treated first, hence the need for \\" to escape the
> \ itself)

Thanks, this is clear.

This is my Python shell:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
>>> import os.path
>>> os.path.isdir("d:\webdav")
True
>>>

So Python recognizes the directory d:\webdav

This is the command shell:

D:\Python27\WebDAV\PyWebDAV\DAVServer>server.py -n -c config.ini

INFO:pywebdav:Starting up PyWebDAV server 
INFO:pywebdav:chunked_http_response feature ON
INFO:pywebdav:http_request_use_iterator feature OFF
INFO:pywebdav :http_response_use_iterator feature OFF
INFO:fshandler:Initialized with D:/Webdav-http://10.0.0.140:8081/
WARNING:pywebdav:Authentication disabled!
INFO:pywebdav:Serving data from D:/Webdav
Listening on 10.0.0.140 <8081>

(here I try to login the WebDAV server with the local IE browser)

INFO:fshandler :get_data: D:\Webdav not found
server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; 
Windows N
T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 -
server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; 
Windows N
T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 -

So - I'm a bit lost now. Thinking seriously that my webdav installation is 
at fault.

Fokke



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


Advice on how to get started with 2D-plotting ?

2011-09-06 Thread Fred Pacquier
Hi,

I'm a Python long-timer, but I've never had to use tools like Matplotlib & 
others before.

Now, for my work, I would need to learn the basics fast, for a one-time 
quick-n-dirty job.

This involves a graphic comparison of RFC1918 IP subnets allocation across 
several networks.

The idea is to draw parallel lines, with segments (subnets) coloured green, 
yellow or red depending on the conflicts between the networks.

What would be the simplest/fastest way of getting this done ?
(the graphic parts, the IP stuff I know how to handle)

Alternately, if someone knows of a ready-made and accessible tool that does 
just that, I'm all ears :-)

TIA,
fp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 20 - Silly Question?

2011-09-06 Thread Peter Otten
Joseph Armbruster wrote:

> I have used Python for some time and ran a windows build-bot for a bit.
>  This morning, I told a fellow developer "There should be only one obvious
> way to do it." and then I proceeded to forward him to the Zen of Python
> and sent him a link to:
> http://www.python.org/dev/peps/pep-0020/
> 
> I noticed that it says only 19 of 20 have been written down.  Which one
> was not written down?

Whoever offers a $1 billion sponsorship to the PSF gets to decide that one.
Expect something like "Keep your baby real dry with black whole diapers".

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


Re: PEP 20 - Silly Question?

2011-09-06 Thread Zero Piraeus
:

On 6 September 2011 12:17, Joseph Armbruster  wrote:
> I noticed that it says only 19 of 20 have been written down.  Which one was
> not written down?

The last one.

 -[]z.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 20 - Silly Question?

2011-09-06 Thread Eric Snow
On Tue, Sep 6, 2011 at 10:17 AM, Joseph Armbruster
 wrote:
> I have used Python for some time and ran a windows build-bot for a bit.
>  This morning, I told a fellow developer "There should be only one obvious
> way to do it." and then I proceeded to forward him to the Zen of Python and
> sent him a link to:
> http://www.python.org/dev/peps/pep-0020/
> I noticed that it says only 19 of 20 have been written down.  Which one was
> not written down?

I'm not sure there ever was a 20th.  Apparently Tim Peters was going
to leave the last one for Guido to fill in:

http://mail.python.org/pipermail/python-list/1999-June/616160.html

(from http://www.wefearchange.org/2010/06/import-this-and-zen-of-python.html)

-eric

> Thank You,
> Joseph Armbruster
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


PEP 20 - Silly Question?

2011-09-06 Thread Joseph Armbruster
I have used Python for some time and ran a windows build-bot for a bit.
 This morning, I told a fellow developer "There should be only one obvious
way to do it." and then I proceeded to forward him to the Zen of Python and
sent him a link to:
http://www.python.org/dev/peps/pep-0020/

I noticed that it says only 19 of 20 have been written down.  Which one was
not written down?

Thank You,
Joseph Armbruster
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point multiplication in python

2011-09-06 Thread Thomas 'PointedEars' Lahn
Thomas Rachel wrote:

> Now if you multiply two values with an error, the error also propagates
> into the result - PLUs the result can have its own error source - in the
> same order of magnitude.
> 
> (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e
> or (2*a + e) * e.

Your explanation about floating-point precision, which I already knew about 
but have only scanned here – so it might be flawed as well –, 
notwithstanding, it is not clear to me at all what you are trying to prove 
there.

Computers (well, perhaps outside of mathematical software) do NOT compute an 
equation as humans would do, so the binomial theorem does NOT apply.  In an 
algorithm of the real implementation,

  (a + e) * (a + e)

would be computed as follows:

  b := a + e
  c := b * b
or
  c := b + … + b

[add the value of `b' to the value of `b' (b−1) times, since binary logic 
does not support multiplication]

IOW, the error does propagate into the result indeed, but not as you 
described.  Indeed, thanks to rounding on assignment and multiplication
(i. e., setting register values or IEEE-754 floating-point mantissa and 
exponent), the error will be different, probably greater than you compute 
here.

-- 
PointedEars

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


Re: Portable locale usage

2011-09-06 Thread Thomas Jollans
On 06/09/11 16:46, ssegvic wrote:
> For the moment, I only wish to properly sort a Croatian text file
> both on Windows and Linux (I am a cautious guy, I like reachable
> goals).
> When the locale is properly set, sorting works like a charm
> with mylist.sort(key=locale.strxfrm).

The problem with that is of course that a Croatian locale has to be
installed. Many Linux systems don't have locales that aren't used.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable locale usage

2011-09-06 Thread ssegvic
On 6 ruj, 15:13, Vlastimil Brom  wrote:

> There may be some differences btween OSes end the versions, but using
> python 2.7 and 3.2 on Win XP and Win7 (Czech)
> I get the following results for setlocale:
>
> >>> locale.setlocale(locale.LC_ALL,'Croatian')
>
> 'Croatian_Croatia.1250'>>> locale.getlocale()
>
> ('Croatian_Croatia', '1250')
>
> >>> locale.getpreferredencoding(do_setlocale=False)
> 'cp1250'
>
> However, "hr" is not recognised on this systems:
>
> >>> locale.setlocale(locale.LC_ALL, "hr")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "locale.pyc", line 531, in setlocale
> Error: unsupported locale setting

Thanks for your feedback!


So this works only on Linux (in concordance with the documentation):

locale.setlocale(locale.LC_ALL, ('croatian',
locale.getpreferredencoding()))

And this works only on Windows (incomplete locale spec probably filled
in by Windows API):

locale.setlocale(locale.LC_ALL, 'croatian')


Obviously, there is a misunderstanding between Python
which uses standard (IANA) language codes
and Windows which, as usual, have their own ways :-(


One possible solution would be to change
locale.locale_alias on Windows so that
it honors the custom Windows conventions:
 'hr' -> 'Croatian_Croatia.1250'
   instead of
 'hr' -> 'hr_HR.ISO8859-2'

In addition, locale.getpreferredencoding()
should probably be changed in order to return
valid Windows encodings ('1250' instead of 'cp1250').

Cheers,

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


Re: Python marks an instance of my class undefined

2011-09-06 Thread Hans Mulder

On 6/09/11 16:18:32, Laszlo Nagy wrote:

On 2011-09-06 15:42, Kayode Odeyemi wrote:

I was able to get this solved by calling class like this:

>>> from core.fleet import Fleet
>>> f = Fleet()

Thanks to a thread from the list titled "TypeError: 'module' object is
not callable"

Or you can also do this:

import core.fleet # import module core.fleet under the name core.fleet
f = core.fleet.Fleet()

Please note that the import statement imports the module with the given
name.

So for example

import x.y.z

will import the name "x.y.z". Anything that is in module "z" will be
available through its module, that is "x.y.z".
Whenever you use "import ", you have to access module contents
through "".

You can change the name:

import core.fleet as c # import module core.fleet under the name c
f = c.Fleet()


An import statement always imports a module, but Python also has the
from...import statement to import one item from a module:

from core.fleet import Fleet
f = Fleet()

The convention is to use the name "Fleet" (with an initial capital)
for the class and "fleet" (all lower case) for the module.  This
makes it easier to not confuse the class and the module.

Hope this helps,

-- HansM





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


Re: Portable locale usage

2011-09-06 Thread ssegvic
On 6 ruj, 13:16, Thomas Jollans  wrote:
> > locale.setlocale(locale.LC_ALL, (myISOCountryCode,
> > locale.getpreferredencoding()))
>
> As far as I can tell, this does work. Can you show us a traceback?

Sorry, I was imprecise.

I wanted to say that the above snippet
does not work both on Windows and Linux.

This is what I get on Windows:

>>> import sys
>>> sys.version
'3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]'
>>> myISOCountryCode='hr'
>>> locale.setlocale(locale.LC_ALL, (myISOCountryCode, 
>>> locale.getpreferredencoding()))
Traceback (most recent call last):
  File "", line 1, in 
locale.setlocale(locale.LC_ALL, (myISOCountryCode,
locale.getpreferredencoding()))
  File "C:\apps\Python32\lib\locale.py", line 538, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

The snippet actually works on Linux, as you note.

> It looks like you don't actually care about the encoding: in your first
> example, you use the default system encoding, which you do not control,
> and in your second example, you're using two different encodings on the
> two platforms.

That's true.

That's because currently I care most about
lists of strings being sorted properly (see below).

Nevertheless, it *appears* to me that, in the Unicode era,
the locales could well be decoupled from particular encodings.
But this is another topic.

> So why do you care whether or not the default uses ISO 8859-2 ?

It's not that I care about encoding,
it's that Windows throws locale.Error at me :-)

> > My questions are the following:
>
> > 1. Is there a way for writing portable Python code dealing with
> > locales
> >     (as sketched in the beginning)?
>
> > 2. If not, is there anything wrong with that idea?
>
> As I said, I believe the above code should work. It works on my Linux
> system.
>
> What are you attempting to achieve with this setting of the locale,
> without even setting the encoding? Doesn't it make more sense to simply
> use the user's usual locale, and interact with them on their own terms?

For the moment, I only wish to properly sort a Croatian text file
both on Windows and Linux (I am a cautious guy, I like reachable
goals).
When the locale is properly set, sorting works like a charm
with mylist.sort(key=locale.strxfrm).

My current solution to the portability problem is:

import locale
try:
  locale.setlocale(locale.LC_ALL, 'hr_HR.utf8')  # linux
except locale.Error:
  locale.setlocale(locale.LC_ALL, 'Croatian_Croatia.1250')#
windows

Thanks for your feedback!

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


Re: Installing WebDAV server

2011-09-06 Thread Fokke Nauta
"becky_lewis"  wrote in message 
news:f5b9ec16-de9a-4365-81a8-860dc27a9...@d25g2000yqh.googlegroups.com...
On Sep 5, 3:51 pm, "Fokke Nauta"  wrote:
>
> Hi Becky,
>
> I tried it straight away:
> directory=D:\Webdav\
> directory=D:/Webdav/
>
> Didn't work, in both cases the same error "fshandler:get_data: \Webdav not
> found".
>
> I have the opinion that my WebDAV installation is at fault. The database 
> is
> not created either.
> To have set up Python, I used python-2.7.2.msi.
> To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both
> Unix/Linux.
> To install the, I used
> "
>
> >> You dont install from "Python GUI", use normal cmd, navigate to the
> >> folder
> >> you downloaded PyXML and PyWebDAV and run "python setup.py install"
> >> (python.exe has to be in your PATH). Then you have to find the
> >> startup-script "davserver". Find your python installation directory and
> >> look into/Tools/Scripts, in my computer this is
> >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the
> >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have
> >> to
> >> look for "davserver" there..."
>
> Shall I reïnstall the whole lot? Would it make a difference if in that 
> case
> I would use ActivePython-2.7.2.5-win32-x86.msi instead of 
> python-2.7.2.msi?
>
> Fokke

You could try that but I'd imagine you'll end up with the same issue.
My best guess is that something is preventing os.path.isdir from
detecting the path as a directory under windows. I can't reproduce it
on my Linux system but may have a working windows installation later.
If I were you I'd fire up a python shell (execute python and get the
>>> prompt), import os.path and manually try os.path.isdir(path_name)
to try and find out what the actualy problem is.

I'm not familiar with Python, but I entered "import os.path " (nothing 
happened) and "os.path.isdir(path_name)
" in the shell. I guess what I did was not correct.
Underneath I copied what showed up in the shell.

---
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
>>> import os.path
>>> os.path.isdir(path_name)

Traceback (most recent call last):
  File "", line 1, in 
os.path.isdir(path_name)
NameError: name 'path_name' is not defined
>>>
---

Fokke 


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


Re: Python marks an instance of my class undefined

2011-09-06 Thread Kayode Odeyemi
On Tue, Sep 6, 2011 at 3:18 PM, Laszlo Nagy  wrote:

> On 2011-09-06 15:42, Kayode Odeyemi wrote:
>
>> I was able to get this solved by calling class like this:
>>
>> >>> from core.fleet import Fleet
>> >>> f = Fleet()
>>
>> Thanks to a thread from the list titled "TypeError: 'module' object is not
>> callable"
>>
> Or you can also do this:
>
> import core.fleet # import module core.fleet under the name core.fleet
> f = core.fleet.Fleet()
>
> Please note that the import statement imports the module with the given
> name.
>
> So for example
>
> import x.y.z
>
> will import the name "x.y.z". Anything that is in module "z" will be
> available through its module, that is "x.y.z".
> Whenever you use "import ", you have to access module contents
> through "".
>
> You can change the name:
>
> import core.fleet as c # import module core.fleet under the name c
> f = c.Fleet()
>
>
That is, import [package-name] .[class-name]

If using from, that can take the form of [package-name].[pymodule] import
[pymodule] or [class-name]

I just got to understand it.

Thanks. This explanation really simplifies it further.

Can I do:

from [pymodule] import [class-name], assuming the pymodule as a class
instance?



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python marks an instance of my class undefined

2011-09-06 Thread Laszlo Nagy

On 2011-09-06 15:42, Kayode Odeyemi wrote:

I was able to get this solved by calling class like this:

>>> from core.fleet import Fleet
>>> f = Fleet()

Thanks to a thread from the list titled "TypeError: 'module' object is 
not callable"

Or you can also do this:

import core.fleet # import module core.fleet under the name core.fleet
f = core.fleet.Fleet()

Please note that the import statement imports the module with the given 
name.


So for example

import x.y.z

will import the name "x.y.z". Anything that is in module "z" will be 
available through its module, that is "x.y.z".
Whenever you use "import ", you have to access module contents 
through "".


You can change the name:

import core.fleet as c # import module core.fleet under the name c
f = c.Fleet()

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


Re: Python marks an instance of my class undefined

2011-09-06 Thread Kayode Odeyemi
I was able to get this solved by calling class like this:

>>> from core.fleet import Fleet
>>> f = Fleet()

Thanks to a thread from the list titled "TypeError: 'module' object is not
callable"

On Tue, Sep 6, 2011 at 2:02 PM, Kayode Odeyemi  wrote:

> Is there anything I need to do to create an instance of a class?
>
> I have this simple code(The class is in a package core.fleet):
>
> class Fleet(object):
> def __init__(self):
> """ no-arg constructor """
> def fleet_file_upload(self, filename, type=None):
> if type == 'user':
> return 'photos/%Y/%m/%d'
> return 'images'
>
> def fleet_get_fleet(self):
> """ Get all fleet """
> return db.db_get_fleet()
>
>  def fleet_get_fleet_type(self):
> """ Get fleet by type or category """
>
> For Python shell, I did this:
>
> >>> import core.fleet
> >>> f = Fleet()
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'Fleet' is not defined
>
> What am I doing wrong?
>
>
> --
> Odeyemi 'Kayode O.
> http://www.sinati.com. t: @charyorde
>
>


-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-- 
http://mail.python.org/mailman/listinfo/python-list


Representation of floats (-> Mark Dickinson?)

2011-09-06 Thread jmfauth
This is just an attempt to put the
http://groups.google.com/group/comp.lang.python/browse_thread/thread/a008af1ac2968833#
discussion at a correct level.

With Python 2.7 a new float number representation (the David Gay's
algorithm)
has been introduced. If this is well honored in Python 2.7, it
seems to me, there are some missmatches in the Py3 series.

>>> sys.version
'2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
(Intel)]'
>>> 0.1
0.10001
>>> print 0.1
0.1
>>> 1.1 * 1.1
1.2102
>>> print 1.1 * 1.1
1.21
>>> print repr(1.1 * 1.1)
1.2102
>>>


>>> sys.version
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
>>>
>>> 0.1
0.1
>>> print 0.1
0.1
>>> 1.1 * 1.1
1.21
>>> print 1.1 * 1.1
1.21
>>> print repr(1.1 * 1.1)
1.2102
>>>


>>> sys.version
'3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]'
>>> 0.1
0.1
>>> print(0.1)
0.1
>>> 1.1 * 1.1
1.2102
>>> print(1.1 * 1.1)
1.21
>>> print(repr(1.1 * 1.1))
1.2102
>>> '{:g}'.format(1.1 * 1.1)
'1.21'



>>> sys.version
'3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]'
>>> 0.1
0.1
>>> print(0.1)
0.1
>>> 1.1 * 1.1
1.2102
>>> print (1.1 * 1.1)
1.2102
>>> print(repr((1.1 * 1.1)))
1.2102
>>>
>>> '{:g}'.format(1.1 * 1.1)
'1.21'
>>>

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


Re: Portable locale usage

2011-09-06 Thread Vlastimil Brom
2011/9/6 ssegvic :
> Hi,
>
> I am musing on how to write portable Python3 code which would
> take advantage of the standard locale module.
>
> For instance, it would be very nice if we could say something like:
>
> # does not work!
> myISOCountryCode='hr'
> locale.setlocale(locale.LC_ALL, (myISOCountryCode,
> locale.getpreferredencoding()))
>
> Up to now, I have found ways to set locale on Linux and Windows:
>
> import locale
> locale.setlocale(locale.LC_ALL, 'hr_HR.utf8')      # works on linux
> locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows
>
> I have noticed that locale defines a dictionary locale.locale_alias,
> and that it contains the following promising keys: 'hr_hr',
> 'hrvatski', 'hr'.
> Unfortunately, both on Windows and Linux all these keys
> are bound to the same outdated string 'hr_HR.ISO8859-2'.
>
> My questions are the following:
>
> 1. Is there a way for writing portable Python code dealing with
> locales
>    (as sketched in the beginning)?
>
> 2. If not, is there anything wrong with that idea?
>
> 3. What is the status of locale.locale_alias (official documentation
> does not mention it)?
>
>
> Cheers,
>
> Sinisa
>
> http://www.zemris.fer.hr/~ssegvic/index_en.html
> --
> http://mail.python.org/mailman/listinfo/python-list
>

There may be some differences btween OSes end the versions, but using
python 2.7 and 3.2 on Win XP and Win7 (Czech)
I get the following results for setlocale:

>>> locale.setlocale(locale.LC_ALL,'Croatian')
'Croatian_Croatia.1250'
>>> locale.getlocale()
('Croatian_Croatia', '1250')
>>> locale.getpreferredencoding(do_setlocale=False)
'cp1250'
>>>

However, "hr" is not recognised on this systems:

>>> locale.setlocale(locale.LC_ALL, "hr")
Traceback (most recent call last):
  File "", line 1, in 
  File "locale.pyc", line 531, in setlocale
Error: unsupported locale setting
>>>

regards,
   vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Python marks an instance of my class undefined

2011-09-06 Thread Kayode Odeyemi
Is there anything I need to do to create an instance of a class?

I have this simple code(The class is in a package core.fleet):

class Fleet(object):
def __init__(self):
""" no-arg constructor """
def fleet_file_upload(self, filename, type=None):
if type == 'user':
return 'photos/%Y/%m/%d'
return 'images'

def fleet_get_fleet(self):
""" Get all fleet """
return db.db_get_fleet()

def fleet_get_fleet_type(self):
""" Get fleet by type or category """

For Python shell, I did this:

>>> import core.fleet
>>> f = Fleet()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'Fleet' is not defined

What am I doing wrong?


-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-- 
http://mail.python.org/mailman/listinfo/python-list


HDF5 tree walker

2011-09-06 Thread Alex van der Spek
Is there an equivalent to os.path.walk() for HDF5 file trees accessed 
through h5py?

Thanks!
Alex van der Spek 


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


Re: Running Python Demo on the Web?

2011-09-06 Thread becky_lewis
On Sep 5, 11:00 pm, Python Fiddle Admin 
wrote:
> Python has been ported to the web browser at pythonfiddle.com. Python
> Fiddle can import snippets of code that you are reading on a web page
> and run them in the browser. It supports a few popular libraries.
>
> Another common usage is to post code on the site to allow other people
> to play around with it. Also, it can be used to demonstrate a working
> program.

Looks interesting but you don't appear to have support for most (any?)
of the python core libs. Are you planning on adding more libraries?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running Python Demo on the Web?

2011-09-06 Thread Colin J. Williams

On 05-Sep-11 18:00 PM, Python Fiddle Admin wrote:

Python has been ported to the web browser at pythonfiddle.com. Python
Fiddle can import snippets of code that you are reading on a web page
and run them in the browser. It supports a few popular libraries.

Another common usage is to post code on the site to allow other people
to play around with it. Also, it can be used to demonstrate a working
program.

A neat idea.

import brian
dir(brian)

Responds "scipy not available"

Colin W.

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


Beginner's query - What is scope of Python for Embedded Programming(C, C++) ?

2011-09-06 Thread Santosh Dumbre
Hi,

Please consider a beginner's query -

I am 9 -years experienced in C++.
Currently working in Automation domain.

Will Python help me to work in Automation/Embedded domain ?

Your advice is highly appreciated.

Please reply.

Thanks a lot,
Santosh.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing WebDAV server

2011-09-06 Thread becky_lewis
On Sep 5, 3:51 pm, "Fokke Nauta"  wrote:
>
> Hi Becky,
>
> I tried it straight away:
> directory=D:\Webdav\
> directory=D:/Webdav/
>
> Didn't work, in both cases the same error "fshandler:get_data: \Webdav not
> found".
>
> I have the opinion that my WebDAV installation is at fault. The database is
> not created either.
> To have set up Python, I used python-2.7.2.msi.
> To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both
> Unix/Linux.
> To install the, I used
> "
>
> >> You dont install from "Python GUI", use normal cmd, navigate to the
> >> folder
> >> you downloaded PyXML and PyWebDAV and run "python setup.py install"
> >> (python.exe has to be in your PATH). Then you have to find the
> >> startup-script "davserver". Find your python installation directory and
> >> look into/Tools/Scripts, in my computer this is
> >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the
> >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have
> >> to
> >> look for "davserver" there..."
>
> Shall I reïnstall the whole lot? Would it make a difference if in that case
> I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi?
>
> Fokke

You could try that but I'd imagine you'll end up with the same issue.
My best guess is that something is preventing os.path.isdir from
detecting the path as a directory under windows. I can't reproduce it
on my Linux system but may have a working windows installation later.
If I were you I'd fire up a python shell (execute python and get the
>>> prompt), import os.path and manually try os.path.isdir(path_name)
to try and find out what the actualy problem is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-06 Thread Hans Mulder

On 6/09/11 01:18:37, Steven D'Aprano wrote:

Terry Reedy wrote:


The doc says "-c
Execute the Python code in command. command can be one or more
statements separated by newlines,"

However, I have no idea how to put newlines into a command-line string.


I imagine that it depends on the shell you are using, but bash on Linux
makes it simple: double quotes "..." are like Python's triple-quoted
strings in that they can include newlines.


Single quotes in bash are more similar to triple quotes in Python, in
that some shell syntax is recognized within double quoted string, but
not within single quoted strings:

$ python -c 'import sys
print `sys.version`'
'2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. 
build 5664)]'


$ python -c "import sys
> print `sys.copyright`"
-bash: sys.copyright: command not found

When using single quotes, the `` are passed to Python, which interprets
them as a call to repr().  With double quotes, the shell interprets ``
as a sub-command.


Other shells may be different.


Most *nix shells are similar to bash. The ones that are different
are csh and tcsh: they require a backslash before each newline:

$ tcsh
% ls f*.py | python -c 'import sys \
? print sys.stdin.read()'
filecmp.py
fileinput.py
fnmatch.py
formatter.py
fpformat.py
fractions.py
ftplib.py
functools.py
%

Sometimes you need two backslashes, one for csh and one for Python:

% python -c 'print "spam spam spam spam spam spam spam spam " \\
? "spam spam spam spam spam"'
spam spam spam spam spam spam spam spam spam spam spam spam spam
%

Hope this helps,

-- HansM




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


Re: Portable locale usage

2011-09-06 Thread Thomas Jollans
On 06/09/11 11:59, ssegvic wrote:
> Hi,
> 
> I am musing on how to write portable Python3 code which would
> take advantage of the standard locale module.
> 
> For instance, it would be very nice if we could say something like:
> 
> # does not work!
Doesn't it?

> myISOCountryCode='hr'

This is a language code. (there also happens to be a country code 'hr',
but you're referring to the Croatian language, 'hr')

> locale.setlocale(locale.LC_ALL, (myISOCountryCode,
> locale.getpreferredencoding()))

As far as I can tell, this does work. Can you show us a traceback?

> Up to now, I have found ways to set locale on Linux and Windows:
> 
> import locale
> locale.setlocale(locale.LC_ALL, 'hr_HR.utf8')  # works on linux
> locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows
> 
> I have noticed that locale defines a dictionary locale.locale_alias,
> and that it contains the following promising keys: 'hr_hr',
> 'hrvatski', 'hr'.
> Unfortunately, both on Windows and Linux all these keys
> are bound to the same outdated string 'hr_HR.ISO8859-2'.

It looks like you don't actually care about the encoding: in your first
example, you use the default system encoding, which you do not control,
and in your second example, you're using two different encodings on the
two platforms. So why do you care whether or not the default uses ISO
8859-2 ?

> My questions are the following:
> 
> 1. Is there a way for writing portable Python code dealing with
> locales
> (as sketched in the beginning)?
> 
> 2. If not, is there anything wrong with that idea?

As I said, I believe the above code should work. It works on my Linux
system.

What are you attempting to achieve with this setting of the locale,
without even setting the encoding? Doesn't it make more sense to simply
use the user's usual locale, and interact with them on their own terms?

> 3. What is the status of locale.locale_alias (official documentation
> does not mention it)?

I don't know, but I'd assume it's not considered part of the public API,
and you that shouldn't assume that it'll exist in future versions of Python.

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


Re: Floating point multiplication in python

2011-09-06 Thread Thomas Rachel

Am 06.09.2011 07:57 schrieb xyz:

hi all:

As we know ,  1.1 * 1.1 is 1.21 .
But in python ,I got following :


1.1 * 1.1

1.2102

why python get wrong result? Who can tell me  where's the 0.0002 
from?


1.1 does not fit in a binary floating point number. It is approximated - 
in binary! - as 1.000110011001100110011 ... (periodically).


Note that, while in the decimal system we normally use, only numbers 
which have other components in the denominator than 2 or 5 are 
periodically, in the binary systems only components with 2 are allowed 
in order not to be periodically.


Example: 3.453 is not periodically, because it is 3453/100 and 100 has 
only the factors 2 and 5, each twice.


1/3 = .333... is periodically, because it has the factor 3. The same 
applies to 1/6, which has 2 and 3 as factors. The latter destroys the 
non-periodical behaviour.


As said, in the dual system, only the 2 is allowed.

.5 (10) = 2** -1 = .1 (2).
.25 (10) = 2 ** -2 = .01 (2).
.75 (10) = their sum = .11 (2).

But .1 (1/10) is more complicated, -2 would be as well.

As the IEEE floating point representation is limited, there is a slight 
error value which makes the stored value differ from the intended one.


Look here:




x=(1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1)
a=0
for n,i in enumerate(x): a += i*2**-n; print a, a-1.1, i*2**-n, a-olda

...
1 -0.1 1 1
1.0 -0.1 0.0 0.0
1.0 -0.1 0.0 0.0
1.0 -0.1 0.0 0.0
1.0625 -0.0375 0.0625 0.0625
1.09375 -0.00625 0.03125 0.03125
1.09375 -0.00625 0.0 0.0
1.09375 -0.00625 0.0 0.0
1.09765625 -0.00234375 0.00390625 0.00390625
1.099609375 -0.000390625 0.001953125 0.001953125
1.099609375 -0.000390625 0.0 0.0
1.099609375 -0.000390625 0.0 0.0
1.09985351562 -0.000146484375 0.000244140625 0.000244140625
1.09997558594 -2.44140625001e-05 0.0001220703125 0.0001220703125
1.09997558594 -2.44140625001e-05 0.0 0.0
1.09997558594 -2.44140625001e-05 0.0 0.0
1.0084473 -9.15527343759e-06 1.52587890625e-05 1.52587890625e-05
1.0847412 -1.52587890634e-06 7.62939453125e-06 7.62939453125e-06
1.0847412 -1.52587890634e-06 0.0 0.0
1.0847412 -1.52587890634e-06 0.0 0.0
1.094278 -5.72204589933e-07 9.53674316406e-07 9.53674316406e-07
1.0990463 -9.53674317294e-08 4.76837158203e-07 4.76837158203e-07
1.0990463 -9.53674317294e-08 0.0 0.0
1.0990463 -9.53674317294e-08 0.0 0.0
1.0996424 -3.57627869541e-08 5.96046447754e-08 5.96046447754e-08
1.0999404 -5.96046456636e-09 2.98023223877e-08 2.98023223877e-08
1.0999404 -5.96046456636e-09 0.0 0.0
1.0999404 -5.96046456636e-09 0.0 0.0
1.0999776 -2.23517426789e-09 3.72529029846e-09 3.72529029846e-09
1.063 -3.72529118664e-10 1.86264514923e-09 1.86264514923e-09
1.063 -3.72529118664e-10 0.0 0.0
1.063 -3.72529118664e-10 0.0 0.0
1.086 -1.3969847501e-10 2.32830643654e-10 2.32830643654e-10
1.098 -2.32831531832e-11 1.16415321827e-10 1.16415321827e-10
1.098 -2.32831531832e-11 0.0 0.0
1.098 -2.32831531832e-11 0.0 0.0
1.099 -8.73123795486e-12 1.45519152284e-11 1.45519152284e-11
1.1 -1.45528034068e-12 7.27595761418e-12 7.27595761418e-12
1.1 -1.45528034068e-12 0.0 0.0
1.1 -1.45528034068e-12 0.0 0.0
1.1 -5.45785638906e-13 9.09494701773e-13 9.09494701773e-13
1.1 -9.10382880193e-14 4.54747350886e-13 4.54747350886e-13
1.1 -9.10382880193e-14 0.0 0.0
1.1 -9.10382880193e-14 0.0 0.0
1.1 -3.41948691585e-14 5.68434188608e-14 5.68434188608e-14
1.1 -5.77315972805e-15 2.84217094304e-14 2.84217094304e-14
1.1 -5.77315972805e-15 0.0 0.0
1.1 -5.77315972805e-15 0.0 0.0
1.1 -2.22044604925e-15 3.5527136788e-15 3.5527136788e-15
1.1 -4.4408920985e-16 1.7763568394e-15 1.7763568394e-15
1.1 -4.4408920985e-16 0.0 0.0
1.1 -4.4408920985e-16 0.0 0.0
1.1 -2.22044604925e-16 2.22044604925e-16 2.22044604925e-16
1.1 0.0 1.11022302463e-16 2.22044604925e-16
1.1 0.0 0.0 0.0
1.1 0.0 0.0 0.0
1.1 0.0 1.38777878078e-17 0.0
1.1 0.0 6.93889390391e-18 0.0

So here we have reached the point where the maximum precision is reached 
- a doesn't change anymore, although it should. The error is about 1E-16.


Now if you multiply two values with an error, the error also propagates 
into the result - PLUs the result can have its own error source - in the 
same order of magnitude.


(a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e 
or (2*a + e) * e.

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


Portable locale usage

2011-09-06 Thread ssegvic
Hi,

I am musing on how to write portable Python3 code which would
take advantage of the standard locale module.

For instance, it would be very nice if we could say something like:

# does not work!
myISOCountryCode='hr'
locale.setlocale(locale.LC_ALL, (myISOCountryCode,
locale.getpreferredencoding()))

Up to now, I have found ways to set locale on Linux and Windows:

import locale
locale.setlocale(locale.LC_ALL, 'hr_HR.utf8')  # works on linux
locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows

I have noticed that locale defines a dictionary locale.locale_alias,
and that it contains the following promising keys: 'hr_hr',
'hrvatski', 'hr'.
Unfortunately, both on Windows and Linux all these keys
are bound to the same outdated string 'hr_HR.ISO8859-2'.

My questions are the following:

1. Is there a way for writing portable Python code dealing with
locales
(as sketched in the beginning)?

2. If not, is there anything wrong with that idea?

3. What is the status of locale.locale_alias (official documentation
does not mention it)?


Cheers,

Sinisa

http://www.zemris.fer.hr/~ssegvic/index_en.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point multiplication in python

2011-09-06 Thread Duncan Booth
Gary Herron  wrote:

> (But try:
>print 1.1*1.1
> and see that the print statement does hide the roundoff error from you.)

That varies according to the version of Python you are using. On my system:

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] 
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1.1*1.1)
1.21
>>> ^Z


C:\Python27>cd \python32

C:\Python32>python
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] 
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1.1*1.1)
1.2102

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strang thing:

2011-09-06 Thread Wolfgang Rohdewald
On Dienstag 06 September 2011, 守株待兔 wrote:
> (date,open,high,low,close,vol,adjclose) = (row[0],
> row[1], row[2], row[3],row[4], row[5], row[6]) print  
> row[0], row[1], row[2], row[3],row[4], row[5], row[6]
> 
> 
> the wrong  output is :
> file = open(filename,'r')
> TypeError: 'str' object is not callable

you reassigned "open" to be a string

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


Re: strang thing:

2011-09-06 Thread Chris Angelico
2011/9/6 守株待兔 <1248283...@qq.com>:
>     file = open(filename,'r')

> when i  add    (date,open,high,low,close,vol,adjclose) = (row[0], row[1],

You're assigning to the name "open", which is shadowing the built-in
of the same name. The second time through the loop, you're not calling
the usual open() function, you're trying to call your string. That's
what your error is telling you.

Hope that helps!

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


Relative seeks on string IO

2011-09-06 Thread Pierre Quentel
Hi,

I am wondering why relative seeks fail on string IO in Python 3.2

Example :

from io import StringIO
txt = StringIO('Favourite Worst Nightmare')
txt.seek(8) # no problem with absolute seek

but

txt.seek(2,1) # 2 characters from current position

raises "IOError: Can't do nonzero cur-relative seeks" (tested with
Python3.2.2 on WindowsXP)

A seek relative to the end of the string IO raises the same IOError

However, it is not difficult to simulate a class that performs
relative seeks on strings :


class FakeIO:

def __init__(self,value):
self.value = value
self.pos = 0

def read(self,nb=None):
if nb is None:
return self.value[self.pos:]
else:
return self.value[self.pos:self.pos+nb]

def seek(self,offset,whence=0):
if whence==0:
self.pos = offset
elif whence==1: # relative to current position
self.pos += offset
elif whence==2: # relative to end of string
self.pos = len(self.value)+offset

txt = FakeIO('Favourite Worst Nightmare')
txt.seek(8)
txt.seek(2,1)
txt.seek(-8,2)
=

Is there any reason why relative seeks on string IO are not allowed in
Python3.2, or is it a bug that could be fixed in a next version ?

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


strang thing:

2011-09-06 Thread 守株待兔
i found stange thing that i can't solve
import os
import  csv

for  name  in   os.listdir('/tmp/quote/'):
filename='/tmp/quote/'+name
file = open(filename,'r')
file.readline()  
for row in csv.reader(file):
print   row[0], row[1], row[2], row[3],row[4], row[5], row[6]

it's ok,
when i  add(date,open,high,low,close,vol,adjclose) = (row[0], row[1], 
row[2], row[3],row[4], row[5], row[6])
change the code into 
import os
import  csv

for  name  in   os.listdir('/tmp/quote/'):
filename='/tmp/quote/'+name
file = open(filename,'r')
file.readline()  
for row in csv.reader(file):
(date,open,high,low,close,vol,adjclose) = (row[0], row[1], row[2], 
row[3],row[4], row[5], row[6])
print   row[0], row[1], row[2], row[3],row[4], row[5], row[6]


the wrong  output is :
file = open(filename,'r')
TypeError: 'str' object is not callable

i don't know why??-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-06 Thread Peter Otten
Jon Redgrave wrote:

> It seems unreasonably hard to write simple one-line unix command line
> filters in python:
> 
> eg: ls | python -c "  print x.upper()"
> 
> to get at sys.stdin or similar needs an import, which makes a
> subsequent for-loop illegal.
> python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError
> 
> Am I missing something obvious?
> 
> The best I've come up with is to use sitecustomize.py to add to
> __builtin__
> def stdin():
>   import sys
>   for x in sys.stdin():
> if not x: return
> yield x.strip()
> import __builtin__
> __builtin__.stdin = stdin
> 
> This allows
> ls | python -c "for x in stdin(): print x.upper()"
> 
> Is there a better solution - if not is this worth a PEP?

$ touch alpha beta gamma omega
$ ls | python -c 'import sys; sys.stdout.writelines(s.upper() for s in 
sys.stdin if s.startswith(("a", "o")))'
ALPHA
OMEGA

If you are doing this a lot, why don't you write a helper script and invoke 
that? 

$ ls | pyfilter.py -f '"m" in line' -s 'lines = (line + line[::-1] for line 
in map(str.strip, lines))' -s'import re' -p 're.compile(r"(([a-
z])\2)").sub(lambda m: m.group(1).upper(), line)'
alphAAhpla
betAAteb
gaMMAAMMag
omegAAgemo

This relies on the convention that a single line of input is accessible as 
"line" and the complete input is called "lines". Of course the same can be 
done with python -c ..., -- and it is even more readable:

$ ls | python -c 'import re, sys
for line in sys.stdin:
> line = line.strip()
> line = line + line[::-1]
> print re.compile(r"(([a-z])\2)").sub(lambda m: m.group(1).upper(), 
line)
> '
alphAAhpla
betAAteb
gaMMAAMMag
omegAAgemo

> Is there a better solution - if not is this worth a PEP?

The python interpreter could accept multiple -c arguments, but to see how 
this will be received a post on python-ideas should be sufficient.

For the sake of completeness here's the script I used to produce the example 
above:

$ cat pyfilter.py
#!/usr/bin/env python
import sys

def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-s", "--setup",
action="append", default=[],
dest="setups", metavar="SETUP")
parser.add_argument(
"-f", "--filter",
action="append", default=[],
dest="filters", metavar="FILTER")
parser.add_argument("-p", "--print", dest="format")

args = parser.parse_args()
lines = sys.stdin
for setup in args.setups:
exec setup
for line in lines:
line = line.rstrip("\n")
for filter in args.filters:
if not eval(filter):
continue
if args.format:
line = eval(args.format)
try:
print line
except IOError as e:
if e.errno == 32: # broken pipe
break
raise
if __name__ == "__main__":
main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point multiplication in python

2011-09-06 Thread Steven D'Aprano
On Tue, 6 Sep 2011 03:57 pm xyz wrote:

> hi all:
> 
> As we know ,  1.1 * 1.1 is 1.21 .
> But in python ,I got following :
> 
 1.1 * 1.1
> 1.2102


The problem is that 1.1 is a *decimal* number, but computers use *binary*,
and it is impossible to express 1.1 exactly as a binary number. So when you
type 1.1 into nearly all computer languages, what you are actually getting
is a tiny bit more than 1.1:

>>> repr(1.1)
'1.1001'


which is the closest number to 1.1 that is possible using a C double
floating point number.

Normally you don't see it, because Python truncates the result when
printing:

>>> str(1.1)
'1.1'

but the difference is there.


-- 
Steven

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


Re: One line command line filter

2011-09-06 Thread John Wiegley
> Jon Redgrave  writes:

> It seems unreasonably hard to write simple one-line unix command line
> filters in python:

> eg: ls | python -c " print x.upper()"

[...]

> Is there a better solution - if not is this worth a PEP?

Have you looked at PyP (http://code.google.com/p/pyp)?

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


Re: Floating point multiplication in python

2011-09-06 Thread Gary Herron

On 09/05/2011 10:57 PM, xyz wrote:

hi all:

As we know ,  1.1 * 1.1 is 1.21 .
But in python ,I got following :


1.1 * 1.1

1.2102

why python get wrong result? Who can tell me  where's the 0.0002 
from?


It's not a python errorIt's the nature of floating point arithmetic 
to be inaccurate on *ANY* computer.Python just allows you to see the 
inaccuracies.


(But try:
  print 1.1*1.1
and see that the print statement does hide the roundoff error from you.)

Read this for more info:

http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate


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