Re: range() vs xrange() Python2|3 issues for performance

2011-08-04 Thread Chris Angelico
On Thu, Aug 4, 2011 at 4:01 AM, Steven D'Aprano
 wrote:
>        a, b = divmod(n, i)
>        if b == 0:
>            total += a+i
>

Wouldn't this fail on squares? It happens to give correct results as
far as I've checked; no square up to 10,000 is called perfect, and
there are no perfect squares in that range, but I think it's
technically using an incorrect intermediate result.

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


Re: Inconsistencies with tab/space indentation between Cygwin/Win32?

2011-08-04 Thread Chris Rebert
On Wed, Aug 3, 2011 at 9:25 PM, Christian Gelinek
 wrote:
> Hi all,
>
> I have a problem running some python program using version 2.6.4 (or version
> 2.7.2, I tried both) from the Win7 command line - it never finishes due to
> an infinite loop. The thing is, when I run the same program through Cygwin
> which uses Python version 2.6.5, it exits the loop at some point.
>
> I came to try this after I realised that in some of the sources (it is a
> rather big program using many source files, most of them being created by
> others from a Linux environment), the indentation is mixed tabs/spaces where
> the assumed tab size is 8 spaces.

That's just plain evil.

> Reading on the Python website, a tab size of 8 is default anyway, so I would
> have assumed it should work... does that mean that one tab equals 2
> indents?!? I myself never use tabs to indent Python code but let my editor
> do a tab-to-4-spaces conversion when I press .
>
> I find it at least confusing to read that Python expects a tab size of 8 but
> at the same time uses 4 spaces for one indent level. Or maybe I am
> completely on the wron track here?

4-space indents are /recommended/ by PEP 8, but the interpreter does
not require or prefer that style. What the interpreter does when
parsing indentation is rather more complicated; see
http://docs.python.org/reference/lexical_analysis.html#indentation

You might wanna look at tabnanny:
http://docs.python.org/library/tabnanny.html

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


Re: making my extensions work together

2011-08-04 Thread Chris Angelico
On Thu, Aug 4, 2011 at 2:19 AM, Mathew  wrote:
> I have 2 extensions and they both access a function in a (static) library.
> The function maintains state information using a static variable.

If your extensions are DLLs and they're both linking to the same
static library, you should have two independent copies of that library
- which would mean they don't interfere with one another. That's why
the other extension doesn't see the change, and normally this is the
correct and desired behaviour.

Having the two be aware of each other is potentially very messy. As
Stefan suggested, making one depend on the other would be a lot
simpler. Alternatively, there may be ways to have the two extensions
share data through Python itself. What are you looking to accomplish?

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


finding the object corresponding to a stack frame

2011-08-04 Thread Eric Snow
For any given stack frame, the corresponding code object is derived
most immediately from either a module [definition], a class
definition, or function definition.  I want to be able to determine
the specific module, class, or function object for any arbitrary
code/frame object.  For modules it is pretty straightforward.  For
classes, the object doesn't exist yet, but I can work around that.

Lastly, for functions it is not nearly as simple as I had hoped.  If
the function is defined in the global namespace then the solution is
relatively trivial, using the inspect module:

def get_context():
frame = inspect.currentframe().f_back
if frame.f_code.co_name == "":
return sys.modules[frame.f_locals["__name__"]]
return frame.f_globals.get(frame.f_code.co_name)

def f():
context = get_context()
f()

However, under other conditions it is not so easy:

- the function is nested inside another,
- the code object is shared between multiple functions,
- the function is accessed as an attribute of some other object and
thus is not bound by its name in the easy search namespaces (like
globals),
- others?

I'm trying to see if there is a way to work through these issues.  It
would be great if objects knew under which object each was defined,
but that is a bigger question for another time.  Right now I would
just settle for a frame object knowing the object for which it is
running, particularly for functions.  However, judging by similar
questions found while researching this, I'm not holding my breath.

Any ideas?

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


Re: Inconsistent SMTP/Gmail connection drop

2011-08-04 Thread Astley Le Jasper
Thanks for those suggestions.

I tried something last night before I got your ideas.

1. I added a line to send a copy of the report just to me, 2 lines
before the line where it emails the report to all the recipients.
2. I also added a timer.sleep(5) pause just before the line that
emails the reports to all the recipients.

So the order was:

a) Send the full report just to me  FAILED.
b) Pause for 5 seconds.
c) Send the full report to all 4 recipients ... WORKED.
d) Send the log file just to me ... WORKED.

So ... what looks like may be happening is that something might still
be locking the file. In which case i'll try again without the test
email to me. And/or perhaps send a test email without the attachment
before the main report to see if that gets through, to see if the
connection with gmail is actually really connected.

See also below...

> 1) You might see if there's something about the size of the message - is it
> bigger after collecting data all night?  Is google disconnecting after a
> maximum amount of data is transferred?

I don't think so. The test message I mentioned above got through and
the attachment was identical (320kb or abouts)

> 2) You might try sending a tiny test message at the beginning, just to
> yourself, and seeing if that has the problem

As above.

> 3) You might try running your script under a system call tracer:
> http://stromberg.dnsalias.org/~dstromberg/debugging-with-syscall-tracers.html
> - and inspecting the list of syscalls and their return codes near when the
> process terminates

Ouch. Looks complicated!
;-)

> 4) I get disconnects from gmail once in a while too, especially when
> downloading a large list of new message headers; I've been just coding
> around it by making my code idempotent and otherwise restartable.  This
> seems to happen with both 2.x and 3.x, so I assume it's not really related
> to the Python version, but I suppose I should try it on PyPy or Jython
> someday.  Note that the error message in 3.x was better than in 2.x.

I was thinking that perhaps I could put a loop in that tests if the
email goes through, and if not, pauses for a few seconds and then
tries again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Snippet: The leanest Popen wrapper

2011-08-04 Thread Thomas Rachel

Am 03.08.2011 19:27 schrieb Chris Rebert:


 shell= True,


I would strongly encourage you to avoid shell=True.


ACK, but not because it is hard, but because it is unnecessary and 
unelegant at this point.



You really don't want to have to worry about doing proper shell escaping 
yourself.


That's nothing to really worry about - just doing

def shellquote(*strs):
return " ".join([
"'"+st.replace("'","'\\''")+"'"
for st in strs
])

would do perfectly: shellquote('echo', "'", '"', " ", "\n")
If you emit a command line over ssh, for example, you don't have another 
simple choice.


There are only worries if there is a shell which better shouldn't be 
named like this. As you generally cannot know what ugly things the user 
of your program does, it is better to avoid the additional shell layer.


So generally agree to what you say, but it is not the proper shell 
escaping one should worry about (it is so simple that one cannot call it 
"worry"), but the type of shell one talks with.


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


Re: Snippet: The leanest Popen wrapper

2011-08-04 Thread Thomas Rachel

Am 03.08.2011 17:29 schrieb Phlip:

Groupies:

This is either a code snippet, if you like it, or a request for a
critique, if you don't.


Well, at first, I cannot see the real point about it...



def command(*cmdz):

 process = Popen( flatten(cmdz),
  shell= True,
  stdout= subprocess.PIPE,
  stderr= subprocess.PIPE,
  bufsize= 4096 )

 def line():
 return process.stdout.readline().rstrip()

 def s():
 while True:
 l = line()
 if not l:  break
 yield l

 line.s = s

 return line


I find it quite ugly. You get a function object with an attached 
generator (which has a strange and non-verbose name and) which might 
stop too early due to an empty line. Plus, you have no real control over 
the communication; you have no access to stdin or stderr. The latter 
might produce a lock if the process writes out too much on stderr.


Plus, you have no access to the exit code of the program.

And you lose information about if the stream ends with any combination 
of whitespace.




That leads to some syntactic sugar. For example, one truly demented
way to stream in an entire block and then treat it as one big string
is this:

print '\n'.join(command('ls').s())


What would work as well via

print Popen( ['ls'], stdout= subprocess.PIPE).stdout.read()
or
print Popen( ['ls'], stdout= subprocess.PIPE).communicate()[0]



The point of the command() complex is the ability to start a long
command and then fetch out individual lines from it:

line = command('find', '../..')


sp = Popen( ['find', '../..'], stdout= subprocess.PIPE).stdout.read()
line = sp.stdout.readline
# if you want so: line = lambda: sp.stdout.readline().rstrip() - which
# might lose information as well...


print 'lines'
print line()
print line()
print line()

print 'all'
print list(line.s())

print list(iter(line, ''))


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


Re: Snippet: The leanest Popen wrapper

2011-08-04 Thread Chris Rebert
On Thu, Aug 4, 2011 at 1:10 AM, Thomas Rachel

wrote:
> Am 03.08.2011 19:27 schrieb Chris Rebert:
>
>>>                     shell= True,
>>
>> I would strongly encourage you to avoid shell=True.
>
> ACK, but not because it is hard, but because it is unnecessary and unelegant
> at this point.
>
>> You really don't want to have to worry about doing proper shell escaping
>> yourself.
>
> That's nothing to really worry about - just doing
>
> def shellquote(*strs):
>        return " ".join([
>                "'"+st.replace("'","'\\''")+"'"
>                for st in strs
>        ])
>
> would do perfectly: shellquote('echo', "'", '"', " ", "\n")

I was considering the more general case where one of the strings may
have come from user input. You then need to also escape
$looks_like_a_var, `some_command`, and way more other such stuff that
your simple function doesn't cover. Even if the user is trusted, not
escaping such things can still lead to bizarre unintended
output/results.

If the commands are completely static, then yes, I agree that lack of
necessity then becomes the main argument against shell=True.

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


Re: Inconsistent SMTP/Gmail connection drop

2011-08-04 Thread Astley Le Jasper
Just to add a little bit to the mix, I have started having these
problems since I rebuilt my machine (Xubuntu 11) and I changed the
disc formats to ext4 without even thinking about it ... I was
wondering if maybe that had something to do with it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Snippet: The leanest Popen wrapper

2011-08-04 Thread Thomas Rachel

Am 04.08.2011 10:42 schrieb Chris Rebert:


I was considering the more general case where one of the strings may
have come from user input. You then need to also escape
$looks_like_a_var, `some_command`, and way more other such stuff that
your simple function doesn't cover.


Even these things are harmless when included in ''s.

$ echo '`rm -rf .`' '$RANDOM'
`rm -rf .` $RANDOM

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


ImportError: No module named PyQt4.QtGui

2011-08-04 Thread 守株待兔
i have  installed such things:

sudo apt-get install libqt4-dev
sudo apt-get install g++ automake
sudo apt-get install qt4-dev-tools qt4-designer qt4-doc
sudo apt-get install libqt4-opengl-dev
sudo apt-get install libqt4-sql-mysql libqt4-sql-odbc libqt4-sql-psql 
libqt4-sql-sqlite libqt4-sql-sqlite2

when i finished,input 
>>>from PyQt4.QtCore import *
Traceback (most recent call last):
   File "", line 1, in 
ImportError: No module named PyQt4.QtCore
 
would you mind to tell me how to solve it?-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ImportError: No module named PyQt4.QtGui

2011-08-04 Thread Thomas Jollans
On 04/08/11 11:39, 守株待兔 wrote:
> i have  installed such things:
> 
> sudo apt-get install libqt4-dev
> sudo apt-get install g++ automake
> sudo apt-get install qt4-dev-tools qt4-designer qt4-doc
> sudo apt-get install libqt4-opengl-dev
> sudo apt-get install libqt4-sql-mysql libqt4-sql-odbc libqt4-sql-psql
> libqt4-sql-sqlite libqt4-sql-sqlite2
> 
> when i finished,input
from PyQt4.QtCore import *
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named PyQt4.QtCore
>  
> would you mind to tell me how to solve it?
> 
> 

http://lmgtfy.com/?q=debian+pyqt4

You haven't actually installed the python-qt4 bindings yet. All you
installed is the C++ library.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: range() vs xrange() Python2|3 issues for performance

2011-08-04 Thread Steven D'Aprano
Chris Angelico wrote:

> On Thu, Aug 4, 2011 at 4:01 AM, Steven D'Aprano
>  wrote:
>> a, b = divmod(n, i)
>> if b == 0:
>> total += a+i
>>
> 
> Wouldn't this fail on squares? It happens to give correct results as
> far as I've checked; no square up to 10,000 is called perfect, and
> there are no perfect squares in that range, but I think it's
> technically using an incorrect intermediate result.

Yes, you're correct -- it counts sqrt(n) twice as a factor if n is a perfect
square. The obvious fix is to change the increment to:

total += a if a==i else a+i

I don't believe it actually makes a difference for perfect numbers, but it's
worth getting right.


-- 
Steven

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


PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Gelonida N
I posted already a  question, but perhaps the subject line wasn't clear.


Subject line was "Text to image with same results on any platform"


>From within a django application
I'd like create a small image file (e.g. .png)
which just contains some text.

I wondered what library would be appropriate and would yield the same
result independent of the OS (assuming the versions of the python
libraries are the same)
Images should be pixel identical independent on the platform on which
the image is created.

I made some attempts with PIL (Image / ImageFont / ImageDraw),
but have difficulties getting the same font under Linux and windows.


# code starts here
import Image
import ImageFont
import ImageDraw

# Here I don't know how to get the same font file
# for all platforms
# Perhaps there is a tiny trick that I overlooked.
font_file = get_font_file_name()
# Is truetype a good choice for portable fonts?
font = ImageFont.truetype(font_file, 20)

img = Image.new("RGB", (800, 600), "#FF")
draw = ImageDraw.Draw(image)

draw.text( (100, 100), font=font, fill="#00FF00")
#  end of code


I could also install any other library (matplotlib??)
if it were capable of creating consistent images
independent on the platform.

Thanks in advance for any suggestions.










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


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Thomas Jollans
On 04/08/11 12:04, Gelonida N wrote:
> I posted already a  question, but perhaps the subject line wasn't clear.
> 
> 
> Subject line was "Text to image with same results on any platform"
> 

Oh, your original message was perfectly clear, and if I knew the answer,
I might have responded. Anyway, into thought.

> 
>>From within a django application
> I'd like create a small image file (e.g. .png)
> which just contains some text.
> 
> I wondered what library would be appropriate and would yield the same
> result independent of the OS (assuming the versions of the python
> libraries are the same)
> Images should be pixel identical independent on the platform on which
> the image is created.
> 
> I made some attempts with PIL (Image / ImageFont / ImageDraw),
> but have difficulties getting the same font under Linux and windows.

Perhaps PIL uses a different font rendering library on each platform?
You could try to get around this by using
http://code.google.com/p/freetype-py/ directly. It's also possible that
different hinting settings on the different systems are playing a role
somehow, somewhere. Perhaps you can tell freetype precisely what to do,
I'm not sure.

If you want exactly the same bitmap on different platforms, you could
just scrap truetype alltogether, and use bitmaps directly, individually
taking the characters you need from a resource file. (you know, one
bitmap with all the characters at known coordinates - or a load of small
bitmaps)

Why do you need the images to be identical to the pixel anyway? Surely,
if it's about comparing the text, you would just compare the strings?
And if it's only for displaying the text, then why bother with details
like that as long as it looks good?

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


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Steven D'Aprano
Gelonida N wrote:

> I wondered what library would be appropriate and would yield the same
> result independent of the OS (assuming the versions of the python
> libraries are the same)
> Images should be pixel identical independent on the platform on which
> the image is created.

Short answer: you can't.

Long answer: you might, if you can find identical fonts (not just fonts with
the same name, but genuinely identical) for each platform, and find some
way of telling each platform's font rendering software to use identical
algorithms (e.g. kerning, hinting, scaling, sub-pixel rendering), and
adjust for any other differences between platforms (e.g. font sizes on
Windows tend to be larger than on Mac or Linux).

And when I say "you might", I mean it is theoretically possibly, but
practically speaking, you can't.

Even longer answer: you can, if you ignore the platform font renderer, and
use your own custom renderer; this is what (apparently) a number of
Linux/Unix applications like Abiword and xpdf do (with varying levels of
success). You still need to find identical fonts for each platform.
Possibly the simplest way to do this is to stick to old-fashioned bitmapped
fonts in fixed sizes, instead of Postscript or TrueType fonts -- assuming
you don't mind your application's output looking like it was produced on a
Macintosh in 1984.

More information here:

https://freddie.witherden.org/pages/font-rasterisation/
http://www.joelonsoftware.com/items/2007/06/12.html
http://www.codinghorror.com/blog/2007/06/whats-wrong-with-apples-font-rendering.html
http://jujusoft.com/?page_id=25


-- 
Steven

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


PyWhich

2011-08-04 Thread Billy Mays

Hey c.l.p.,

I wrote a little python script that finds the file that a python module 
came from.  Does anyone see anything wrong with this script?



#!/usr/bin/python

import sys
if __name__ == '__main__':
if len(sys.argv) > 1:
try:
m = __import__(sys.argv[1])
sys.stdout.write(m.__file__ + '\n')
sys.stdout.flush()
sys.exit(0)
except ImportError:
sys.stderr.write("No such module '%s'\n" % sys.argv[1])
sys.stderr.flush()
sys.exit(1)
else:
sys.stderr.write("Usage: pywhich \n")
sys.stderr.flush()
sys.exit(0)


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


Re: making my extensions work together

2011-08-04 Thread Mathew
more info.  I have a large 3rd party library with a function that looks like 
this
void dumbfunc() {
static int statevar=0;
++statevar;
if (startvar ==3) printf("I have been called 3 times\n");
}

and I have 2 extensions, foo,py goo.py,created with SWIG, and the both make 
calls to dumbfunc. In creating the extensions, I linked to the 3rd party 
library.

The behavior I want to see is
>foo.dumbfunc()
>goo.dumbfunc()
>goo.dumbfunc()
I have been called 3 times


"Chris Angelico"  wrote in message 
news:mailman.1880.1312441742.1164.python-l...@python.org...
> On Thu, Aug 4, 2011 at 2:19 AM, Mathew  wrote:
>> I have 2 extensions and they both access a function in a (static) 
>> library.
>> The function maintains state information using a static variable.
>
> If your extensions are DLLs and they're both linking to the same
> static library, you should have two independent copies of that library
> - which would mean they don't interfere with one another. That's why
> the other extension doesn't see the change, and normally this is the
> correct and desired behaviour.
>
> Having the two be aware of each other is potentially very messy. As
> Stefan suggested, making one depend on the other would be a lot
> simpler. Alternatively, there may be ways to have the two extensions
> share data through Python itself. What are you looking to accomplish?
>
> ChrisA 


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


Re: making my extensions work together

2011-08-04 Thread Katriel Cohn-Gordon
Wrap your 3rd party library with a Python interface module, and run all
calls from foo and goo through your interface.

On Thu, Aug 4, 2011 at 2:48 PM, Mathew  wrote:

> more info.  I have a large 3rd party library with a function that looks
> like
> this
> void dumbfunc() {
> static int statevar=0;
> ++statevar;
> if (startvar ==3) printf("I have been called 3 times\n");
> }
>
> and I have 2 extensions, foo,py goo.py,created with SWIG, and the both make
> calls to dumbfunc. In creating the extensions, I linked to the 3rd party
> library.
>
> The behavior I want to see is
> >foo.dumbfunc()
> >goo.dumbfunc()
> >goo.dumbfunc()
> I have been called 3 times
>
>
> "Chris Angelico"  wrote in message
> news:mailman.1880.1312441742.1164.python-l...@python.org...
> > On Thu, Aug 4, 2011 at 2:19 AM, Mathew  wrote:
> >> I have 2 extensions and they both access a function in a (static)
> >> library.
> >> The function maintains state information using a static variable.
> >
> > If your extensions are DLLs and they're both linking to the same
> > static library, you should have two independent copies of that library
> > - which would mean they don't interfere with one another. That's why
> > the other extension doesn't see the change, and normally this is the
> > correct and desired behaviour.
> >
> > Having the two be aware of each other is potentially very messy. As
> > Stefan suggested, making one depend on the other would be a lot
> > simpler. Alternatively, there may be ways to have the two extensions
> > share data through Python itself. What are you looking to accomplish?
> >
> > ChrisA
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: making my extensions work together

2011-08-04 Thread Mathew
okay. It worked to make my 3'rd party library dynamic. Hopefully this will 
help someone else in the future.


"Mathew"  wrote in message 
news:j1cs2t$j2f$1...@news.jpl.nasa.gov...
> This isn't exactly a Python question but maybe someone here has run into 
> this.
>
> I have 2 extensions and they both access a function in a (static) library. 
> The function maintains state information using a static variable.
>
> This doesn't work. When one of my extensions changes the variable value, 
> the other extension does not see the change.
>
> Would it work if I made my library dynamic?
>
> This is on Windows XP compiling with MSVC 2008.
>
> -Mathew
> 


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


Re: Community Involvement

2011-08-04 Thread Ethan Furman

Steve Holden wrote:
We would ideally like the last project to to be something that 
demonstrates at least some minimal involvement with the Python 
community. Something like "get a Python answer upvoted on 
StackOverflow", for example, or getting a question answered on c.l.p. At 
the same time it shouldn't be anything that places a burden on the 
community (otherwise the hundredth student would be abused and the 
thousandth murdered).


The problem I see with either of those is making the student's academic 
standing dependent on the actions of strangers.  Having said that...


Posting a question to c.l.py is fine if you have a real question, but if 
you don't...


Of the two, I like the StackOverflow option better -- but keep in mind 
that at this moment, about 6,600 unanswered Python questions remain. 
(I've made it to page 23 of 132 over the last week.)  Getting an answer 
upvoted can be pretty hit-and-miss.


Perhaps the thing to do is have a wide range of options, any one of 
which will satisfy the requirement -- some will have questions to post, 
others may have a bug to file or, even better, a patch for a bug, others 
can go the StackOverflow route, someone may have a module to put on 
PyPI, etc., etc.


Hope this helps!

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


Re: Community Involvement

2011-08-04 Thread sparky gmail

On 8/3/2011 8:14 PM, Steve Holden wrote:

[Ccs appreciated]

After some three years labor I (@holdenweb) at last find myself 
approaching the completion of the Python Certificate Series with 
O'Reilly School of Technology (@OReillySchool).


At OSCON last week the team fell to talking about the final assignment 
(although the Certificate is not a certification, students only 
progress by answering real quiz questions, not the usual 
multiple-choice task). Success also requires that they complete a 
project at the end of each (of the ~60) lesson(s).


We would ideally like the last project to to be something that 
demonstrates at least some minimal involvement with the Python 
community. Something like "get a Python answer upvoted on 
StackOverflow", for example, or getting a question answered on c.l.p. 
At the same time it shouldn't be anything that places a burden on the 
community (otherwise the hundredth student would be abused and the 
thousandth murdered).


So I wondered if anyone had any good ideas.

regards
 Steve
--
Steve Holden
st...@holdenweb.com 




Just a thought.

What about contributing code or documentation to an established project?

I dislike the idea of getting an answer up voted. First of all, for 
people trying to do it honestly you are putting
their completion into the hands of strangers, secondly, it would be very 
easy to cheat by having someone else,

or themselves with a puppet account, up vote the answer.

There are a metric grip of established projects that could use a little 
help with documentation, code examples, etc.

I think this is a better route to community participation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWhich

2011-08-04 Thread Chris Rebert
On Thu, Aug 4, 2011 at 5:43 AM, Billy Mays
<81282ed9a88799d21e77957df2d84bd6514d9...@myhashismyemail.com> wrote:
> Hey c.l.p.,
>
> I wrote a little python script that finds the file that a python module came
> from.  Does anyone see anything wrong with this script?
>
>
> #!/usr/bin/python
>
> import sys
> if __name__ == '__main__':
>    if len(sys.argv) > 1:
>        try:
>            m = __import__(sys.argv[1])
>            sys.stdout.write(m.__file__ + '\n')
>            sys.stdout.flush()
>            sys.exit(0)
>        except ImportError:
>            sys.stderr.write("No such module '%s'\n" % sys.argv[1])
>            sys.stderr.flush()
>            sys.exit(1)
>    else:
>        sys.stderr.write("Usage: pywhich \n")
>        sys.stderr.flush()
>        sys.exit(0)

Nothing wrong per se, but the flush()es seem unnecessary, and why do
stdout.write() when you can just print()?

Cheers,
Chris
--
I can't not think of the pitchman when I read your posts...
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWhich

2011-08-04 Thread Tim Chase

On 08/04/2011 07:43 AM, Billy Mays wrote:

Hey c.l.p.,

I wrote a little python script that finds the file that a python module
came from.  Does anyone see anything wrong with this script?

#!/usr/bin/python

import sys
if __name__ == '__main__':
  if len(sys.argv)>  1:
  try:
  m = __import__(sys.argv[1])
  sys.stdout.write(m.__file__ + '\n')


For a quick script in a controlled environment, not bad.  In a 
hostile environment, I'd be nervous about running arbitrary 
module code triggered by the import.  Even if non-malicious, some 
imports (like PyCrypto) may have some initialization lag which 
would be nice to avoid.  I think I'd make use of imp.find_module 
to write it something like this (untested)


  from sys import argv, stderr
  import imp
  type_map = {
imp.PY_SOURCE: "Source file",
imp.PY_COMPILED: "Compiled code object",
imp.C_EXTENSION: "Dynamically loadabld shared library",
imp.PKG_DIRECTORY: "Package directory",
imp.C_BUILTIN: "Built-in",
imp.PY_FROZEN: "Frozen module",
}
  if __name__ == '__main__':
if len(argv) > 1:
  for modname in argv[1:]:
try:
  fp, pth, desc = imp.find_module(modname)
  (suffix, mode, type_) = desc
  if fp is not None: fp.close()
  print("%s\t[%s]" % (
pth,
type_map.get(type_, "UNKNOWN")
))
except ImportError:
  stderr.write("No such module '%s'\n" % modname)
else:
  stderr.write("Usage: pywhich  [...]\n")

I don't know a good way to tap into other import hooks (such as 
the zipfile import) to augment that type_map dictionary.


-tkc



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


problem with bcd and a number

2011-08-04 Thread nephish
Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with bcd and a number

2011-08-04 Thread nephish
Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Gelonida N
On 08/04/2011 12:32 PM, Thomas Jollans wrote:
> On 04/08/11 12:04, Gelonida N wrote:
Thanks for your answer.

>> >From within a django application
>> I'd like create a small image file (e.g. .png)
>> which just contains some text.
>>
>> I wondered what library would be appropriate and would yield the same
>> result independent of the OS (assuming the versions of the python
>> libraries are the same)
>> Images should be pixel identical independent on the platform on which
>> the image is created.
>>
>> I made some attempts with PIL (Image / ImageFont / ImageDraw),
>> but have difficulties getting the same font under Linux and windows.
> 
> Perhaps PIL uses a different font rendering library on each platform?
> You could try to get around this by using
> http://code.google.com/p/freetype-py/ directly. It's also possible that
> different hinting settings on the different systems are playing a role
> somehow, somewhere. Perhaps you can tell freetype precisely what to do,
> I'm not sure.

The reason why I want the images to  look identical is very simple.
Though the final web server will run on a linux server, I use sometimes
windows for development or as test server.

For automated tests I would have liked pixel identical images.
this allows calculating the md5sum of images to know whether
a regression in the image layout occured. Well I can live without it.

The second (more import issue) is, that the images should look the same
whether created on a Windows or Linux host.

I didn't know that PIL delegated font rendering to the underlying OS,
but thought it contains its own rendering.

Here the problem is not if a few pixels are different, but currently I
even don't know how to choose a font, and make sure it exists on both
platforms. I also don't know how I can write portable python code,  that
will find a given font on windows and on linux independent of the exact
font location.


> 
> If you want exactly the same bitmap on different platforms, you could
> just scrap truetype alltogether, and use bitmaps directly, individually
> taking the characters you need from a resource file. (you know, one
> bitmap with all the characters at known coordinates - or a load of small
> bitmaps)

A resource file or a bitmapped font packaged with my application might
be a solution.
I just had to learn where to get one from or how to create one without
any copyright issues
> 
> Why do you need the images to be identical to the pixel anyway? Surely,
> if it's about comparing the text, you would just compare the strings?
> And if it's only for displaying the text, then why bother with details
> like that as long as it looks good?

I hope I clarified a little what I was looking for.
It's not necessarily pixel true, but it should not be too visible
whether the image was rendered on a windows or linux PC



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


python glibc issue

2011-08-04 Thread Garrett, Benjamin D
Hi, I am running into a problem with Python 2.6 and SuSe 11 SP1. The error 
message looks just like this one:

https://bugzilla.redhat.com/show_bug.cgi?id=556584

That link implies the fix is to upgrade to > glibc-2.11.90.  But for this 
particular hardware, it would be difficult to upgrade the core operating 
system's glibc as novell hasn't blessed a version of glibc > 2.11.1.  Also, 
using an upgraded dynamic/shared version of glibc seems to produce 
incompatibilities with core operating systems commands.

So, is it possible to build python against a static version of glibc?  I've 
tried installing a static glibc 2.12 on a different machine, then configuring 
python with 'configure -disable-shared 
--with-libc=/usr/lib64/libc_nonshared.a'.  python builds but an ldd still seems 
to think the resulting executable depends on libc.so.6.

I've tried google but found nothing concrete.

Any other suggestions or comments would be greatly appreciated.

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


Re: problem with bcd and a number

2011-08-04 Thread Dave Angel

On 01/-10/-28163 02:59 PM, nephish wrote:

Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.

Your problem is simply to extract the two nibbles from a byte.  Then you 
can use trivial arithmetic to combine the nibbles.  Error checking is 
another matter.


First you need to specify whether this is Python 2.x or Python 3.x.  In 
this message I'll assume 2.7


>>> val = "\x47"
>>> print val
G
>>> print ord(val)
71
>>> print ord(val)/16
4
>>> print ord(val)%16
7
>>>

DaveA


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


Re: problem with bcd and a number

2011-08-04 Thread Ethan Furman

nephish wrote:

Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.


As I recall, when you cut a byte in half you get two nibbles.  You need 
to translate your nibbles into numbers, then multiply and add -- 
something like this:


8<--- bcd.py --
def bcd_to_int(msb, lsb):
"""msb has two decimal digits, lsb has one
e.g. msb has xy=10, lsb has zX = 00, actual number (xyz)
is 100"""
ones = lsb >> 4
tens = msb & 0x0f
hundreds = msb >> 4
if ones > 9 or tens > 9 or hundreds > 9:
raise ValueError(
  "invalid BCD digits in %02x %02x" % (msb, lsb)
  )
tens *= 10
hundreds *= 100
answer = hundreds + tens + ones
return answer

if __name__ == '__main__':
import unittest

class Test_BCD(unittest.TestCase):
def test_valid(self):
msb = 0x09
lsb = 0x34  # 4 will be discarded as garbage
self.assertEqual(bcd_to_int(msb, lsb), 93)
def test_invalid(self):
msb = 0x1a
lsb = 0x10
self.assertRaises(ValueError, bcd_to_int, msb, lsb)

unittest.main()
8<-

Hope this helps.

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


Re: problem with bcd and a number

2011-08-04 Thread Christoph Hansen

nephish schrieb:


thanks for any tips on this.


I'll try.

In BCD a (decimal) digit is stored in a halfbyte (or a 'nibble'). So, in 
a byte

you can store two decimal digits. For instance 42 would be

nibble1 nibble2
0100 0010
42

>>> c=0b0110
>>> c
66
>>> c >> 4   # first nibble
4
>>> c & 0b # second nibble
2


So, a speed of 57% should be
LSB= 0111 
MSB=  0101
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Irmen de Jong
On 4-8-2011 20:54, Gelonida N wrote:

> The reason why I want the images to  look identical is very simple.
> Though the final web server will run on a linux server, I use sometimes
> windows for development or as test server.
> 
> For automated tests I would have liked pixel identical images.
> this allows calculating the md5sum of images to know whether
> a regression in the image layout occured. Well I can live without it.

Then don't run your automated tests on the dev server but deploy your stuff to a
separate test server first, that runs the same software as production. And run 
the tests
there.


> The second (more import issue) is, that the images should look the same
> whether created on a Windows or Linux host.
> 
> I didn't know that PIL delegated font rendering to the underlying OS,
> but thought it contains its own rendering.

I'm pretty sure it does have that indeed; it links with the freetype library. 
Are you
sure you're not just seeing differences because of differences in the typeface 
itself?

A courier.ttf on one system can look very different from a ms-courier-new.ttf 
on another...

> Here the problem is not if a few pixels are different, but currently I
> even don't know how to choose a font, and make sure it exists on both
> platforms. I also don't know how I can write portable python code,  that
> will find a given font on windows and on linux independent of the exact
> font location.

I once made a module that uses PIL to draw captcha images. It uses one of the 
free
truetype font files that I just place next to the code. I downloaded the ttf 
files from
http://www.fontgirl.com/  but there are dozens of free font sites. Just be sure 
to check
the license terms of the the typeface files.

As far as I know, I did not see any difference in output on windows, linux and 
mac os x
as long as the code used the same ttf file and PIL versions. (but I'll double 
check now
and see if I remember this correctly).

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


Re: problem with bcd and a number

2011-08-04 Thread MRAB

On 04/08/2011 19:26, nephish wrote:

Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.


The value is MSB * 100 + (LSB >> 4) * 10 + (LSB & 0xF)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Early binding as an option

2011-08-04 Thread Chris Torek
>Chris Angelico wrote:
[snippage]
>> def func(x):
>>len = len  # localize len
>>for i in x:
>>len(i)  # use it exactly as you otherwise would

In article <4e39a6b5$0$29973$c3e8da3$54964...@news.astraweb.com>
Steven D'Aprano   wrote:
>That can't work. The problem is that because len is assigned to in the body
>of the function, the Python compiler treats it as a local variable. So the
>line len=len is interpreted as len = len, which doesn't yet
>exist. There's no way of saying len = len in the body of the
>function.
>
>So you must either:
>
>(1) use a different name: length = len
>
>(2) use a fully-qualified name: import builtins; len = builtins.len

(This is my preferred form, given what one has now, if one is going
to do this in the function body.  Of course in 2.x it is spelled
__builtin__.len instead...)

>(3) do the assignment as a default parameter, which has slightly different
>binding rules: def func(x, len=len)
>
>(4) manual lookup: len = builtins.__dict__['len']  # untested
>
>
>I don't recommend that last one, unless you're deliberately trying to write
>obfuscated code :)

If Python *were* to have some kind of "tie this symbol down now"
operation / keyword / whatever, one could write:

def func(x):
snap len # here the new keyword is "snap"
for i in x:
   ... len(i) ... # use it exactly as you otherwise would

Of course there is no *need* for any new syntax with the other
construction:

def func(x,  len=len) # snapshots "len" at def() time
for i in x:
   ... len(i) ...

but if one were to add it, it might look like:

def func(x, snap len):

The advantage (?) of something like a snap or snapshot or whatever
keyword / magic-function / whatever is that you can apply it to
more than just function names, e.g.:

def func(arg):
# for this example, assume that arg needs to have the
# following attributes:
snap arg.kloniblatt, arg.frinkle, arg.tippy
...

Here, in the "..." section, a compiler (whether byte-code, or JIT,
or whatever -- JIT makes the most sense in this case) could grab
the attributes, looking up their types and any associated stuff it
wants to, and then assume that for the rest of that function's
execution, those are not allowed to change.  (But other arg.whatever
items are, here.  If you want to bind *everything*, perhaps "snap
arg" or "snap arg.*" -- see below.)

Even a traditional (CPython) byte-code compiler could do something
sort of clever here, by making those attributes "read-only" to
whatever extent the snapshot operation is defined as fixing the
binding (e.g., does it recurse into sub-attributes? does it bind
only the name-and-type, or does it bind name-and-type-and-value,
or name-and-type-and-function-address-if-function, or ... -- all
of which has to be pinned down before any such suggestion is taken
too seriously :-) ).
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with bcd and a number

2011-08-04 Thread Christoph Hansen

MRAB schrieb:


The value is MSB * 100 + (LSB>>  4) * 10 + (LSB&  0xF)


i would say

(MSB >> 4)*100 + (MSB & 0xF)*10 + (LSB >> 4)

but who knows
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with bcd and a number

2011-08-04 Thread Ethan Furman

MRAB wrote:

On 04/08/2011 19:26, nephish wrote:

Hey all,

I have been trying to get my head around how to do something, but i am
missing how to pull it off.
I am reading a packet from a radio over a serial port.

i have " two bytes containing the value i need.  The first byte is the
LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
containing digits zX and MSB containing digits xy.  The system speed
is then xyz%, where 100% means maximum speed and would be given by
bytes 00(LSB) 10(MSB)."

that is a quote from the documentation.
Anyway, i am able to parse out the two bytes i need, but don't know
where to go from there.

thanks for any tips on this.


The value is MSB * 100 + (LSB >> 4) * 10 + (LSB & 0xF)


Not according to the docs -- msb has two digits, lsb has one and garbage.

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


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Irmen de Jong
On 4-8-2011 21:30, Irmen de Jong wrote:

> As far as I know, I did not see any difference in output on windows, linux 
> and mac os x
> as long as the code used the same ttf file and PIL versions. (but I'll double 
> check now
> and see if I remember this correctly).

To follow up on myself, I've just tested it with the same ttf file on windows, 
os x and
linux. (made an image in font size 40 with 'The quick brown fox' as text 
line) The
resulting image files were byte-identical between os x and linux but the 
windows ones
were slightly different (just by a few bytes). The text in the image itself 
looked
identical though to the ones from the other systems (I couldn't see any 
difference by
looking at it) so I presume the difference is in the image compression or file 
header
metadata.

PIL's font rendering seems to produce identical results across platforms and if 
you see
a difference it must be caused by a difference in typeface file (or perhaps a 
different
PIL/freetype version on the platform).

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


Re: Community Involvement

2011-08-04 Thread Rhodri James
On Thu, 04 Aug 2011 18:04:48 +0100, Ethan Furman   
wrote:


Of the two, I like the StackOverflow option better -- but keep in mind  
that at this moment, about 6,600 unanswered Python questions remain.  
(I've made it to page 23 of 132 over the last week.)  Getting an answer  
upvoted can be pretty hit-and-miss.


The other thing that may affect this is that anything posted to SE is  
subject to the Creative Commons license.  This may be an issue for  
academic purposes, I don't know.  (It's certainly an issue when you come  
across J*ff!)


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


Re: Inconsistencies with tab/space indentation between Cygwin/Win32?

2011-08-04 Thread Nobody
On Thu, 04 Aug 2011 13:55:37 +0930, Christian Gelinek wrote:

> I find it at least confusing to read that Python expects a tab size of 8 but
> at the same time uses 4 spaces for one indent level. Or maybe I am
> completely on the wron track here?

4-column indents are a convention, not a rule. You can use however many
columns you like, and you don't even need to be consistent about it; you
can use 2 columns for one "block" and 4 columns for another. Python only
cares about "indented more than the previous line" and "indented to a
depth matching an outer level of the code".

8-column tab stops are a rule, due to it being such a long-standing
convention that some software and hardware has 8-column tab stops
hardwired (and anything which allows tab stops to be configured normally
defaults to 8 columns).

> Any ideas on how to get the thing to run under (real) Windows, hopefully
> without having to edit existing sources of people who left our company ages
> ago?

The only time you'll have problems is if you copy-and-paste code which was
written using a mix of tabs and spaces and which assumed a different tab
width. If code only ever uses tabs, the tab width doesn't matter. If code
uses a mix of tabs and spaces and it actually works, it's correct
according to Python's 8-column tab stops, even if that's not how the
programmer's editor was set up. Also, copying blocks of code which start
and end at the top-level (i.e. without indentation) will work regardless.

Where it fails is if you copy indented code from e.g. a file which used a
mix of spaces and 4-column tabs into a file which uses 8-column tabs.

If you have existing code which uses a mix of tabs and spaces where tabs
aren't 8 columns (or you aren't sure that they're 8 columns), your best
bet is to reformat the code to avoid using tabs (on Unix: "pr -t -e", or
"pr -t -e4" for 4-column tabs).

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


Re: Community Involvement

2011-08-04 Thread Eric Snow
On Wed, Aug 3, 2011 at 9:14 PM, Steve Holden  wrote:
> [Ccs appreciated]
> After some three years labor I (@holdenweb) at last find myself approaching
> the completion of the Python Certificate Series with O'Reilly School of
> Technology (@OReillySchool).
> At OSCON last week the team fell to talking about the final assignment
> (although the Certificate is not a certification, students only progress by
> answering real quiz questions, not the usual multiple-choice task). Success
> also requires that they complete a project at the end of each (of the ~60)
> lesson(s).
> We would ideally like the last project to to be something that demonstrates
> at least some minimal involvement with the Python community. Something like
> "get a Python answer upvoted on StackOverflow", for example, or getting a
> question answered on c.l.p. At the same time it shouldn't be anything that
> places a burden on the community (otherwise the hundredth student would be
> abused and the thousandth murdered).
> So I wondered if anyone had any good ideas.

While not as "community" as the mailing lists, perhaps they could post
a recipe to the activestate.

-eric

> regards
>  Steve
> --
> Steve Holden
> st...@holdenweb.com
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWhich

2011-08-04 Thread Dan Stromberg
On Thu, Aug 4, 2011 at 10:22 AM, Chris Rebert  wrote:

>
> > #!/usr/bin/python
> >
> > import sys
> > if __name__ == '__main__':
> >if len(sys.argv) > 1:
> >try:
> >m = __import__(sys.argv[1])
> >sys.stdout.write(m.__file__ + '\n')
> >sys.stdout.flush()
> >sys.exit(0)
> >except ImportError:
> >sys.stderr.write("No such module '%s'\n" % sys.argv[1])
> >sys.stderr.flush()
> >sys.exit(1)
> >else:
> >sys.stderr.write("Usage: pywhich \n")
> >sys.stderr.flush()
> >sys.exit(0)
>
> Nothing wrong per se, but the flush()es seem unnecessary, and why do
> stdout.write() when you can just print()?
>

The flushes are unnecessary, but sys.stdout.write has an advantage over
print: sys.stdout.write works pretty much the same in both 2.x and 3.x;
print doesn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


HSeparator() in gtk.layour

2011-08-04 Thread Peter Irbizon
hello,

how can I add hseparator to gtk.layout?
I tried
hseparator = gtk.HSeparator()
self.layout.put(hseparator,   50,195)
but it does not work :/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL question. having exactly same font on multiple platforms

2011-08-04 Thread Gelonida N
Thanks again to everybody,

Your answers helped me to understand better.

My pragmatic solution is now to package my program
with an open source .ttf font,
which will be used on both platforms.


On 08/04/2011 10:24 PM, Irmen de Jong wrote:
> On 4-8-2011 21:30, Irmen de Jong wrote:
> 
>> As far as I know, I did not see any difference in output on windows, linux 
>> and mac os x
>> as long as the code used the same ttf file and PIL versions. (but I'll 
>> double check now
>> and see if I remember this correctly).
> 
> To follow up on myself, I've just tested it with the same ttf file on 
> windows, os x and
> linux. (made an image in font size 40 with 'The quick brown fox' as text 
> line) The
> resulting image files were byte-identical between os x and linux but the 
> windows ones
> were slightly different (just by a few bytes). The text in the image itself 
> looked
> identical though to the ones from the other systems (I couldn't see any 
> difference by
> looking at it) so I presume the difference is in the image compression or 
> file header
> metadata.
> 
> PIL's font rendering seems to produce identical results across platforms and 
> if you see
> a difference it must be caused by a difference in typeface file (or perhaps a 
> different
> PIL/freetype version on the platform).
> 


What I finally did was following:

I copied a ttf font whoose copyright seems to be permissive ('Vera.ttf')
from my linux machine to my windows host.

I wrote following script:
import Image
import ImageFont, ImageDraw
import ImageChops


im = Image.new( "RGB", (250,60) , "#00" )

draw = ImageDraw.Draw(im)

font = ImageFont.truetype("Vera.ttf", 40)

draw.text((5, 5), "Hello world", font=font)
im.save("img.png")

im = Image.open('img.png')
iml = Image.open('img_other.png')
diff = ImageChops.difference(im, iml)
diff.save('diff.png')



and ran it on one machine
then I copied the generated file img.png to  my other platform and
renamed it to img_other.png

then I ran my script there

and displayed diff.png


What I see (but I do not have the same version of PIL on both machines)
is, that the images are different, though the difference as rather local
and not too huge.

So copying an open source ttf font to my windows machine
creates fonts, which are from an optical aspect similair enough.

I will still check whether the imgaes are identical if using the same
font file and the same PIL version.
THis should clarify whether the OS is involved in rendering the images
or not.

If really wanted to run automated tests verifying the image result I
could still do it by saving the md5sums for both platforms and veryfing
whether the result is identical to one of them.








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


Re: Text to image with same results on any platform

2011-08-04 Thread Gelonida N
Just FYI.

Thread continued in thread with the subject line
'PIL question. having exactly same font on multiple platforms'

I'm currently not pixel true, but images are sufficiently similiar.

On 08/03/2011 11:40 AM, Gelonida N wrote:
> Hi,
> 
> 
>>From within a django application
> I'd like create a small image file (e.g. .png)
> which just contains some text.
> 
> I wondered what library would be appropriate and would yield the same
> result independent of the OS (assuming the versions of the python
> libraries are the same)
> Images should be pixel identical independent on the platform on which
> the image is created.
> 
> I made some attempts with PIL (Image / ImageFont / ImageDraw),
> but have difficulties getting the same font under Linux and windows.
> 
> 



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


Re: problem with bcd and a number

2011-08-04 Thread shawn bright
Thanks for your help on this, gents. Got it working now.
shawn

On Thu, Aug 4, 2011 at 2:28 PM, Dave Angel  wrote:

> nibbles from a byte
-- 
http://mail.python.org/mailman/listinfo/python-list


error compiling python, and "plat-linux2" versus "plat-linux3"

2011-08-04 Thread Robert P. J. Day

  i may have asked about this once upon a time but i'm still fighting
with it so i'll throw myself on the mercy of the list and ask again.
(and if there's a better forum for this question, let me know.)

  i'm using the development environment wind river linux 4.2
(hereafter just "WRL") to configure and build an entire embedded
system, and that build is failing when it comes to compile
python-2.6.2.  i *think* i have an idea what the general problem is,
but i need help to narrow it down.

  here's the tail end of the build process:

= begin snippet =

Checking for unpackaged file(s): 
/home/rpjday/WindRiver/projects/42/glibc_std/host-cross/bin/../lib64/rpm/check-files
 /home/rpjday/WindRiver/projects/42/glibc_std/build/INSTALL_STAGE/python-2.6.2
error: Installed (but unpackaged) file(s) found:
   /usr/lib64/python2.6/plat-linux3/IN.py
   /usr/lib64/python2.6/plat-linux3/IN.pyc
   /usr/lib64/python2.6/plat-linux3/IN.pyo
   /usr/lib64/python2.6/plat-linux3/regen


RPM build errors:
File not found: 
/home/rpjday/WindRiver/projects/42/glibc_std/build/INSTALL_STAGE/python-2.6.2/usr/lib64/python2.6/plat-linux2
Installed (but unpackaged) file(s) found:
   /usr/lib64/python2.6/plat-linux3/IN.py
   /usr/lib64/python2.6/plat-linux3/IN.pyc
   /usr/lib64/python2.6/plat-linux3/IN.pyo
   /usr/lib64/python2.6/plat-linux3/regen
/home/rpjday/WindRiver/projects/42/glibc_std/scripts/packages.mk:2661: *** 
[python.install] Error 1
/home/rpjday/WindRiver/projects/42/glibc_std/scripts/packages.mk:3017: *** 
[python.buildlogger] Error 2
/home/rpjday/WindRiver/projects/42/glibc_std/scripts/Makefile.common.epilogue:37:
 *** [all] Error 2
GNUmakefile:55: *** [all] Error 2

#0  all at /home/rpjday/WindRiver/projects/42/glibc_std/build/GNUmakefile:55
remake[2]: Leaving directory 
`/home/rpjday/WindRiver/projects/42/glibc_std/build'
Command-line arguments:
"all"
Makefile:831: *** [all-recursive] Error 1

#0  all-recursive at /home/rpjday/WindRiver/projects/42/glibc_std/Makefile:831
remake[1]: Leaving directory `/home/rpjday/WindRiver/projects/42/glibc_std'
Command-line arguments:
"all-recursive"
make: *** [all] Error 2

= end snippet =

  note the references to "plat-linux3" above -- i think that's what's
killing me as i'm doing all this on a ubuntu 11.04 system with my own
hand-rolled 3.x kernel and i think there's a step in the python build
process that can't handle a running kernel with version "3.*".  this
is my suspicion as i've already found another location in the WRL
build that clearly never imagined it would be run on a 3.x kernel (it
recognized only "2.x" kernels as a hardcoded value.)

  another reason i think it's something like this is if i run just the
prep step -- that is, untar the python-2.6.2 tarball and apply the
WRL patches -- here's what i get in the resulting directory:

$ grep -r plat-linux2 *
Doc/install/index.rst:   ['', '/usr/local/lib/python2.3',
'/usr/local/lib/python2.3/plat-linux2',
Doc/install/index.rst:'/www/python/lib/pythonX.Y/plat-linux2', ...]``.
Misc/RPM/python-2.6.spec:%{__prefix}/%{libdirname}/python%{libvers}/plat-linux2
Misc/HISTORY:   * Lib/plat-sunos5/CDIO.py, Lib/plat-linux2/CDROM.py:
Misc/HISTORY:e.g. lib-tk, lib-stdwin, plat-win, plat-linux2,
plat-sunos5, dos-8x3.
$

  as you can see, it's all *hardcoded* references to "plat-linux2" so
it's a mystery as to where the references to "plat-linux3" are coming
from during the build process, which is why i suspect the reason i
gave above -- that nothing took into account that this build would be
done on a 3.x kernel.

  can anyone shed light on this?  can anyone else *try* this on a
system with a 3.x kernel and let me know what they get?  i'm about to
just hack the source and change that to "plat-linux3" to see what
happens, but it would be nice to do something more intelligent.
thanks.

rday

-- 


Robert P. J. Day Ottawa, Ontario, CANADA
http://crashcourse.ca

Twitter:   http://twitter.com/rpjday
LinkedIn:   http://ca.linkedin.com/in/rpjday

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


Re: PyWhich

2011-08-04 Thread Steven D'Aprano
Billy Mays wrote:

> Hey c.l.p.,
> 
> I wrote a little python script that finds the file that a python module
> came from.  Does anyone see anything wrong with this script?


Yes -- the most screamingly obvious question has to be, why are you writing
directly to sys.stdout instead of just using print?


> #!/usr/bin/python

I believe the recommended, platform independent hash-bang line is

#!/usr/bin/which python


> import sys
> if __name__ == '__main__':
>  if len(sys.argv) > 1:
>  try:
>  m = __import__(sys.argv[1])

The major risk here is whether or not you trust the module enough to import
it and run arbitrary code. The alternative would be a lot more work: you
would have to duplicate the logic of the import statement, search the
PYTHONPATH, look for packages, inside zip files, etc. 


>  sys.stdout.write(m.__file__ + '\n')

Built-in modules don't have a __file__ attribute. The most obvious example:

>>> import builtins  # spelled __builtin__ in Python 2.x
>>> builtins.__file__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute '__file__'

Also, __file__ is not always entirely honest. In Python 3, module.__file__
may report a .py file when it is actually loaded from a .pyc file, even if
the .py file doesn't exist. So if you care about the distinction
between .py, .pyc, .pyo etc. files, looking at __file__ alone will be
inadequate.



>  except ImportError:
>  sys.stderr.write("No such module '%s'\n" % sys.argv[1])

That's not a given -- it may be that the module exists, but importing fails
for some other reason. I would recommend not catching ImportError at all,
and just let the standard Python error handling print the traceback.
Especially for a tool aimed at programmers (who else would be interested in
PyWhich?), hiding useful diagnostic errors and replacing them with a
generic, and potentially wrong, message, is very bad.



-- 
Steven

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


Re: problem with bcd and a number

2011-08-04 Thread Dan Stromberg
It sounds like you have what you need, but here's an amusing way of dealing
with a BCD byte:

>>> print int(hex(0x72).replace('0x', ''))
72

On Thu, Aug 4, 2011 at 5:15 PM, shawn bright  wrote:

> Thanks for your help on this, gents. Got it working now.
> shawn
>
> On Thu, Aug 4, 2011 at 2:28 PM, Dave Angel  wrote:
>
>> nibbles from a byte
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: with statement and context managers

2011-08-04 Thread Steven D'Aprano
Thomas Rachel wrote:

> Am 03.08.2011 04:15 schrieb Steven D'Aprano:
[...]
>  > but to me that looks badly wrong. Surely the spam context manager
>  > object will exit after the first iteration, and always raise an
>  > exception on the second? But I don't quite understand context
>  > managers enough to be sure.
> 
> Depends on the implementation. As already stated, a
> contextlib.contextmanager will only run once. But it is easy to turn it
> into a persistent one - which internally initializes as often as needed.

Thanks, that's exactly the sort of information I was after.

Thank you to everyone who answered.


-- 
Steven

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


Re: PyWhich

2011-08-04 Thread Tim Chase

On 08/04/2011 07:34 PM, Steven D'Aprano wrote:

Billy Mays wrote:

#!/usr/bin/python


I believe the recommended, platform independent hash-bang line is

#!/usr/bin/which python


I think you mean

  #!/usr/bin/env python

-tkc



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


Re: error compiling python, and "plat-linux2" versus "plat-linux3"

2011-08-04 Thread Terry Reedy

There has been some discussion about what to do with 'linux3'.
See http://bugs.python.org/issue12326 for example.

--
Terry Jan Reedy

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


Re: Community Involvement

2011-08-04 Thread Steve Holden
Haven't had much Cc input so far, but this one is definitely worth following up 
on. Thanks!

regards
 Steve

On Aug 4, 2011, at 5:42 PM, Eric Snow wrote:

> On Wed, Aug 3, 2011 at 9:14 PM, Steve Holden  wrote:
>> [Ccs appreciated]
>> After some three years labor I (@holdenweb) at last find myself approaching
>> the completion of the Python Certificate Series with O'Reilly School of
>> Technology (@OReillySchool).
>> At OSCON last week the team fell to talking about the final assignment
>> (although the Certificate is not a certification, students only progress by
>> answering real quiz questions, not the usual multiple-choice task). Success
>> also requires that they complete a project at the end of each (of the ~60)
>> lesson(s).
>> We would ideally like the last project to to be something that demonstrates
>> at least some minimal involvement with the Python community. Something like
>> "get a Python answer upvoted on StackOverflow", for example, or getting a
>> question answered on c.l.p. At the same time it shouldn't be anything that
>> places a burden on the community (otherwise the hundredth student would be
>> abused and the thousandth murdered).
>> So I wondered if anyone had any good ideas.
> 
> While not as "community" as the mailing lists, perhaps they could post
> a recipe to the activestate.
> 
> -eric
> 
>> regards
>>  Steve
>> --
>> Steve Holden
>> st...@holdenweb.com
>> 
>> 
>> 
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> 

-- 
Steve Holden
st...@holdenweb.com



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


Re: PyWhich

2011-08-04 Thread Chris Angelico
On Fri, Aug 5, 2011 at 1:34 AM, Steven D'Aprano
 wrote:
> Especially for a tool aimed at programmers (who else would be interested in
> PyWhich?)

The use that first springs to my mind is debugging import paths etc.
If you have multiple pythons installed and aren't sure that they're
finding the right modules, you could fire up PyWhich on an innocuous
module like math or sys, and see if it's loading it from the right
path. People doing this might not necessarily be programmers, they
might be sysadmins; but you're right that it's most likely this will
be used by competent Python programmers.

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


JSON Strict Mode

2011-08-04 Thread John Riselvato
I am working on a license verification script. I am rather new to the
concept and to JSON files in general.

This is what my pseudocode looks like:

licenses = meta['license']
> for x in licenses:
> if licenses[x]['terms'] is not valid opensource license
> if in strict mode
> raise nonfree exception
>
> How would i go about checking if its in "strick mode" and what does "raise
nonfree exception" mean?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JSON Strict Mode

2011-08-04 Thread Chris Rebert
On Thu, Aug 4, 2011 at 8:25 PM, John Riselvato  wrote:
> I am working on a license verification script. I am rather new to the
> concept and to JSON files in general.

Based on your questions, reading a programming tutorial might be a
good idea. Here's one that uses Python and that I've heard praise for:
http://openbookproject.net/thinkcs/python/english3e/
The official tutorial is also worth reading:
http://docs.python.org/dev/tutorial/

Once you understand Python's basic datatypes, JSON is a breeze; they
are extremely similar.

> This is what my pseudocode looks like:
>>
>> licenses = meta['license']
>> for x in licenses:
>> if licenses[x]['terms'] is not valid opensource license

I would probably instead write that as:

for license_name, license in licenses.items():
if not is_open_source(license['terms']):
# rest same as before

>> if in strict mode
>> raise nonfree exception
>
> How would i go about checking if its in "strict mode"

You would have a boolean* variable somewhere indicating whether or not
the program is in strict mode. Its value would presumably be set based
on user input, or a configuration file, or whatever is applicable to
your program; e.g.:
strict = True
strict = False

config = parse_configuration_file()
if config.strict:
# whatever

> and what does "raise nonfree exception" mean?

I regret that the Wikipedia article on the topic of exceptions isn't
too approachable. So, I'll instead refer you to the relevant section
of the Python tutorial:
http://docs.python.org/dev/tutorial/errors.html#errors-and-exceptions

(Disclaimer: The following is oversimplified and somewhat Python-specific.)
In a nutshell, an exception is type of object** used to indicate that
a program has encountered an error; it contains details about the
error and its cause.
When a program encounters an error, it stores information about the
error into a new exception object and then "raises" (using, in Python,
the "raise" statement) this object so that the program can properly
react to the error. By virtue of the "raise", normal execution of the
program stops, and control is transferred to another part of the
program which previously registered itself as being capable of
handling the kind of error in question. The code in that part of the
program then examines the exception object that was raised and takes
appropriate action to deal with the error. If no part of the program
registered itself as capable of handling the kind of error in
question, a detailed error message is output and the program exits.

In your specific example, the non-pseudo-code would look something like:

# a declaration somewhere:
class NonFreeLicenseError(ValueError):
"""License is not free according to the Open Source Definition."""

# ... back in the part of your code corresponding to your pseudocode:
if strict:
raise NonFreeLicenseError("The '%s' license is nonfree and thus
impermissible." % x)

As written, I have NonFreeLicenseError as a kind of ValueError. This
may or may not be appropriate depending on your program; a list of
built-in types of exceptions can be found at
http://docs.python.org/dev/library/exceptions.html#bltin-exceptions

Cheers,
Chris
--
http://rebertia.com

* http://en.wikipedia.org/wiki/Boolean_data_type
** http://en.wikipedia.org/wiki/Object_%28computer_science%29
-- 
http://mail.python.org/mailman/listinfo/python-list