Announcing: python-ghostscript 0.3

2010-08-12 Thread Hartmut Goebel
Announcing:

python-ghostscript 0.3

A Python-Interface to the Ghostscript
 C-API using ctypes

:Copyright: GNU Public License v3 (GPLv3)
:Author:  Hartmut Goebel h.goe...@crazy-compiler.com
:Homepage: http://bitbucket.org/htgoebel/python-ghostscript
:Download: http://pypi.python.org/pypi/ghostscript

`Ghostscript`__, is a well known interpreter for the PostScript
language and for PDF. This package implements a interface to the
Ghostscript C-API using `ctypes`__. Both a low-level and a pythonic,
high-level interface are provided.

__ http://www.ghostscript.com/
__ http://docs.python.org/library/ctypes.html

This package is currently tested only under GNU/Linux. Please report
whether it works in your environment, too. Thanks.


Latest Changes


:0.3 (2010-08-12):

  * Added support for win32: The DLL to load is searched in registry.

  * On other platforms: Be more inteligent about finding Ghostscript
shared object file (fall back to ctypes.util.find_library() if
`libgs.8.so` can not be loaded

  * Better error messages if lib/dll is not found.

  * Removed relative imports, so older versions of Python can be used.

  * Added nice project logo

:0.2 (2010-08-06):

  * Fixed several bugs, esp. for running strings by Ghostscript.


Example


Here is an example for how to use the high-level interface of
`python-ghostscript`. This implements a very basic ps2pdf-tool::

  import sys
  import ghostscript

  args = [
  ps2pdf, # actual value doesn't matter
  -dNOPAUSE, -dBATCH, -dSAFER,
  -sDEVICE=pdfwrite,
  -sOutputFile= + sys.argv[1],
  -c, .setpdfwrite,
  -f,  sys.argv[2]
  ]

  ghostscript.Ghostscript(*args)

-- 
Regards
Hartmut Goebel

| Hartmut Goebel  | h.goe...@crazy-compilers.com   |
| www.crazy-compilers.com | compilers which you thought are impossible |
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: urllib2 does not implement with Python 2.6

2010-08-12 Thread Paul Rubin
John Nagle na...@animats.com writes:
 AttributeError: addinfourl instance has no attribute '__exit__'.

 I thought that all the file-like objects supported with in 2.6.
 No?

I guess not.  Use contextlib.closing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Beyond the moratorium

2010-08-12 Thread Vito 'ZeD' De Tullio
Hi all.

I know, maybe I'm just lazily speculating, but I'm curious about what's 
next, in python, when GvR will stop the moratorium and will let changes in 
the language.

I don't know what to expect... some syntax sugar about concurrent 
programming? static types? an erlang-style bang (!) process message 
passing?

-- 
By ZeD

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


Why can't I set sys.ps1 to a unicode string?

2010-08-12 Thread RG
More precisely, why does sys.ps1 not appear if I set it to a unicode 
string?  This problem is hard for me to describe here because my 
newsreader is not properly unicode enabled, but here's the gist of it:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type help, copyright, credits or license for more information.
 

First, let's make sure our encodings are set properly:

 import sys
 sys.stdin.encoding
'utf-8'
 sys.stdout.encoding
'utf-8'

Looks good.  Now, let's make two unicode strings, identical except for 
one character:

 s1 = u'%%% %%% '
 s2 = u'%%% ' + u'\u262f' + '%%% '
 print s1
%%% %%% 
 print s2
%%% /%%% 

If this were a properly unicode-enabled newsreader you would see a 
yin-yang symbol in the middle of s2.

Now the weird part:

 sys.ps1 = s1
%%% %%% sys.ps1 = s2   # This is as expected
print s1   # But this isn't.  There's no prompt!
%%% %%%# Everything still works
print s2
%%% /%%% 
sys.ps1 = s1   # If we reset sys.ps1 we get our prompt back
%%% %%% sys.ps1 = ' '
 sys.ps1 = u' '
 

So... why does having a non-ascii character in sys.ps1 make the prompt 
vanish?

(If you're wondering why I care, I want to connect to an interactive 
python interpreter from another program, and I want a non-ascii 
delimiter to unambiguously mark the end of the interpreter's output on 
every interaction.)

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


Re: python ide for ubuntu

2010-08-12 Thread Werner Thie
Eclipse with pydev (great debugging) does the trick nicely, free of 
charge and throws in some other goodies (JScript/HTML/XML editing) too.


I use the EE for Java developer version

http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr

Install pydev from Menu Help/Software Updates

After ten years of Python coding and suffering thru most of the 
commercial products like VisualPython, Komodo, Wings, asf I heartily 
recommend Eclipse nowadays.


If you want to stay as pythonesque as possible you could go with SPE 
which uses wxPython and integrates with Blender, although this project 
seems to be stalled.


Werner

On 12.08.2010 04:15, Bhanu Kumar wrote:

Hi All,

Is there any good free python IDE available in Ubuntu?


thanks,
-Bhanu

attachment: werner.vcf-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-12 Thread Ulrich Eckhardt
sturlamolden wrote:
 On 11 Aug, 08:40, Ulrich Eckhardt eckha...@satorlaser.com wrote:
 Header (definition) and source (implementation) is not the same. 

I'm aware of this and that's not the thing I was talking about.

Uli

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

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


Re: Beyond the moratorium

2010-08-12 Thread Stefan Behnel

Vito 'ZeD' De Tullio, 12.08.2010 08:49:

I know, maybe I'm just lazily speculating, but I'm curious about what's
next, in python, when GvR will stop the moratorium and will let changes in
the language.

I don't know what to expect... some syntax sugar about concurrent
programming? static types? an erlang-style bang (!) process message
passing?


One of the reasons the moratorium was established was to reduce the time 
spent in overly speculative discussions about various features that will 
most likely not end up in the language anyway. Also note that your examples 
above span both the language and the stdlib, which are put under different 
constraints by the moratorium.


Stefan

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


Re: Beyond the moratorium

2010-08-12 Thread Ben Finney
Vito 'ZeD' De Tullio zak.mc.kra...@libero.it writes:

 I know, maybe I'm just lazily speculating, but I'm curious about
 what's next, in python, when GvR will stop the moratorium and will let
 changes in the language.

Subscribe to the ‘python-ideas’ forum for the latest pie-in-the-sky
discussions about how to change Python, including the occasional
contribution from GvR on ideas that take his interest.

-- 
 \  “In the long run, the utility of all non-Free software |
  `\  approaches zero. All non-Free software is a dead end.” —Mark |
_o__)Pilgrim, 2006 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't I set sys.ps1 to a unicode string?

2010-08-12 Thread Martin v. Loewis
 So... why does having a non-ascii character in sys.ps1 make the prompt 
 vanish?

I can't pinpoint it to a specific line of code. Most likely, it tries
to encode the prompt as ASCII before writing it to stdout. That fails,
and it silently ignores the error.

FWIW, this is fixed in Python 3.

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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread News123
Hi Steven,

On 08/12/2010 01:37 AM, Steven D'Aprano wrote:
 On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote:
 
 level: beginner

 exercise: given that packs of McNuggets can only be bought in 6, 9 or 20
 packs, write an exhaustive search to find the largest number of
 McNuggets that cannot be bought in exact quantity.
 
 Is this a trick question?
 
 I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) 
 McNuggets. And that's not even close to the largest number that you can't 
 buy.

You CAN buy that many Nuggets.

You just need the money and of course you have to wait a little until
they are ready.

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


Re: how to save a whole web page with something block

2010-08-12 Thread Lawrence D'Oliveiro
In message mailman.1921.1281452652.1673.python-l...@python.org, Daniel 
Fetchinson wrote:

 A web server may present different output depending on the client
 used.

It may also require execution of some JavaScript to insert HTML content.

 So you might want to make urllib appear as a browser by sending the
 appropriate headers.

If the above is the case, then this won’t be enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread MRAB

Steven D'Aprano wrote:

On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote:


level: beginner

exercise: given that packs of McNuggets can only be bought in 6, 9 or 20
packs, write an exhaustive search to find the largest number of
McNuggets that cannot be bought in exact quantity.


Is this a trick question?

I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) 
McNuggets. And that's not even close to the largest number that you can't 
buy.



If you'd looked at the link then you would've seen that it's
mathematically possible.

But then I expect you have a life! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: python ide for ubuntu

2010-08-12 Thread geremy condra
On Wed, Aug 11, 2010 at 11:53 PM, Werner Thie wer...@thieprojects.ch wrote:
 Eclipse with pydev (great debugging) does the trick nicely, free of charge
 and throws in some other goodies (JScript/HTML/XML editing) too.

 I use the EE for Java developer version

 http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliosr

 Install pydev from Menu Help/Software Updates

 After ten years of Python coding and suffering thru most of the commercial
 products like VisualPython, Komodo, Wings, asf I heartily recommend Eclipse
 nowadays.

 If you want to stay as pythonesque as possible you could go with SPE which
 uses wxPython and integrates with Blender, although this project seems to be
 stalled.

 Werner

Or you could use a text editor and a terminal and spare yourself the
agony of dealing with 600MB of Java of questionable quality ;).

And don't even get me started about all the unsigned OSGi bundles that
float around in there.

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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread News123
On 08/11/2010 10:14 PM, Baba wrote:
 level: beginner
 
 exercise: given that packs of McNuggets can only be bought in 6, 9 or
 20 packs, write an exhaustive search to find the largest number of
 McNuggets that cannot be bought in exact quantity.
 
 exercise source:
 http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf
 
 please help me write this code
 
 i believe it's something along the lines of this:
 
 c=0
 sol=[]
 for n in range (0,10):
  for a in range (0,10):
   for b in range (0,10):
for c in range (0,10):
 sol=6*a+9*b+20*c
 if sol!=n:
  c+=1
 if c==6:
  print sol
 

If you're interested in more, than just finishing the exercise, then you
should post your solution even if you have it already and read about all
the tips how to make it faster or shorter or more readable
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Tkinter Simple Qn

2010-08-12 Thread Eric Brunel
In article 
ecd3ebca-8192-445a-a60c-c688b18f4...@i4g2000prf.googlegroups.com,
 ChrisChia chrischi...@gmail.com wrote:

 Hi i have the following problem with Python Tkinter.
 I switch to switch the image background (which i used Tkinter.Label
 with image arg to display on the GUI).
 
 How can I do that? the callback function which i have created doesn't
 seem to work...

It is usually way better to post the actual error than just saying 
doesn't seem to workŠ Here your problem is quite clear, but in most 
circumstances, it would be quite difficult to figure out what's 
happening.

 some advice?
 
 below is my code:
 
 
 import Tkinter as tk
 from PIL import Image, ImageTk
 
 root = tk.Tk()
 
 # having problem with switching the image
 def callback(event):
 global root
 root.panel1.pack_forget()
 root.panel1.image = image2

The variable image2 is not known in this context, so no wonder the 
callback doesn't work. Let me guess: it says something like NameError: 
name 'image2' is not defined?

 root.panel1.pack()
 
 
 def app():
 
 root.title('FIT 2022 Assignment 1')
 
 # pick an image file you have .bmp .jpg .gif. .png
 # load the file and covert it to a Tkinter image object
 imageFile = c:\\test1.jpg
 image1 = ImageTk.PhotoImage(Image.open(imageFile))
 imageFile2 = c:\\test2.jpg
 image2 = ImageTk.PhotoImage(Image.open(imageFile2))

Here, you create image2 as a local variable in function app. So the 
variable name will not be known outside of app. If you want it to be 
global, you have to add a line:
global image2
at the beginning of your app function. Then it should work correctly.

By the way, I usually find it better to organize a GUI into classes 
rather than using functions. This way, you could store the images in 
object attributes and define your callback as a method, and not as a 
function.

 # get the image size
 w = image1.width()
 h = image1.height()
 
 
 # position coordinates of root 'upper left corner'
 x = 0
 y = 0
 
 
 # make the root window the size of the image
 root.geometry(%dx%d+%d+%d % (w, h, x, y))
 
 
 # root has no image argument, so use a label as a panel
 panel1 = tk.Label(root, image=image1)
 panel1.pack(side='top', fill='both', expand='yes')
 panel1.image = image1
 panel1.bind(Button-1, callback)
 
 
 panel1.pack()
 root.mainloop()
 
 
 app()

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


Re: most popular gui framework for python

2010-08-12 Thread meitham
On Aug 11, 8:31 pm, Back9 backgoo...@gmail.com wrote:
 Hi,

 Does anyone know of what is the most popular gui framework for python
 application?

 TIA

I used to prefer using GTK mainly because it is available on most
platforms. I have realised the majority of the enterprises prefer to
use browsers even for local applications. So a combination of django/
html/css/jquery/ajax now gives me the best gui I could get. This
approach also forces me to separate logic from presentation, and the
gui will be truly platform independent which could run on any device
with a browser.

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


Does anyone use Quixote for web developing?

2010-08-12 Thread ph4nut
Hi all,I am learning Quixote a few days ago,,,and i have no idea about
whether there is any Google Group talking about Quixote,so i post this
post to check that is Quixote been talking in this group before or can
i ask question about Quixote here!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Jean-Michel Pichavant

Baba wrote:

level: beginner

exercise: given that packs of McNuggets can only be bought in 6, 9 or
20 packs, write an exhaustive search to find the largest number of
McNuggets that cannot be bought in exact quantity.

exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf

please help me write this code

i believe it's something along the lines of this:

c=0
sol=[]
for n in range (0,10):
 for a in range (0,10):
  for b in range (0,10):
   for c in range (0,10):
sol=6*a+9*b+20*c
if sol!=n:
 c+=1
if c==6:
 print sol


  

for mcNugget in range(0,10):
   sendTo(trashbin)

You're welcome :p

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Paul Rubin
Baba raoul...@gmail.com writes:
 exercise: given that packs of McNuggets can only be bought in 6, 9 or
 20 packs, write an exhaustive search to find the largest number of
 McNuggets that cannot be bought in exact quantity.

Is that a homework problem?  Hint: first convince yourself that a
largest number actually exists.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone use Quixote for web developing?

2010-08-12 Thread Bruno Desthuilliers

ph4nut a écrit :

Hi all,I am learning Quixote a few days ago,,,and i have no idea about
whether there is any Google Group talking about Quixote,so i post this
post to check that is Quixote been talking in this group before or can
i ask question about Quixote here!


From the project's home page:


There is a mailing list for discussing Quixote and you should look there 
for information about obtaining the current release:


* quixote-users



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


Re: python ide for ubuntu

2010-08-12 Thread Bruno Desthuilliers

geremy condra a écrit :

(about eclipse+pydev)


Or you could use a text editor and a terminal and spare yourself the
agony of dealing with 600MB of Java of questionable quality ;).


+1 QOTW

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


Re: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT)

2010-08-12 Thread Alexander Gattin
Hello,

On Wed, Aug 11, 2010 at 02:29:24PM -0700, tormod wrote:
 I've tried countless times to build  install cx_Oracle on Python
 3.1.2, and failed every time, so I'd like to ask someone for help.
...
 I've opened the cx_Oracle.pyd with Dependency Walker (http://
 www.dependencywalker.com/) and DW reports it can't find: OCI.DLL,
 PYTHON31.DLL, MSVCR90.DLL (why?)

Does Windows have anything like
LD_LIBRARY_PATH/SHLIB_PATH?

 Appreciate any help, even wildshots and 2 cents are welcome - I'll try
 everything.

please try starting python -d (--debug IIRC)
and then loading cx_Oracle manually
( import cx_Oracle).

Usually it succeeds (sic!) but outputs a lot
of symbol errors. // Problem with Oracle libs

-- 
With best regards,
xrgtn (+380501102966/+380636177128/xr...@jabber.kiev.ua)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python ide for ubuntu

2010-08-12 Thread Roald de Vries

Hi Bhanu,

On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote:

Hi All,

Is there any good free python IDE available in Ubuntu?


See a similar discussion at django-users mailing list:
http://groups.google.com/group/django-users/browse_thread/thread/562189578285211

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Roald de Vries

On Aug 12, 2010, at 11:33 AM, Paul Rubin wrote:

Baba raoul...@gmail.com writes:

exercise: given that packs of McNuggets can only be bought in 6, 9 or
20 packs, write an exhaustive search to find the largest number of
McNuggets that cannot be bought in exact quantity.


Is that a homework problem?  Hint: first convince yourself that a
largest number actually exists.


Good point. There is actually an upper bound. Let's take 6 packs of  
20, that's 120 nuggets.
Now 121 nuggets can be reached by substituting 1 pack of 20 with 2  
packs of 6 and 1 pack of 9.

122 = 4*20 + 2*(2*6+9)
123 = 3*20 + 3*(2*6+9)
...
126 = 6*20 + 6
127 = 121 + 6 = 5*20 + (2*6 + 9) + 6
... etcetera.

Now you have to find the largest number below 120, which you can  
easily do with brute force (untested):


can_be_bought = [False for i in range(120)]
for twenties in range(6):
for nines in range(14):
for sixes in range(20):
can_be_bought[twenties*20+nines*9+sixes*6] = True
for i in reverse(range(120)):
if not can_be_bought[i]: return i

Cheers, Roald


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


Programming Puzzles? What's your favorite puzzle?

2010-08-12 Thread Matty Sarro
Hey All!
Hope your thursday is treating you well. I'm looking for suggestions on
books of programming/engineering puzzles that range from beginners to
advanced and even expert level problems. I know they exist; we had them back
in college for practicing before the ACM programming competitions. However I
can't seem to really find any books out there that look like they're what
I'm seeking. Basically I haven't programmed a lot since I was in college,
and that was about 9 years ago. I'm expected to do a bit more programming at
my current job and I figure the best way to get back into things is to have
some practical things to solve, and maybe have a bit of fun in the process.

Anyone have any suggestions?

Also, if you have any favorite puzzles/simple learning programs to suggest,
please, share with the class :)

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


Copying a file with a question mark in it's name in Windows

2010-08-12 Thread drodrig
A python script I use to backup files on a Windows 2003 server
occasionally fails to retrieve the size of a file with a question mark
in the name. The exception I get is OSError #123 The filename,
directory name, or volume label syntax is incorrect. I realize that
technically a question mark in the name of a file on Windows is
illegal, but nevertheless these files exist on the file system. It
seems that they are created by Office 2007 Word, for the most part.

The line that fails is:

os.path.getsize(source)

Where source is the full path to the file with the question mark in
it's name.

Any idea how to retrieve the file's size? Also, I imagine that after I
overcome this hurdle, I'll need help finding a way to copy the file
(assuming copy2() doesn't work). I've tried escaping the question mark
(\\?). Same result.

Although I could use the Windows dir command, parsing the results to
find the size of the file then use the Windows copy command, I'd
rather stay away from this type of solution.

Any help is appreciated!

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


Long rant about Python in Education

2010-08-12 Thread ???????
This is in response to one of the pyWiki pages:
PythonAsAFirstLanguage.

If there's a better place I could have posted this, please tell me
about it. I will be posting this elsewhere over the next few ideas,
because I feel it's my duty to spread this idea.

It's not grandiose, just Quixotic.

Someone wrote,

We could really use some success stories of Python in education.

Right... Python was developed to be easily learnt by children. So
that's not a declarative sentence. It's an implied question.

Here's my answer. It took a while to write, but it's quite simple.

Problem: Python won't be easily learnt by my stepchild, I know for a
fact.

She loves her laptop, but she calls me a nerd whenever Linux gets
brought up at the dinner table.

I'm not bitter about this.

But I want you guys, especially the ones who are planning on having
kids, as well as the ones who already have them, to understand what
steps you can take to teach your kids Python.

I've basically outlined an 'algorithm' for it here. If you don't have
time to read a long, eccentric, rambling post, just 'read the lead'

Solution to problem:

1) Only let them see you using the terminal. Don't even use Windows in
the house.
2) Their first laptop should be installed with a nice, well-supported
Linux distro.
3) Brush up on your Linux skills yourself.

The bottom line: teach them to do beautiful things with the terminal.

I believe Linux should be mastered by everyone who uses it.

And I believe Linux (not Python) is the way to teach children to
program. Especially intuitive ones. (In the Myers-Briggs scale.)

Why is this important?

Because the part of the world that most hates America right now is
full of intuitives. And if we want not to be blown off the face of the
earth in a few decades, we have to empower them in a very new way: we
have to teach them to enjoy programming, enjoy computers, and develop
their minds in a way that doesn't involve becoming 'Imams' who are
essentially the learned mafia bosses of terrorism.

I have mastered Classical Arabic. I once met a Pakistani and told him
I had done so. We were in the middle of a theological debate. In the
middle of his Islamic theology was, laughably enough, some Christian
theology that I have no idea how it got there. Orthodox Islam has no
concept of original sin, but he believed in it. That was a real
surprise for me.

Anyway, despite the fact that he'd only read translations of the
Qur'an, whereas I'd read the original, he was not impressed.

He said that Pakistan had many 'schools' for studying Arabic, and that
there was an incredible number of 'students' there.

These people aren't dumb, guys. They're just learning the wrong stuff.

We can't change the schools, but we don't need to.

Don't forget that Arabs and Central Asians both had education systems
based on Islam before western education came with the French and
British. The attempt to re-establish the primacy of that system of
education is what Islamic terrorism is all about.

It was based on memorizing/hearing the Qur'an, yes, then learning the
meanings of the words by reading it.

Actually, for an intuitive person, this is an excellent way to learn
any language (find a text, find a recording, memorize the recording,
intuit the meanings) and I have used it to learn Spanish, Chinese, and
Arabic.

How does this apply to Linux/Python?

Having access to the /usr/bin directory means having access to a whole
load of algorithms without even having to write them yourself!

Hasn't anyone but me thought of how great that would be for kids?

So, when you guys ban windows in the home and start breastfeeding your
kids terminals (I was using a DOS terminal correctly at age 9,
shouldn't be hard to teach them whippersnappers to use a -nix shell),
then you can bring in Python. But first, start writing Python to put
in their /usr/bin directories, so that they get comfortable with the
idea that Python can be both scripted and compiled, and that programs
are simply algorithms that get called using arguments.

Then teach them to write Python stuff they can put into /usr/bin

Important: ban windows entirely in the home. I cannot stress this
enough.

My stepdaughter is as good with computers as I was at her age, and
I've seen her play around with the settings on her laptop when she's
bored. Obviously, she wants to explore the machine sometimes, but
windows has trained her mind not to look for geeky solutions.

Windows has trained her to think of a computer as a magic machine, and
not as an algorithm machine.

Will the real Bill Gates please stand up.

When I was her 10, my stepfather banned me from playing DOOM unless I
could get it to work using the DOS command line.

I did not manage to replace the .dll file he had deleted, but I did
learn lots.

Will the real Bill Gates please stand up, please stand up, please
stand up...

So, in conclusion:

DO people of the free-thinking world want a Mozart Python genius to
show off to the schools in Europe, Japan, 

Re: Copying a file with a question mark in it's name in Windows

2010-08-12 Thread Tim Golden

On 12/08/2010 12:49, drodrig wrote:

A python script I use to backup files on a Windows 2003 server
occasionally fails to retrieve the size of a file with a question mark
in the name. The exception I get is OSError #123 The filename,
directory name, or volume label syntax is incorrect. I realize that
technically a question mark in the name of a file on Windows is
illegal, but nevertheless these files exist on the file system. It
seems that they are created by Office 2007 Word, for the most part.


Could you show us the script you're using? I'm not aware of any
way to get a question mark into a file name; even using the
file namespace prefix \\?\ doesn't allow it as far as I can tell.

Where are you seeing the question mark? Is it possible it's a
placeholder for an unprintable character rather than an actual
question mark?

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


Re: Beyond the moratorium

2010-08-12 Thread John Roth
On Aug 12, 1:22 am, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Vito 'ZeD' De Tullio zak.mc.kra...@libero.it writes:

  I know, maybe I'm just lazily speculating, but I'm curious about
  what's next, in python, when GvR will stop the moratorium and will let
  changes in the language.

 Subscribe to the ‘python-ideas’ forum for the latest pie-in-the-sky
 discussions about how to change Python, including the occasional
 contribution from GvR on ideas that take his interest.

 --
  \              “In the long run, the utility of all non-Free software |
   `\      approaches zero. All non-Free software is a dead end.” —Mark |
 _o__)                                                    Pilgrim, 2006 |
 Ben Finney

You might also want to look at PEP 3152, which was just posted.

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


Secure LDAP Configuration

2010-08-12 Thread sajuptpm
I want to create an LDAP database for my company with following
settings.

Only the ldap user belongs to my company can search and view ldap
entries
I want to protect ldap user belongs to my company
One ldap user can't search and view others details
Only allow ldap users to authenticate with there username and
password
I need an LDAP administrator for my company.Only he can add and
delete users from LDAP.

For these how configure /etc/openldap/slapd.conf



I need to add group and role infornations to ldap directory.Can i use
existing attributes like 'ou' for these or need to add new attribute.


Here is the LDAP entry i configured.

dn: uid=user6,dc=localhost,dc=localdomain
objectclass: top
objectclass: person
objectclass: inetorgperson
ou: [('userGroup111','userr'),('adminGroup','admin'),
('Server111','operator')]
cn: user6
sn: My company
uid: user6
userPassword: 123456


ou: [('userGroup111','userr'),('adminGroup','admin'),
('Server111','operator')] -newly added group and role pair.Is it
correct way

Have any other way to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Renaming OS files by file type in python

2010-08-12 Thread blur959
Hi all, I am creating a program that renames all files of the similar
file type. But i am stuck at this part. I tried running this code and
I got this error:new_name = os.rename(path, newpath)
WindowsError: [Error 183] Cannot create a file when that file already
exists. Hope you guys could help.



import os

directory = raw_input(Please input file directory. \n\n)

s = raw_input(Please input a name to replace. \n\n)
ext = raw_input(input file ext)

for filename in listdir(directory):
if ext in filename:
path = join(directory, filename)
fnpart = os.path.splitext(filename)[0]
replace_name = filename.replace(fnpart, s)
newpath = os.path.join(directory, replace_name)

new_name = os.rename(path, newpath)
print new_name

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


Re: Copying a file with a question mark in it's name in Windows

2010-08-12 Thread Aleksey
On 12 авг, 18:49, drodrig drod...@magicbrain.com wrote:
 A python script I use to backup files on a Windows 2003 server
 occasionally fails to retrieve the size of a file with a question mark
 in the name. The exception I get is OSError #123 The filename,
 directory name, or volume label syntax is incorrect. I realize that
 technically a question mark in the name of a file on Windows is
 illegal, but nevertheless these files exist on the file system. It
 seems that they are created by Office 2007 Word, for the most part.


If ? is a placeholder for an unprintable character you can try view
real file name in IDLE:

  import glob
  print glob.glob(u'e:/full/path/to/file?')

In path to file you must instead question use wild ?.
Will be printed all like files.

-
Under Windows I too have similar problem: windows sometimes (from any
programs - e.g. Firefox) save files with wrong names, but later
do not manipulate with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Dave Angel



Roald de Vries wrote:
div class=moz-text-flowed style=font-family: -moz-fixedOn Aug 
12, 2010, at 11:33 AM, Paul Rubin wrote:

Baba raoul...@gmail.com writes:

exercise: given that packs of McNuggets can only be bought in 6, 9 or
20 packs, write an exhaustive search to find the largest number of
McNuggets that cannot be bought in exact quantity.


Is that a homework problem?  Hint: first convince yourself that a
largest number actually exists.


Good point. There is actually an upper bound. Let's take 6 packs of 
20, that's 120 nuggets.
Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 
packs of 6 and 1 pack of 9.

122 = 4*20 + 2*(2*6+9)
123 = 3*20 + 3*(2*6+9)
...
126 = 6*20 + 6
127 = 121 + 6 = 5*20 + (2*6 + 9) + 6
... etcetera.

Now you have to find the largest number below 120, which you can 
easily do with brute force (untested):


can_be_bought = [False for i in range(120)]
for twenties in range(6):
for nines in range(14):
for sixes in range(20):
can_be_bought[twenties*20+nines*9+sixes*6] = True
for i in reverse(range(120)):
if not can_be_bought[i]: return i

Cheers, Roald


for i in reverse(range(120)):
   if not can_be_bought[i]: return i

can probably be replaced by (untested):

return len(can_be_bought) - reverse(can_be_bought).index(False) - 1

DaveA

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


Re: Programming Puzzles? What's your favorite puzzle?

2010-08-12 Thread Dave Angel

Matty Sarro wrote:

Hey All!
Hope your thursday is treating you well. I'm looking for suggestions on
books of programming/engineering puzzles that range from beginners to
advanced and even expert level problems. I know they exist; we had them back
in college for practicing before the ACM programming competitions. However I
can't seem to really find any books out there that look like they're what
I'm seeking. Basically I haven't programmed a lot since I was in college,
and that was about 9 years ago. I'm expected to do a bit more programming at
my current job and I figure the best way to get back into things is to have
some practical things to solve, and maybe have a bit of fun in the process.

Anyone have any suggestions?

Also, if you have any favorite puzzles/simple learning programs to suggest,
please, share with the class :)

-Matty

  

For puzzles:

http://projecteuler.net
http://www.pythonchallenge.com

And you might get some ideas from:

http://wiki.python.org/moin/CodingProjectIdeas


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


Re: Long rant about Python in Education

2010-08-12 Thread D'Arcy J.M. Cain
On Thu, 12 Aug 2010 05:05:55 -0700 (PDT)
เข้านอน iktomus.heyo...@gmail.com wrote:
 have to teach them to enjoy programming, enjoy computers, and develop
 their minds in a way that doesn't involve becoming 'Imams' who are
 essentially the learned mafia bosses of terrorism.

This is the point that I stopped reading your message and added you
to my blacklist.  Goodbye.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does Python get the value for sys.stdin.encoding?

2010-08-12 Thread Anssi Saari
Benjamin Kaplan benjamin.kap...@case.edu writes:

 Sys.stdin and stdout are files, just like any other. There's nothing
 special about them at compile time. When the interpreter starts, it
 checks to see if they are ttys. If they are, then it tries to figure
 out the terminal's encoding based on the environment.

Just a related question, is looking at sys.stdin.encoding the proper
way of doing things? I've been working on a script to display some
email headers, some of which are encoded in MIME to various charsets.

Until now I have used whatever locale.getdefaultlocale() returns as
the target encoding, since it seemed to work. Although on one
computer the call returns ISO-8859-15 even though I don't quite
understand why.
-- 
http://mail.python.org/mailman/listinfo/python-list


__class__ of what

2010-08-12 Thread Eric J. Van der Velden
Hello,

I have,

class C:
n=0
def __init__(s):
__class__.n+=1


I do
 C()

This is fine. But of what thing I am taking the __class__ of?
I can also do

@staticmethod
def p():
print(__class__.n)

 C.p()
1

Thanks,

Eric J.



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


Re: Programming Puzzles? What's your favorite puzzle?

2010-08-12 Thread Neil Cerutti
On 2010-08-12, Dave Angel da...@ieee.org wrote:
 For puzzles:

 http://projecteuler.net

...if you like math problems.

 http://www.pythonchallenge.com

...if you like fooling around with PIL, graphics and bytes.

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


Using elementtree to Create HTML Form / Set selected

2010-08-12 Thread Doug
I'm using elementtree to create a form.

I would like to set the selected attribute.

Setting using the usual
 option.set( selected =  )
gives me
  option selected= value=operationsOperations/option
how does one make
  option selected value=operationsOperations/option
which is what I need.

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


Re: Does anyone use Quixote for web developing?

2010-08-12 Thread ph4nut
On Aug 12, 5:40 pm, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:
 ph4nut a écrit :

  Hi all,I am learning Quixote a few days ago,,,and i have no idea about
  whether there is any Google Group talking about Quixote,so i post this
  post to check that is Quixote been talking in this group before or can
  i ask question about Quixote here!

  From the project's home page:

 
 There is a mailing list for discussing Quixote and you should look there
 for information about obtaining the current release:

      * quixote-users
 

Thanks,I will have a check!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone use Quixote for web developing?

2010-08-12 Thread ph4nut
On Aug 12, 5:40 pm, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:
 ph4nut a écrit :

  Hi all,I am learning Quixote a few days ago,,,and i have no idea about
  whether there is any Google Group talking about Quixote,so i post this
  post to check that is Quixote been talking in this group before or can
  i ask question about Quixote here!

  From the project's home page:

 
 There is a mailing list for discussing Quixote and you should look there
 for information about obtaining the current release:

      * quixote-users
 

Thanks,I will have a check!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __class__ of what

2010-08-12 Thread Jean-Michel Pichavant

Eric J. Van der Velden wrote:

Hello,

I have,

class C:
n=0
def __init__(s):
__class__.n+=1

  


Should be

class C:
   n = 0
   def __init__(self):
  self.__class__.n+=1
  C.n+=1 # equivalent to this line (I prefer this one, more 
readable, less refactor-friendly)


 @classmethod
 def p(cls):
   print(cls.n)

JM


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


Re: __class__ of what

2010-08-12 Thread Eric Brunel
In article 
72151646-65cb-47bb-bd55-e7eb67577...@z10g2000yqb.googlegroups.com,
 Eric J. Van der Velden ericjvandervel...@gmail.com wrote:

 Hello,
 
 I have,
 
 class C:
 n=0
 def __init__(s):
 __class__.n+=1
 
 
 I do
  C()
 
 This is fine.

No it's not, at least in Python 2.x:
 C()
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 4, in __init__
NameError: global name '__class__' is not defined

 But of what thing I am taking the __class__ of?

Nothing, precisely. You should write s.__class__ (and replace s by self 
while you're at it).

 I can also do
 
 @staticmethod
 def p():
 print(__class__.n)
 
  C.p()
 1

No you can't, again in Python 2.x:
 C.p()
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 4, in p
NameError: global name '__class__' is not defined

Unless I'm missing something or something fundamental changed in Python 
3, your examples do not workŠ

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


Re: __class__ of what

2010-08-12 Thread Peter Otten
Eric J. Van der Velden wrote:

 I have,
 
 class C:
 n=0
 def __init__(s):
 __class__.n+=1
 
 
 I do
 C()
 
 This is fine. But of what thing I am taking the __class__ of?
 I can also do
 
 @staticmethod
 def p():
 print(__class__.n)
 
 C.p()
 1

I had no idea that this existed. __class__ was probably added to make 
super() calls without an explicit class argument possible in Python 3. It is 
made available as a closure:

 class A:
... def f(self): __class__
... def g(self): pass
...
 A.f.__closure__[0].cell_contents
class '__main__.A'
 A.g.__closure__ is None
True

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


Re: Using elementtree to Create HTML Form / Set selected

2010-08-12 Thread Peter Otten
Doug wrote:

 I'm using elementtree to create a form.
 
 I would like to set the selected attribute.
 
 Setting using the usual
  option.set( selected =  )

Maybe that should be option.set(selected=selected). I think

option selected=selected

and

option selected

are equivalent.

http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.3.4.2

 gives me
   option selected= value=operationsOperations/option
 how does one make
   option selected value=operationsOperations/option
 which is what I need.

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


Re: Using elementtree to Create HTML Form / Set selected

2010-08-12 Thread Doug
On Aug 12, 10:47 am, Peter Otten __pete...@web.de wrote:
 Doug wrote:
  I'm using elementtree to create a form.

  I would like to set the selected attribute.

  Setting using the usual
   option.set( selected =  )

 Maybe that should be option.set(selected=selected). I think

 option selected=selected

 and

 option selected

 are equivalent.

 http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.3.4.2



  gives me
    option selected= value=operationsOperations/option
  how does one make
    option selected value=operationsOperations/option
  which is what I need.

Makes sense to me. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __class__ of what

2010-08-12 Thread Stefan Schwarzer
Hello Jean-Michel,

On 2010-08-12 16:06, Jean-Michel Pichavant wrote:
 Eric J. Van der Velden wrote:
 Should be
 
 class C:
 n = 0
 def __init__(self):
self.__class__.n+=1
C.n+=1 # equivalent to this line (I prefer this one, more 
 readable, less refactor-friendly)

I think both lines have slightly different semantics if you
consider instantiating an object of a derived class. (The
following formatting is from IPython, thus the differences
to the usual interpreter output.)

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)

 class C(object):
... n = 0
... def __init__(self):
... self.__class__.n += 1
...
 class D(C):
... pass
...
 d = D()
 D.n
1
 C.n
0

Here, the augmented assignment looks up self.__class__.n
which it doesn't find and so gets it from class C. The
actual assignment assigns to D.n, however.

On the other hand:

 class C(object):
... n = 0
... def __init__(self):
... C.n += 1
...
 class D(C):
... pass
...
 d = D()
 D.n
1
 C.n
1

Here, only C is changed. D doesn't get an own attribute n,
and after the instantiation of d, D.n looks up and gets n
from the base class C.

Curiously,

 dir(D)
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'n']

seems to contain n (is it supposed to be listed here?), but

 dict(D.__dict__)
{'__doc__': None, '__module__': '__main__'}

indicates that D doesn't contain n. But C does:

 dict(C.__dict__)
{'__dict__': attribute '__dict__' of 'C' objects,
 '__doc__': None,
 '__init__': function __init__ at 0xb70c2454,
 '__module__': '__main__',
 '__weakref__': attribute '__weakref__' of 'C' objects,
 'n': 1}

I hope everything I wrote above is valid. If not, please
correct me. :-)

Anyway, depending on what you want, either of the two
variants might be ok. In any case I'd include a meaningful
comment on why you actually wrote what you wrote. :-)

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


Inserting/Deleting newline(s) in very large text files

2010-08-12 Thread Dlanor Slegov
Hi,

I am dealing with very large text files (a few million lines) and would like to 
check and modify them according to a well defined format. The format 
requires ONLY ONE NEWLINE (followed by some sort of text) on top of the file 
and 
NO NEWLINE in the very end. The input files can be very diverse, such as one 
file may have 2 newlines on top and none in the end or other may not have a 
newline on top and 5 in the end. 


The aim is to check these files  introduce JUST ONE NEWLINE in the TOP and NO 
NEWLINE in the BOTTOM.

Any pointers will be appreciated.

Thanks,
DS.


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


Announcing: python-ghostscript 0.3

2010-08-12 Thread Hartmut Goebel
Announcing:

python-ghostscript 0.3

A Python-Interface to the Ghostscript
 C-API using ctypes

:Copyright: GNU Public License v3 (GPLv3)
:Author:  Hartmut Goebel h.goe...@crazy-compiler.com
:Homepage: http://bitbucket.org/htgoebel/python-ghostscript
:Download: http://pypi.python.org/pypi/ghostscript

`Ghostscript`__, is a well known interpreter for the PostScript
language and for PDF. This package implements a interface to the
Ghostscript C-API using `ctypes`__. Both a low-level and a pythonic,
high-level interface are provided.

__ http://www.ghostscript.com/
__ http://docs.python.org/library/ctypes.html

This package is currently tested only under GNU/Linux. Please report
whether it works in your environment, too. Thanks.


Latest Changes


:0.3 (2010-08-12):

  * Added support for win32: The DLL to load is searched in registry.

  * On other platforms: Be more inteligent about finding Ghostscript
shared object file (fall back to ctypes.util.find_library() if
`libgs.8.so` can not be loaded

  * Better error messages if lib/dll is not found.

  * Removed relative imports, so older versions of Python can be used.

  * Added nice project logo

:0.2 (2010-08-06):

  * Fixed several bugs, esp. for running strings by Ghostscript.


Example


Here is an example for how to use the high-level interface of
`python-ghostscript`. This implements a very basic ps2pdf-tool::

  import sys
  import ghostscript

  args = [
  ps2pdf, # actual value doesn't matter
  -dNOPAUSE, -dBATCH, -dSAFER,
  -sDEVICE=pdfwrite,
  -sOutputFile= + sys.argv[1],
  -c, .setpdfwrite,
  -f,  sys.argv[2]
  ]

  ghostscript.Ghostscript(*args)

-- 
Regards
Hartmut Goebel

| Hartmut Goebel  | h.goe...@crazy-compilers.com   |
| www.crazy-compilers.com | compilers which you thought are impossible |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Puzzles? What's your favorite puzzle?

2010-08-12 Thread Ian Kelly
On Thu, Aug 12, 2010 at 5:41 AM, Matty Sarro msa...@gmail.com wrote:
 Hey All!
 Hope your thursday is treating you well. I'm looking for suggestions on
 books of programming/engineering puzzles that range from beginners to
 advanced and even expert level problems. I know they exist; we had them back
 in college for practicing before the ACM programming competitions. However I
 can't seem to really find any books out there that look like they're what
 I'm seeking. Basically I haven't programmed a lot since I was in college,
 and that was about 9 years ago. I'm expected to do a bit more programming at
 my current job and I figure the best way to get back into things is to have
 some practical things to solve, and maybe have a bit of fun in the process.

 Anyone have any suggestions?

http://www.spoj.pl/
http://www.codechef.com/

Many of the problems at those sites are difficult in Python due to the
time constraints, but they're well worth checking out.

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


Re: Announcing: python-ghostscript 0.3

2010-08-12 Thread Peter Kleiweg
Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010:

 Here is an example for how to use the high-level interface of
 `python-ghostscript`. This implements a very basic ps2pdf-tool::
 
   import sys
   import ghostscript
 
   args = [
   ps2pdf,   # actual value doesn't matter
   -dNOPAUSE, -dBATCH, -dSAFER,
   -sDEVICE=pdfwrite,
   -sOutputFile= + sys.argv[1],
   -c, .setpdfwrite,
   -f,  sys.argv[2]
   ]
 
   ghostscript.Ghostscript(*args)

How is this different from os.system(' '.join(args)) ?



-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/kleiweg/ls.html
-- 
http://mail.python.org/mailman/listinfo/python-list


unicode string alteration

2010-08-12 Thread BAvant Garde
HELP!!!
I need help with a unicode issue that has me stumped. I must be doing 
something  wrong because I don't believe this condition would have slipped thru 
testing.

Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or unichr(1113088) is 
substituted and the file loses 1 character resulting in all trailing characters 
being shifted out of position. No other corrupt strings have been detected.
    
The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 where 
the maximum ord # is 1114111 (wide Python build).
    
Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 (narrow 
Python build) the string u'\U0010fc00' also occurs and it seems that the 
substitution takes place but no characters are lost and file sizes are ok. Note 
that ord(u'\U0010fc00')
 causes the following error: 
 TypeError: ord() expected a character, but string of length 2 
found
The condition is otherwise invisible in 2.5.4 and is handled internally without 
any apparent effect on processing with characters u'\udbff' and u'\udc00' each 
being separately accessible. 

The first part of the attachment repeats this email but also has examples and 
illustrates other related oddities.
    
Any help would be greatly appreciated.
Bruce


  Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type copyright, credits or license() for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 2.6.5  
 = RESTART 
 =
 
HELP!!!
I need help with a unicode issue that has me stumped. I must be doing something
 wrong because I don't believe this condition would have slipped thru testing.

Script output in the next section w/data = map(unichr,xrange(56317,56323))
 Reveals a condition where a unicode string is corrupted when created.

Wherever the string u'\udbff\udc00' occurs u'\U0010fc00'...unichr(1113088)
  is substituted and the file loses 1 character resulting in all trailing
  characters being shifted out of position. No other corrupt strings have
  been detected.

The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04
  where the maximum ord # is 1114111 (wide Python build).

Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535
  (narrow Python build) the string u'\U0010fc00' also occurs and it seems
  that the substitution takes place but no characters are lost and file
  sizes are ok. Note that ord(u'\U0010fc00') causes the following error:
TypeError: ord() expected a character, but string of length 2 found
  The condition is otherwise invisible in 2.5.4 and is handled internally
  without any apparent effect on processing with characters u'\udbff'
  and u'\udc00' each being separately accessible. 

In Python 2.5.4/win32(ME) the system substitutes U0010fc00 but is othersize ok
as the system handles these events internally without any other known effect.

NOTE:
In Python 2.6.5/linux2(ubuntu 10.04) the system may not substitute immediately
but returns different lengths depending on the method of length request.
len(u'\udbff\udc00') returns a shorter len than: u2 = u'\udbff\udc00'; len(u2)
In those cases the variable reference method (len(u2)) is more accurate
eventhough the variable value and the string value are identical.
I have evidence of this string resulting in a file losing 1 character for each
time the string occurs on write to file. As a test I reversed the string
sequence and used the same commands to write to file, everything was fine.
I think the problem is confined to strings u'\udbff\udc00'  u'\U0010fc00'.

Any help would be greatly appreciated.
Bruce

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2

u = map(unichr, xrange(56317, 56323))
[u'\udbfd', u'\udbfe', u'\udbff', u'\udc00', u'\udc01', u'\udc02'] .. length 6, 
ords(56317-56322)

  #-#
  # EXHIBIT 1:  #
  # The following commands were used to write to file and then to read back #
  #   to illustrate the effect of the substitute string on a file's size at #
  #   least in Python 2.6.5 linux2(ubuntu 10.04), maybe other combinations. #
  # #
  # import codecs   #
  # u = map(unichr, (xrange(56317, 56323)

How to parse a sentence using grammars provided by nltk?

2010-08-12 Thread Sohail
Hi,

When I define my own production rules for the grammar the code below
runs fine. Can anyone tell me how to use the built in grammars of nltk
(if there are any)?

 groucho_grammar = nltk.parse_cfg(
... S - NP VP
... PP - P NP
... NP - Det N | Det N PP | 'I'
... VP - V NP | VP PP
... Det - 'an' | 'my'
... N - 'elephant' | 'pajamas'
... V - 'shot'
... P - 'in'
... )
 sent = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas']
 parser = nltk.ChartParser(groucho_grammar)
 trees = parser.nbest_parse(sent)
 for tree in trees:
... print tree

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


Extract stack from running python program

2010-08-12 Thread Zac Burns
Is there a utility to extract the stacks from a running python program that
is hung?

Sounds like a long shot but if anyone knows it would be you guys.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Renaming OS files by file type in python

2010-08-12 Thread MRAB

blur959 wrote:

Hi all, I am creating a program that renames all files of the similar
file type. But i am stuck at this part. I tried running this code and
I got this error:new_name = os.rename(path, newpath)
WindowsError: [Error 183] Cannot create a file when that file already
exists. Hope you guys could help.


[snip]
As the traceback says, a file with that new name already exists. You
can't have 2 files with the same name in the same folder.
--
http://mail.python.org/mailman/listinfo/python-list


OptParse and Constant values

2010-08-12 Thread J
How do you use OptParse with constants?

Example:
usage = 'Usage: %prog [OPTIONS]'
parser = OptionParser(usage)
parser.add_option('-l','--level',
  action='store_const',
  default=LOG_INFO,
  help='Set the log level to inject into syslog (either an\
  integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\
  LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG')
(options,args) = parser.parse_args()

print options

always returns {'level':None} regarless of whether I call it with an
int (0 - 7) or the const name (LOG_*)

I'm importing syslog like so:

from syslog import *

so all the syslog constants should be available to me at run time (at
least that's my understanding) so I'm doing something wrong here or
just not understanding how to do a constant as an option.

The basic gist of the above is that I'm writing a tool to do basic
syslog testing by injecting messages and making sure they end up in
the correct log file...  I can do all of this manually or in a loop by
looping through the various log levels, however, I want to be able to
specify them at run-time using an optional argument.  Any ideas on how
to make this work, or at least why it's not doing what I thought it
would do?

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


Re: OptParse and Constant values

2010-08-12 Thread Robert Kern

On 8/12/10 11:19 AM, J wrote:

How do you use OptParse with constants?

Example:
usage = 'Usage: %prog [OPTIONS]'
 parser = OptionParser(usage)
 parser.add_option('-l','--level',
   action='store_const',
   default=LOG_INFO,
   help='Set the log level to inject into syslog (either an\
   integer [0 - 7] or one of LOG_EMERG, LOG_ALERT,LOG_CRIT,\
   LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG')
 (options,args) = parser.parse_args()

 print options

always returns {'level':None} regarless of whether I call it with an
int (0 - 7) or the const name (LOG_*)


http://docs.python.org/library/optparse#standard-option-actions

'store_const' means that the option is a flag without arguments and stores the 
value provided by the 'const' keyword to add_option() (it defaults to None so 
that's what you get when you use that flag). This is not what you want. You just 
want the default 'store' action.


--
Robert Kern

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

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


Re: Long rant about Python in Education

2010-08-12 Thread John Bokma
D'Arcy J.M. Cain da...@druid.net writes:

 On Thu, 12 Aug 2010 05:05:55 -0700 (PDT)
 เข้านอน iktomus.heyo...@gmail.com wrote:
 have to teach them to enjoy programming, enjoy computers, and develop
 their minds in a way that doesn't involve becoming 'Imams' who are
 essentially the learned mafia bosses of terrorism.

 This is the point that I stopped reading your message and added you
 to my blacklist.  Goodbye.

For what it's worth, same here.

Also, I don't think it's a good idea to force a learning environment or
an OS on a child. IMO it works best if you let the child discover and be
a guide, not thou should not use Windows.

Not so remarkable that the rant moves from an extremistic teaching
environment to an extremistic world view. From hating everything that's
not Linux and idolizing the CLI to hating everything that is different
in general.

-- 
John Bokma   j3b

Hacking  Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl  Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode string alteration

2010-08-12 Thread MRAB

BAvant Garde wrote:

HELP!!!
I need help with a unicode issue that has me stumped. I must be doing 
something  wrong because I don't believe this condition would have 
slipped thru testing.


Wherever the string u'\udbff\udc00' occurs u'\U0010fc00' or 
unichr(1113088) is substituted and the file loses 1 character resulting 
in all trailing characters being shifted out of position. No other 
corrupt strings have been detected.
   
The condition was noticed while testing in Python 2.6.5 on Ubuntu 10.04 
where the maximum ord # is 1114111 (wide Python build).
   
Using Python 2.5.4 on Windows-ME where the maximum ord # is 65535 
(narrow Python build) the string u'\U0010fc00' also occurs and it 
seems that the substitution takes place but no characters are lost and 
file sizes are ok. Note that ord(u'\U0010fc00') causes the following error:
 TypeError: ord() expected a character, but string of 
length 2 found
The condition is otherwise invisible in 2.5.4 and is handled internally 
without any apparent effect on processing with characters u'\udbff' and 
u'\udc00' each being separately accessible.


The first part of the attachment repeats this email but also has 
examples and illustrates other related oddities.
   
Any help would be greatly appreciated.



It's not an error, it's a surrogate pair. Surrogate pairs are part of
the Unicode specification.

Unicode codepoints go up to U+0010.

If you're using 16 bits per codepoint, like in a narrow build of Python,
then the codepoints above U+ _can't_ be represented directly, so
they are represented by a pair of codepoints called a surrogate pair.

If, on the other hand, you're using 32 bits per codepoint, like in a
wide build of Python, then the codepoints above U+ _can_ be
represented directly, so surrogate pairs aren't needed, and, indeed
shouldn't be there.

What you're seeing in the wide build is Python replacing a surrogate
pair with the codepoint that it represents, which is actually the right
thing to do because, as I said, the surrogate pairs really shouldn't be
there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't I set sys.ps1 to a unicode string?

2010-08-12 Thread RG
In article i407mn$la...@online.de,
 Martin v. Loewis mar...@v.loewis.de wrote:

  So... why does having a non-ascii character in sys.ps1 make the prompt 
  vanish?
 
 I can't pinpoint it to a specific line of code. Most likely, it tries
 to encode the prompt as ASCII before writing it to stdout. That fails,
 and it silently ignores the error.
 
 FWIW, this is fixed in Python 3.

Guess it's time to upgrade.  :-)

Thanks!

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


inline exception handling in python

2010-08-12 Thread wheres pythonmonks
Hi!

I have on a few occasions now wanted to have inline-exception
handling, like the inline if/else operator.

For example,

The following might raise ZeroDivisionError:

f = n / d

So, I can look before I leap (which is okay):

f = float(nan) if d == 0 else n/d;

But, what I'd like to be able to write is:

f = n / d except float(nan);

Which I find much more appealing than:

try:
   f = n / d
except:
   f = float(nan)

(Obviously, I am thinking about more complicated functions than n/d
-- but this works as an example.)

Thoughts?

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


Re: OptParse and Constant values

2010-08-12 Thread J
On Thu, Aug 12, 2010 at 12:41, Robert Kern robert.k...@gmail.com wrote:
 On 8/12/10 11:19 AM, J wrote:

 How do you use OptParse with constants?

 http://docs.python.org/library/optparse#standard-option-actions

 'store_const' means that the option is a flag without arguments and stores
 the value provided by the 'const' keyword to add_option() (it defaults to
 None so that's what you get when you use that flag). This is not what you
 want. You just want the default 'store' action.

Thanks Robert...

Sigh... head - desk - repeat :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inline exception handling in python

2010-08-12 Thread Thomas Jollans
On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
 try:
f = n / d
 except:
f = float(nan)

A catch-all except clause. Never a good idea. It's not as bad in this case, as 
there is only one expression, but there are still a couple of other exceptions 
that have a chance of occurring here: KeyboardInterrupt and SystemExit.
So:

try:
f = n / d
except ZeroDivisionError:
f = float('nan')


 f = n / d except float(nan);

So this syntax really isn't adequate for real use: catch-all except clauses 
are frowned upon, and rightfully so. 

Besides, more often than not, you want to have a finally clause around when 
you're dealing with exceptions.


 (Obviously, I am thinking about more complicated functions than n/d
 -- but this works as an example.)

The more complex the function is, the more likely it is to raise an exception 
you can't handle that easily.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inline exception handling in python

2010-08-12 Thread wheres pythonmonks
On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans tho...@jollybox.de wrote:
 On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
 try:
    f = n / d
 except:
    f = float(nan)

 A catch-all except clause. Never a good idea. It's not as bad in this case, as
 there is only one expression, but there are still a couple of other exceptions
 that have a chance of occurring here: KeyboardInterrupt and SystemExit.
 So:

 try:
    f = n / d
 except ZeroDivisionError:
    f = float('nan')


 f = n / d except float(nan);

 So this syntax really isn't adequate for real use: catch-all except clauses
 are frowned upon, and rightfully so.

 Besides, more often than not, you want to have a finally clause around when
 you're dealing with exceptions.


 (Obviously, I am thinking about more complicated functions than n/d
 -- but this works as an example.)

 The more complex the function is, the more likely it is to raise an exception
 you can't handle that easily.
 --
 http://mail.python.org/mailman/listinfo/python-list


With a bit imagination the syntax can handle specific exceptions:

f = n /d except except(ZeroDivisionError) float(nan)

f = n /d except except(ZeroDivisionError) float(nan)
except(ValueError) float(nan)

But then we cannot bind to useful variable you say...

I think the problem in my case is best solved by look before you leap,
or a wrapper function.  [I just hate function call overhead for this.
]

Thanks,

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


Re: inline exception handling in python

2010-08-12 Thread wheres pythonmonks
On Thu, Aug 12, 2010 at 2:19 PM, wheres pythonmonks
wherespythonmo...@gmail.com wrote:
 On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans tho...@jollybox.de wrote:
 On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
 try:
    f = n / d
 except:
    f = float(nan)

 A catch-all except clause. Never a good idea. It's not as bad in this case, 
 as
 there is only one expression, but there are still a couple of other 
 exceptions
 that have a chance of occurring here: KeyboardInterrupt and SystemExit.
 So:

 try:
    f = n / d
 except ZeroDivisionError:
    f = float('nan')


 f = n / d except float(nan);

 So this syntax really isn't adequate for real use: catch-all except clauses
 are frowned upon, and rightfully so.

 Besides, more often than not, you want to have a finally clause around when
 you're dealing with exceptions.


 (Obviously, I am thinking about more complicated functions than n/d
 -- but this works as an example.)

 The more complex the function is, the more likely it is to raise an exception
 you can't handle that easily.
 --
 http://mail.python.org/mailman/listinfo/python-list


 With a bit imagination the syntax can handle specific exceptions:

 f = n /d except except(ZeroDivisionError) float(nan)

 f = n /d except except(ZeroDivisionError) float(nan)
 except(ValueError) float(nan)

 But then we cannot bind to useful variable you say...

 I think the problem in my case is best solved by look before you leap,
 or a wrapper function.  [I just hate function call overhead for this.
 ]

 Thanks,

 W


I mean something along these lines:

f = n /d  except(ZeroDivisionError) float(nan) except(ValueError) float(nan)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread Baba
Hi News123

Thank You for helping me out. Indeed i am not looking for the code but
rather for hints that direct my reasoning as well as hints as to how
to write basic programs like this.

You have broken down the approach into 2 parts. I have tried to solve
part 1 but i'm not quite there yet. Here's my code:

def can_buy(n_nuggets):
for a in range (1,n_nuggets):
for b in range (1,n_nuggets):
for c in range (1,n_nuggets):
if 6*a+9*b+20*c==n_nuggets:
#print a,b,c,'n_nuggets=',n_nuggets
return True
else:
return False


can_buy(55)

as you can see i am trying to loop through all combinations of values
bewtween 1 and n_nuggets and when the equation resolves it should
return True, else it should return False.

I was hoping that when i then call my function and ask it to test a
value nothing happens. What is wrong? My syntax? My semantic? Both?

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


Re: inline exception handling in python

2010-08-12 Thread MRAB

wheres pythonmonks wrote:

Hi!

I have on a few occasions now wanted to have inline-exception
handling, like the inline if/else operator.

For example,

The following might raise ZeroDivisionError:

f = n / d

So, I can look before I leap (which is okay):

f = float(nan) if d == 0 else n/d;

But, what I'd like to be able to write is:

f = n / d except float(nan);

Which I find much more appealing than:

try:
   f = n / d
except:
   f = float(nan)

(Obviously, I am thinking about more complicated functions than n/d
-- but this works as an example.)

Thoughts?


Discussed a year ago:

[Python-Dev] (try-except) conditional expression similar to (if-else) 
conditional (PEP 308)


http://code.activestate.com/lists/python-dev/90256/

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


Re: inline exception handling in python

2010-08-12 Thread wheres pythonmonks
On Thu, Aug 12, 2010 at 2:42 PM, MRAB pyt...@mrabarnett.plus.com wrote:
 wheres pythonmonks wrote:

 Hi!

 I have on a few occasions now wanted to have inline-exception
 handling, like the inline if/else operator.

 For example,

 The following might raise ZeroDivisionError:

 f = n / d

 So, I can look before I leap (which is okay):

 f = float(nan) if d == 0 else n/d;

 But, what I'd like to be able to write is:

 f = n / d except float(nan);

 Which I find much more appealing than:

 try:
   f = n / d
 except:
   f = float(nan)

 (Obviously, I am thinking about more complicated functions than n/d
 -- but this works as an example.)

 Thoughts?

 Discussed a year ago:

 [Python-Dev] (try-except) conditional expression similar to (if-else)
 conditional (PEP 308)

 http://code.activestate.com/lists/python-dev/90256/

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



http://code.activestate.com/lists/python-dev/90256/

Nice -- excellent discussion and what I was looking for.  I am
guessing that no implementation materialized.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inline exception handling in python

2010-08-12 Thread Thomas Jollans
On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
 [I just hate function call overhead for this.]

I think you've got your priorities wrong. If you want to avoid unnecessary 
overhead, avoid exceptions more than functions.

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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread Brian Victor
Baba wrote:
 def can_buy(n_nuggets):
[snip]
 can_buy(55)

 as you can see i am trying to loop through all combinations of values
 bewtween 1 and n_nuggets and when the equation resolves it should
 return True, else it should return False.

 I was hoping that when i then call my function and ask it to test a
 value nothing happens. What is wrong? My syntax? My semantic? Both?

You're calling the function, but you're not doing anything with the
result.  If you use print can_buy(55) you'll see the result on the
console.  Presumably you'll actually want to use it in an if statement.

-- 
Brian

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


Re: cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT)

2010-08-12 Thread tormod
On Aug 12, 12:30 pm, Alexander Gattin xr...@yandex.ru wrote:
 Does Windows have anything like
 LD_LIBRARY_PATH/SHLIB_PATH?

No, isn't that only if I have an actual Oracle client installed (not
the instant client)?

But great tip, wasn't exactly the solution, but your question
triggered me to check the Windows environment variables*. I included
env. variable name PATH and the value ;C:\Python31;C:\MinGW\bin;C:\TEMP
\ORAIC10\bin.
Only thing I set manually in the command prompt was: SET ORACLE_HOME=C:
\TEMP\ORAIC10 , before the build.

*=I checked the setup.py script which says:
userOracleHome = os.environ.get(ORACLE_HOME)
Checking in Visual Basic::environ(path) only included info from the
Windows env. variables, and not the ones I set via the command prompt
with PATH=%PATH%;... so I reckon if it applies to VB it also does for
os.environ

I can now import without errors!

Thanks Alexander for putting me in the right direction.


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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Peter Otten
Baba wrote:


 Thank You for helping me out. Indeed i am not looking for the code but
 rather for hints that direct my reasoning as well as hints as to how
 to write basic programs like this.
 
 You have broken down the approach into 2 parts. I have tried to solve
 part 1 but i'm not quite there yet. Here's my code:
 
 def can_buy(n_nuggets):
 for a in range (1,n_nuggets):
 for b in range (1,n_nuggets):
 for c in range (1,n_nuggets):
 if 6*a+9*b+20*c==n_nuggets:
 #print a,b,c,'n_nuggets=',n_nuggets
 return True
 else:
 return False
 
 
 can_buy(55)
 
 as you can see i am trying to loop through all combinations of values
 bewtween 1 and n_nuggets and when the equation resolves it should
 return True, else it should return False.
 
 I was hoping that when i then call my function and ask it to test a
 value nothing happens. What is wrong? My syntax? My semantic? Both?

First, the function gives up too early; it should only return False when all 
combinations of a, b, c (technically: the product of the ranges) have been 
tried.

Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + 0*20 is 
never tried; fix your ranges accordingly.

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


Re: urllib2 does not implement with Python 2.6

2010-08-12 Thread Terry Reedy

On 8/12/2010 1:34 AM, John Nagle wrote:

  Somewhat to my surprise, in Python 2.6,

with urllib2.urlopen(url) as fh :

doesn't work. It fails with
AttributeError: addinfourl instance has no attribute '__exit__'.

I thought that all the file-like objects supported with in 2.6.
No?


This seems to work in 3.1, which first came out almost a year after 2.6.

from urllib.request import urlopen
with urlopen(http://www.python.org;) as fh : pass


--
Terry Jan Reedy

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


Re: image resize doesn't work

2010-08-12 Thread Aahz
In article mailman.1399.1280702057.1673.python-l...@python.org,
Chris Hare  ch...@labr.net wrote:

And I see now what I did wrong - thanks for putting up with the questions.

Posting that information is useful for any other newbies who might be
following along
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box.  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inserting/Deleting newline(s) in very large text files

2010-08-12 Thread Thomas Jollans
On Thursday 12 August 2010, it occurred to Dlanor Slegov to exclaim:
 Hi,
 
 I am dealing with very large text files (a few million lines) and would
 like to check and modify them according to a well defined format. The
 format requires ONLY ONE NEWLINE (followed by some sort of text) on top of
 the file and NO NEWLINE in the very end. The input files can be very
 diverse, such as one file may have 2 newlines on top and none in the end
 or other may not have a newline on top and 5 in the end.
 
 
 The aim is to check these files  introduce JUST ONE NEWLINE in the TOP and
 NO NEWLINE in the BOTTOM.
 
 Any pointers will be appreciated.

If the files are that long, you might want to avoid storing the whole file in 
memory at the same time.

Have you already tried writing the program? If not, go write the program! (and 
then come back, possibly, if you have questions)


PS: What a strange format that must be. Everybody agrees that text files 
should end with a line feed, because some text editors might mess up if they 
don't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread MRAB

Baba wrote:

Hi News123

Thank You for helping me out. Indeed i am not looking for the code but
rather for hints that direct my reasoning as well as hints as to how
to write basic programs like this.

You have broken down the approach into 2 parts. I have tried to solve
part 1 but i'm not quite there yet. Here's my code:

def can_buy(n_nuggets):
for a in range (1,n_nuggets):
for b in range (1,n_nuggets):
for c in range (1,n_nuggets):
if 6*a+9*b+20*c==n_nuggets:
#print a,b,c,'n_nuggets=',n_nuggets
return True
else:
return False


can_buy(55)

as you can see i am trying to loop through all combinations of values
bewtween 1 and n_nuggets and when the equation resolves it should
return True, else it should return False.

I was hoping that when i then call my function and ask it to test a
value nothing happens. What is wrong? My syntax? My semantic? Both?


Think about it this way.

How many packs of 20 would you need? You don't want too many, but too
few is OK.

Then, how many packs of 9 for the remaining nuggets? (Again, you don't
want too many.)

Then, how many packs of 6?

If all the nuggets are accounted for, good, otherwise reduce the number
of one of the packs and try again. Repeat as necessary.

A couple of 'for' loops will do it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: exception handling with sqlite db errors

2010-08-12 Thread Aahz
In article 2a47b306-45d1-474a-9f8e-5b71eba62...@p11g2000prf.googlegroups.com,
CM  cmpyt...@gmail.com wrote:

Maybe it's not much of an issue, but I think it would be a shame if
occasional hangs/crashes could be caused by these (rare?) database
conflicts if there is a good approach for avoiding them.  I guess I
could put every last write to the db in a try/except block but I
thought there should be a more general solution, since that will
require many such exceptions and seems inelegant.

Wrap all your uses of sqlite into a function that does the try/except;
you only write the code once, then.  As you progress, you can also
change the code to retry operations.  Here's some ugly code I wrote on
top of SQLObject:

from sqlobject.dbconnection import registerConnection
from sqlobject.sqlite.sqliteconnection import SQLiteConnection

class RetrySQLiteConnection(SQLiteConnection):

Because SQLite is not really concurrent, having multiple processes 
read/write can result in locked DB failures.  In addition, SQLObject 
doesn't properly protect operations in transations, so you can get 
spurious DB errors claiming that the DB is corrupt because of
foreign key integrity failures.

This subclass retries DatabaseError and OperationalError
exceptions.

MAX_RETRIES = 4
SAFE_DB_ERROR = [
'database disk image is malformed',
'file is encrypted or is not a database',
]

def _safe_db_error(self, exception):
err = str(exception).lower()
for safe_err in self.SAFE_DB_ERROR:
if safe_err in err:
return True
return False

def _check_integrity(self):
conn = self.getConnection()
try:
i = 0
while True:
i += 1
try:
cursor = conn.cursor()
query = pragma integrity_check
SQLiteConnection._executeRetry(self, conn, cursor, query)
result = cursor.fetchall()
if result == [('ok',)]:
return True
else:
logging.error(Bad integrity result: %s, result)
return False
except DatabaseError, e:
if i  self.MAX_RETRIES:
logging.info('integrity_check, try #%s: %s', i, e)
time.sleep(2)
else:
logging.error('integrity_check, try #%s: %s', i, e)
raise
finally:
self.releaseConnection(conn)

def _executeRetry(self, conn, cursor, query):
i = 0
while True:
i += 1
try:
return SQLiteConnection._executeRetry(self, conn, cursor, query)
except OperationalError, e:
if i  self.MAX_RETRIES:
logging.warn('OperationalError, try #%s: %s', i, e)
time.sleep(10)
else:
logging.error('OperationalError, try #%s: %s', i, e)
raise
except DatabaseError, e:
if e.__class__ is not DatabaseError:
# Don't retry e.g. IntegrityError
raise
if not self._safe_db_error(e):
# Only retry specific errors
raise
if not self._check_integrity():
raise
if i  self.MAX_RETRIES:
logging.warn('DatabaseError, try #%s: %s', i, e)
time.sleep(0.5)
else:
logging.error('DatabaseError, try #%s: %s', i, e)
raise

def conn_builder():
return RetrySQLiteConnection

registerConnection(['retrysqlite'], conn_builder)

def init():
dbpath = os.path.join(common.getSyncDataPath(), app.dbname)
connection_string = retrysqlite: + dbpath
global _connection
_connection = connectionForURI(connection_string)
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box.  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-12 Thread Nobody
On Wed, 11 Aug 2010 18:49:26 -0700, RG wrote:

 This doesn't explain why cat | cat when run interactively outputs 
 line-by-line (which it does).  STDIN to the first cat is a TTY, but the 
 second one isn't.

GNU cat doesn't use stdio, it uses read() and write(), so there isn't any
buffering.

For more complex programs, using unbuffered I/O may not be practical,
due to either code complexity or performance.

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


Re: Announcing: python-ghostscript 0.3

2010-08-12 Thread Aahz
In article alpine.deb.1.10.1008121733280.3...@localhost,
Peter Kleiweg  p.c.j.klei...@rug.nl wrote:
Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010:

 Here is an example for how to use the high-level interface of
 `python-ghostscript`. This implements a very basic ps2pdf-tool::
 
   import sys
   import ghostscript
 
   args = [
   ps2pdf,  # actual value doesn't matter
   -dNOPAUSE, -dBATCH, -dSAFER,
   -sDEVICE=pdfwrite,
   -sOutputFile= + sys.argv[1],
   -c, .setpdfwrite,
   -f,  sys.argv[2]
   ]
 
   ghostscript.Ghostscript(*args)

How is this different from os.system(' '.join(args)) ?

You don't have problems with shell metacharacters.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box.  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't I set sys.ps1 to a unicode string?

2010-08-12 Thread Thomas Jollans
On Thursday 12 August 2010, it occurred to RG to exclaim:
 %%% /%%%
 
 If this were a properly unicode-enabled newsreader you would see a
 yin-yang symbol in the middle of s2.

Are you sure about that? Now maybe the mailing list gateway is messing things 
up, but I rather suspect your newsreader (or USENET server) is sending out 
nonsense. After all, Unicode usually works around here.

Some excerpts from the message, as I received it:

Content-Type: text/plain;
  charset=us-ascii
Content-Transfer-Encoding: 7bit

[...]

 print s2
%%% /%%% 

No quoted-printable. No UTF-7. Just three completely random characters?

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread Roald de Vries


On Aug 12, 2010, at 9:02 PM, Peter Otten wrote:


Baba wrote:


Thank You for helping me out. Indeed i am not looking for the code  
but

rather for hints that direct my reasoning as well as hints as to how
to write basic programs like this.

You have broken down the approach into 2 parts. I have tried to solve
part 1 but i'm not quite there yet. Here's my code:

def can_buy(n_nuggets):
   for a in range (1,n_nuggets):
   for b in range (1,n_nuggets):
   for c in range (1,n_nuggets):
   if 6*a+9*b+20*c==n_nuggets:
   #print a,b,c,'n_nuggets=',n_nuggets
   return True
   else:
   return False


can_buy(55)

as you can see i am trying to loop through all combinations of values
bewtween 1 and n_nuggets and when the equation resolves it should
return True, else it should return False.

I was hoping that when i then call my function and ask it to test a
value nothing happens. What is wrong? My syntax? My semantic? Both?


First, the function gives up too early; it should only return False  
when all
combinations of a, b, c (technically: the product of the ranges)  
have been

tried.

Second, can_buy(0) should return True, but the solution 0*6 + 0*9 +  
0*20 is

never tried; fix your ranges accordingly.


Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and  
n_nuggets/20 respectively. This will work, but does too much work.


Cheers, Roald

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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread Martin P. Hellwig

On 08/11/10 21:14, Baba wrote:
cut

How about rephrasing that question in your mind first, i.e.:

For every number that is one higher then the previous one*:
If this number is dividable by:
6 or 9 or 20 or any combination of 6, 9, 20
than this number _can_ be bought in an exact number
else
print this number

* There are an infinite amount of numbers, just imagine the biggest
number you can think of and I say plus 1 :-)


Next thing you have to do is figure out how to write this in python,
particularly getting all the combinations of divisions can be tricky.
Hint; you are not really interested in the division result but rather if 
a division would be complete or give a remainder (modulo operator).
If you get an remainder this could be okay if that can divided by one of 
the other numbers, and so forth till you ran out of combinations.


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


Re: Announcing: python-ghostscript 0.3

2010-08-12 Thread Peter Kleiweg
Aahz schreef op de 12e dag van de oogstmaand van het jaar 2010:

 In article alpine.deb.1.10.1008121733280.3...@localhost,
 Peter Kleiweg  p.c.j.klei...@rug.nl wrote:
 Hartmut Goebel schreef op de 12e dag van de oogstmaand van het jaar 2010:
 
  Here is an example for how to use the high-level interface of
  `python-ghostscript`. This implements a very basic ps2pdf-tool::
  
import sys
import ghostscript
  
args = [
ps2pdf,# actual value doesn't matter
-dNOPAUSE, -dBATCH, -dSAFER,
-sDEVICE=pdfwrite,
-sOutputFile= + sys.argv[1],
-c, .setpdfwrite,
-f,  sys.argv[2]
]
  
ghostscript.Ghostscript(*args)
 
 How is this different from os.system(' '.join(args)) ?
 
 You don't have problems with shell metacharacters.

Then use os.spawnv(os.P_WAIT, args[0], args) 



-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/kleiweg/ls.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inline exception handling in python

2010-08-12 Thread wheres pythonmonks
On Thu, Aug 12, 2010 at 2:57 PM, Thomas Jollans tho...@jollybox.de wrote:
 On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
 [I just hate function call overhead for this.]

 I think you've got your priorities wrong. If you want to avoid unnecessary
 overhead, avoid exceptions more than functions.

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


Well I suppose it matters depending on the nature of the data you are
looking at...  But small function calls tend to be the death of
interpreted languages...

 timeit.timeit(
def f(y,i):
 try:
  return(y/(i%10))
 except:
  return(float(nan))

for i in range(100):
 x = f(7,i)

)
56.362180419240985

 timeit.timeit(
for i in range(100):
 try:
  x = 7 / (i % 10)
 except:
  x = float(nan)
)
34.588313601484742

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


Decompressing a file retrieved by URL seems too complex

2010-08-12 Thread John Nagle

   I'm reading a URL which is a .gz file, and decompressing
it.  This works, but it seems far too complex.  Yet
none of the wrapping you might expect to work
actually does.  You can't wrap a GzipFile around
an HTTP connection, because GzipFile, reasonably enough,
needs random access, and tries to do seek and tell.
Nor is the output descriptor from gzip general; it fails
on readline, but accepts read. (No good reason
for that.) So I had to make a second copy.

John Nagle

def readurl(url) :
if url.endswith(.gz) :  
nd = urllib2.urlopen(url,timeout=TIMEOUTSECS)   
td1 = tempfile.TemporaryFile()  # compressed file
td1.write(nd.read())# fetch and copy file
nd.close() # done with network
td2 = tempfile.TemporaryFile()  # decompressed file
td1.seek(0) # rewind
gd = gzip.GzipFile(fileobj=td1, mode=rb) # wrap unzip
td2.write(gd.read()) # decompress file
td1.close() # done with compressed copy
td2.seek(0) # rewind
return(td2) # return file object for compressed object
else :
return(urllib2.urlopen(url,timeout=TIMEOUTSECS))
--
http://mail.python.org/mailman/listinfo/python-list


EXOR or symmetric difference for the Counter class

2010-08-12 Thread Paddy
I find myself needing to calculate the difference between two Counters
or multisets or bags.

I want those items that are unique to each bag. I know how to
calculate it:

 b = Counter(a=1, b=2)
 c = Counter(a=3, b=1)
 diff = (b - c) + (c - b)
 (b - c)
Counter({'b': 1})
 (c - b)
Counter({'a': 2})
 diff
Counter({'a': 2, 'b': 1})

But thought why doesn't this operation appear already as a method of
the class?

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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread News123
Hi Baba,

The last tips should really help you getting started:

for testing your function you could do:

Below your uncorrected code and a test for it

def can_buy(n_nuggets):
   for a in range (1,n_nuggets):
   for b in range (1,n_nuggets):
   for c in range (1,n_nuggets):
print trying for %2d: %2d %2d %2d % (n,a,b,c)
   if 6*a+9*b+20*c==n_nuggets:
   return True
   else:
   return False

# show the results for the first 50 numbers.
for n in xrange(50):
result = can_buy(n) # get the result (see Brian's comment)
print(result of can_buy(%2d) is %s % (n,result))


with the print statement in can_buy() you should immediately see some
issues.
as soon as can_buy seems to work, you could comment the print statement.


Additionally:
I would return [a,b,c] if you got a result
and [] if you got no result.

So you don't only seem whether you can buy n nuggets, but you can also
see how (AND even verify the solution)


the print statement should show you what Peter said.
You just make one test and return immediately in the else statement

Instead you should continue until you found a solution or until you
tried all possibilities.

After having fixed the fact, that you don't try all options, you'll see
that your first success would be with 6+9+12 = 27 nuggets es you never
try with 0 boxes of a kind. (as Peter mentioned)

Finally as Roald says.

if you can reduce the upper limit of your search ranges.
if you have for example 13 nuggets you do not have to try 3 boxes of 6
as this is already 18, so trying only 0,1 or two boxes is enough







You will now also see, what
On 08/12/2010 09:42 PM, Roald de Vries wrote:
 
 On Aug 12, 2010, at 9:02 PM, Peter Otten wrote:
 
 Baba wrote:


 Thank You for helping me out. Indeed i am not looking for the code but
 rather for hints that direct my reasoning as well as hints as to how
 to write basic programs like this.

 You have broken down the approach into 2 parts. I have tried to solve
 part 1 but i'm not quite there yet. Here's my code:

 def can_buy(n_nuggets):
for a in range (1,n_nuggets):
for b in range (1,n_nuggets):
for c in range (1,n_nuggets):
if 6*a+9*b+20*c==n_nuggets:
#print a,b,c,'n_nuggets=',n_nuggets
return True
else:
return False


 can_buy(55)

 as you can see i am trying to loop through all combinations of values
 bewtween 1 and n_nuggets and when the equation resolves it should
 return True, else it should return False.

 I was hoping that when i then call my function and ask it to test a
 value nothing happens. What is wrong? My syntax? My semantic? Both?

 First, the function gives up too early; it should only return False
 when all
 combinations of a, b, c (technically: the product of the ranges) have
 been
 tried.

 Second, can_buy(0) should return True, but the solution 0*6 + 0*9 +
 0*20 is
 never tried; fix your ranges accordingly.
 
 Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and
 n_nuggets/20 respectively. This will work, but does too much work.
 
 Cheers, Roald
 

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


Re: default behavior

2010-08-12 Thread David Niergarth
Peter Otten __pete...@web.de wrote:

  1 .conjugate()


This is a syntax I never noticed before. My built-in complier (eyes)
took one look and said: that doesn't work. Has this always worked in
Python but I never noticed? I see other instance examples also work.

   '1' .zfill(2)
  '01'
   1.0 .is_integer()
  True

and properties

   1.0 .real
  1.0

Curiously, this works

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


Re: shelf-like list?

2010-08-12 Thread Thomas Jollans
On Tuesday 10 August 2010, it occurred to kj to exclaim:
 I'm looking for a module that implements persistent lists: objects
 that behave like lists except that all their elements are stored
 on disk.  IOW, the equivalent of shelves, but for lists rather
 than a dictionaries.
 
 Does anyone know of such a module?
 
 (I suppose that I could slap together a crude implementation of
 such a thing by wrapping a shelf with suitable methods to simulate
 the list interface.  But I'd rather not roll my own if a tested
 implementation already exist.)

You could simply use pickle to save the data every once in a while.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread News123
One more small tip to verify whether your code is working:


On 08/12/2010 10:28 PM, News123 wrote:
 Hi Baba,
Your code, but returning the result as  suggested in my preious post:


 def can_buy(n_nuggets):
for a in range (1,n_nuggets):
for b in range (1,n_nuggets):
for c in range (1,n_nuggets):
 print trying for %2d: %2d %2d %2d % (n,a,b,c)
if 6*a+9*b+20*c==n_nuggets:
return [a,b,c]
else:
return []



# show the results for the first 50 numbers.
# and verify whether it's true

for n in xrange(50):
result = can_buy(n) # get the result (see Brian's commen
print(result of can_buy(%2d) is %s % (n,result))
if result:
a,b,c = result
if a*6+b*9+c*12 != n:
print ERROR: can_buy() gives wrong result

Alternatively you can use a nice python feature called asserts

assert statements can be used to vrify whether your code works as expected.
Nothing will be printed if the assertion is correct otherwise your
program will abort and print the assertion error:


Example:
for n in xrange(50):
result = can_buy(n) # get the result (see Brian's commen
print(result of can_buy(%2d) is %s % (n,result))
if result:
a,b,c = result
assert  a*6+b*9+c*12 == n




 
 
 with the print statement in can_buy() you should immediately see some
 issues.
 as soon as can_buy seems to work, you could comment the print statement.
 
 
 Additionally:
 I would return [a,b,c] if you got a result
 and [] if you got no result.
 
 So you don't only seem whether you can buy n nuggets, but you can also
 see how (AND even verify the solution)
 
 
 the print statement should show you what Peter said.
 You just make one test and return immediately in the else statement
 
 Instead you should continue until you found a solution or until you
 tried all possibilities.
 
 After having fixed the fact, that you don't try all options, you'll see
 that your first success would be with 6+9+12 = 27 nuggets es you never
 try with 0 boxes of a kind. (as Peter mentioned)
 
 Finally as Roald says.
 
 if you can reduce the upper limit of your search ranges.
 if you have for example 13 nuggets you do not have to try 3 boxes of 6
 as this is already 18, so trying only 0,1 or two boxes is enough
 
 
 
 
 
 
 
 You will now also see, what
 On 08/12/2010 09:42 PM, Roald de Vries wrote:

 On Aug 12, 2010, at 9:02 PM, Peter Otten wrote:

 Baba wrote:


 Thank You for helping me out. Indeed i am not looking for the code but
 rather for hints that direct my reasoning as well as hints as to how
 to write basic programs like this.

 You have broken down the approach into 2 parts. I have tried to solve
 part 1 but i'm not quite there yet. Here's my code:

 def can_buy(n_nuggets):
for a in range (1,n_nuggets):
for b in range (1,n_nuggets):
for c in range (1,n_nuggets):
if 6*a+9*b+20*c==n_nuggets:
#print a,b,c,'n_nuggets=',n_nuggets
return True
else:
return False


 can_buy(55)

 as you can see i am trying to loop through all combinations of values
 bewtween 1 and n_nuggets and when the equation resolves it should
 return True, else it should return False.

 I was hoping that when i then call my function and ask it to test a
 value nothing happens. What is wrong? My syntax? My semantic? Both?

 First, the function gives up too early; it should only return False
 when all
 combinations of a, b, c (technically: the product of the ranges) have
 been
 tried.

 Second, can_buy(0) should return True, but the solution 0*6 + 0*9 +
 0*20 is
 never tried; fix your ranges accordingly.

 Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and
 n_nuggets/20 respectively. This will work, but does too much work.

 Cheers, Roald

 

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


Re: default behavior

2010-08-12 Thread David Niergarth
[Oops, now complete...]
Peter Otten __pete...@web.de wrote:

   1 .conjugate()

This is a syntax I never noticed before. My built-in complier (eyes)
took one look and said: that doesn't work. Has this always worked in
Python but I never noticed? I see other instance examples also work.

   '1' .zfill(2)
  '01'
   1.0 .is_integer()
  True

and properties

   1.0 .real
  1.0

Curiously, a float literal works without space

   1.0.conjugate()
  1.0

but not an int.

   1.conjugate()
File stdin, line 1
  1.conjugate()
^
  SyntaxError: invalid syntax

Anyway, I didn't realize int has a method you can call.

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


Floating numbers

2010-08-12 Thread Bradley Hintze
Hi all.

Is there a way I can keep my floating point number as I typed it? For
example, I want 34.52 to be 34.52 and NOT 34.520002.

-- 
Bradley J. Hintze
Graduate Student
Duke University
School of Medicine
801-712-8799
-- 
http://mail.python.org/mailman/listinfo/python-list


Decompressing a file retrieved by URL seems too complex

2010-08-12 Thread John Nagle

(Repost with better indentation)
   I'm reading a URL which is a .gz file, and decompressing
it.  This works, but it seems far too complex.  Yet
none of the wrapping you might expect to work
actually does.  You can't wrap a GzipFile around
an HTTP connection, because GzipFile, reasonably enough,
needs random access, and tries to do seek and tell.
Nor is the output descriptor from gzip general; it fails
on readline, but accepts read. (No good reason
for that.) So I had to make a second copy.

John Nagle

def readurl(url) :
if url.endswith(.gz) :  
nd = urllib2.urlopen(url,timeout=TIMEOUTSECS)   
td1 = tempfile.TemporaryFile()  # compressed file
td1.write(nd.read())# fetch and copy file
nd.close() # done with network
td2 = tempfile.TemporaryFile()  # decompressed file
td1.seek(0) # rewind
gd = gzip.GzipFile(fileobj=td1, mode=rb) # wrap unzip
td2.write(gd.read()) # decompress file
td1.close() # done with compressed copy
td2.seek(0) # rewind
return(td2) # return file object for compressed object
else :
return(urllib2.urlopen(url,timeout=TIMEOUTSECS))
--
http://mail.python.org/mailman/listinfo/python-list


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-12 Thread News123
On 08/12/2010 09:56 PM, Martin P. Hellwig wrote:
 On 08/11/10 21:14, Baba wrote:
 cut
 
 How about rephrasing that question in your mind first, i.e.:
 
 For every number that is one higher then the previous one*:
 If this number is dividable by:
 6 or 9 or 20 or any combination of 6, 9, 20
 than this number _can_ be bought in an exact number
 else
 print this number
 

you are allowed to mix.
15 is neither divisable by 6 nor by nine, but 9 + 6 = 15

I guess, trying to find the result with divisions and remainders is
overly complicated.

Simple brute force trial to find a combination shall be enough.

Also:


if you know for example,
that you can buy 101,102,103,104,105 and 106 nuggets,
then you know, that you can buy any other larger amout of nuggets.

107 = 101 + one box of six
108 = 102 + one box of six
. . .

As soon as you found 6 sequential solutions you can stop searching.





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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-12 Thread John Posner

On 8/12/2010 9:22 AM, Dave Angel wrote:


Now you have to find the largest number below 120, which you can
easily do with brute force


Dept of overkill, iterators/generators division ...

-John

#--
from itertools import imap, product, ifilter
from operator import mul

box_sizes = (6, 9, 20)

def sum_product(s1, s2):

return scalar product of two sequences

return sum(imap(mul, s1, s2))

def reachables(target):

return generator of numbers that are = target
and are valid linear combos of McNuggets

candidate_box_counts = product(
xrange(target/box_sizes[0] + 1),
xrange(target/box_sizes[1] + 1),
xrange(target/box_sizes[2] + 1),
)

gen = (sum_product(box_sizes, tup)
  for tup in candidate_box_counts)

return (ifilter(lambda val, tgt=target: val  tgt,
gen))

if __name__ == __main__:
tgt = 120 # thanks, Dave Angel
unreachables = set(xrange(tgt)) - set(reachables(tgt))
print Max unreachable:, max(unreachables)
--
http://mail.python.org/mailman/listinfo/python-list


Re: default behavior

2010-08-12 Thread Peter Otten
David Niergarth wrote:

 [Oops, now complete...]
 Peter Otten __pete...@web.de wrote:

   1 .conjugate()

 This is a syntax I never noticed before. My built-in complier (eyes)
 took one look and said: that doesn't work. 

(1).conjugate may hurt a little less. Anyway, the space is only needed for 
the tokenizer that without it would produce a float immediately followed by 
a name.

 Has this always worked in
 Python but I never noticed? 

Probably.

 I see other instance examples also work.
 
  '1' .zfill(2)
 '01'
  1.0 .is_integer()
 True
 
 and properties
 
  1.0 .real
 1.0
 
 Curiously, a float literal works without space
 
1.0.conjugate()
   1.0
 
 but not an int.
 
1.conjugate()
 File stdin, line 1
   1.conjugate()
 ^
   SyntaxError: invalid syntax
 
 Anyway, I didn't realize int has a method you can call.
 
 --David

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


re.sub and variables

2010-08-12 Thread fuglyducky
I have a function that I am attempting to call from another file. I am
attempting to replace a string using re.sub with another string. The
problem is that the second string is a variable. When I get the
output, it shows the variable name rather than the value. Is there any
way to pass a variable into a regex?

If not, is there any other way to do this? I need to be able to dump
the variable value into the replacement string.

For what it's worth this is an XML file so I'm not afraid to use some
sort of XML library but they look fairly complicated for a newbie like
me.

Also, this is py3.1.2 is that makes any difference.

Thanks!!!

#

import random
import re
import datetime

def pop_time(some_string, start_time):
global that_string

rand_time = random.randint(0, 30)
delta_time = datetime.timedelta(seconds=rand_time)

for line in some_string:
end_time = delta_time + start_time
new_string = re.sub(thisstring, thisstring\\end_time,
some_string)
start_time = end_time

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


Re: Floating numbers

2010-08-12 Thread Gary Herron

On 08/12/2010 01:43 PM, Bradley Hintze wrote:

Hi all.

Is there a way I can keep my floating point number as I typed it? For
example, I want 34.52 to be 34.52 and NOT 34.520002.

   



Is this a Python question?


The answer is both Yes and No. The binary floating point representation 
of numbers on a computer cannot exactly represent most decimal number 
you would like to type. (Similar to the fact that you cannot represent 
1/3 exactly in a decimal system.)


But that's the internal representation, over which you have no control. 
You do, however, have control over how a number is displayed when printed.


Python 2: Choose a format that displays the exact number of digits you want
'%.2f' % a
or let str(a) choose
but not repr(a) which tries to get all the digits.
(Adding to the confusion, you might also find it confusing to understand 
which of str() or repr() Python chooses to display a number.)


Python 3: Python3 uses David Gay’s algorithm for chosing how to display 
floats. Both str(a) and repr(a) produce '34.52' for your example, which 
is probably just what you want.



Gary Herron


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


Re: Floating numbers

2010-08-12 Thread Grant Edwards
On 2010-08-12, Bradley Hintze bradle...@aggiemail.usu.edu wrote:

 Is there a way I can keep my floating point number as I typed it?

No.

 For example, I want 34.52 to be 34.52 and NOT 34.520002.

You can't represent 34.52 using base-2 IEEE floating point (the HW
floating point format used by pretty much all modern computers).
34.520002 is as close as you can get.

When you enter a base-10 floating-point number, the computer will use
the closest base-2 IEEE floating point number.

Here are the nitty-gritty details:

  http://docs.sun.com/source/806-3568/ncg_goldberg.html

Can you explain what your actual problem is?
  
-- 
Grant Edwards   grant.b.edwardsYow! I'm imagining a surfer
  at   van filled with soy sauce!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers

2010-08-12 Thread Grant Edwards
On 2010-08-12, Grant Edwards inva...@invalid.invalid wrote:
 On 2010-08-12, Bradley Hintze bradle...@aggiemail.usu.edu wrote:

 Is there a way I can keep my floating point number as I typed it?

 No.

 For example, I want 34.52 to be 34.52 and NOT 34.520002.

 You can't represent 34.52 using base-2 IEEE floating point (the HW
 floating point format used by pretty much all modern computers).
 34.520002 is as close as you can get.

 When you enter a base-10 floating-point number, the computer will use
 the closest base-2 IEEE floating point number.

 Here are the nitty-gritty details:

   http://docs.sun.com/source/806-3568/ncg_goldberg.html

Here is a gentler intro:

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

-- 
Grant Edwards   grant.b.edwardsYow! If I felt any more
  at   SOPHISTICATED I would DIE
  gmail.comof EMBARRASSMENT!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >