Re: [Tutor] Opening .py files in firefox

2006-03-21 Thread Ed Singleton
On 20/03/06, Alan Gauld [EMAIL PROTECTED] wrote:
  If the browser tries to execute the script you will need to go to
  the file types setting in the browser and set .py to plain-text.
 
  This is what I need to do ... but, after looking at all the options
  (within tools-Options), I still can not find a way to do this;

 Neither can I! How odd.

  firefox-snafu: when I try to open a file in my document, firefox
  splits up the path, interprets the request as a series of files to
  open, and start to open a number of totally unrelated webpages.

 You probably need to mess around with quotes.

 Something like %1 after the exectuable name might do it
 %1 is DOS shorthand for the name of the file... Putting it in
 quotes should stop Firefox splitting the path.

  Thanks for your help, anyway; I'll stick to opening them with an editor
  for now.

 You've got me curious how to do this in Firefox now :-)

On Windows, Go to Run then type Regedit.  Go to HKEY_CLASSES_ROOT and
find .py then change it's Content Type to text/plain.

As far as I am aware this is the default for python files anyway, but
it may have got changed on your computer.

Firefox itself doesn't have a list of MimeTypes under normal
circumstances.  It's mimetypes.rdf is generally empty except for
references to online lists of mimetypes.  (It's stored in your profile
btw, usually [your profile]\Application
Data\Mozilla\Firefox\Profiles\)

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python MP3

2006-03-21 Thread Johanna








Hallo



This is my first post, so hallo to everyone. Im just
a newbee with python so I hope my msg will make some sense. J



Is it possible to work with MP3 in python? 

Im looking for a library to modify MP3s (like
fade in, fade out, etc..). I know there are actually some libraries for doing
this work with .wav but I didnt find one for working with MP3. Im
not sure but should be something like - http://effbot.org/librarybook/wave.htm
. Anyone?



Thanks.



Jo






___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Control Flow Graph

2006-03-21 Thread Brian C. Lum
Dear Python Tutors,

I have been looking for a good way to convert python code into a control 
flow graph.

I know of Python functions that will convert an expression into an 
abstract syntax tree (i.e. ast = parser.expr('(x+5)*5') then t = 
ast.totuple() then t), but I am not sure how to obtain a CFG.

I've gone through the compiler and it has code that converts the AST into 
a CFG (described here: 
http://www.python.org/doc/peps/pep-0339/#ast-to-cfg-to-bytecode). 
Basically, PyAST_Compile() in Python/compile.c coverts the AST to a CFG 
and outputs final bytecode from the CFG by calling two functions: 
PySymtable_Build() in Python/symtable.c and compiler_mod() in 
Python/compile.c.  PySymtable_Build() will build a symtable and 
compiler_mod() will create the CFG.

I can try to hack with the compiler, but I was wondering if anyone knew of 
any tools already out there or any easier way.

Thanks,
Brian

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python MP3

2006-03-21 Thread Andre Roberge
On 3/21/06, Johanna [EMAIL PROTECTED] wrote:
 Hallo

 This is my first post, so hallo to everyone. Im just a newbee with python so
 I hope my msg will make some sense.

 Is it possible to work with MP3 in python?


Pygame (http://www.pygame.org/docs/ref/music.html) apparently works
with mp3 files.

There's also a tutorial on using Pygame to work with sound files at
http://takira.freehosting.net/ (check Pygame notes).

I haven't used it myself.

André

 I'm looking for a library to modify MP3s (like fade in, fade out, etc..). I
 know there are actually some libraries for doing this work with .wav but I
 didn't find one for working with MP3. I'm not sure but should be something
 like - http://effbot.org/librarybook/wave.htm . Anyone?



 Thanks.



 Jo
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Opening .py files in firefox

2006-03-21 Thread Andre Roberge
** Copy of a reply sent only to Alan Gauld by mistake.

On 3/20/06, Alan Gauld [EMAIL PROTECTED] wrote:
  If the browser tries to execute the script you will need to go to
  the file types setting in the browser and set .py to plain-text.
 
  This is what I need to do ... but, after looking at all the options
  (within tools-Options), I still can not find a way to do this;

 Neither can I! How odd.

  firefox-snafu: when I try to open a file in my document, firefox
  splits up the path, interprets the request as a series of files to
  open, and start to open a number of totally unrelated webpages.

 You probably need to mess around with quotes.

 Something like %1 after the exectuable name might do it
 %1 is DOS shorthand for the name of the file... Putting it in
 quotes should stop Firefox splitting the path.



Thanks, that solved both problems!  I can now either right-click on a
Python file (icon) and chose to display it in the browser, or open the
file within Firefox (ctrl-o) itself.

Thank you!! :-)

André
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] TKinter question

2006-03-21 Thread Christian Wood

To whom this may concern,
   Attatched is the source code, which 
demonstrates a

problem I am having making a GUI for my python project  work. Both
files need to be in the same folder.

My code writes to a text file 'table.txt', and 'table.txt' is displayed in
the GUI. The user can generate new data at the click of a button
which re-writes 'table.txt', but I can only add the new table to the GUI
window rather than 'update' the existing one.

Any assistance would be much appreciated,

Regards,
Christian Wood.
Part III Aerospace Engineering
University of Southampton, UK.


Program to send to Python Tutors.
##
Question: How do I simply update a table from within TKinter?, this
current program just adds the new text box, so is there a way of removing
the old one first?, or do I have to try a completely different approach?

I am completely new to TKinter, and GUI programming, my background is just
solving numerical problems using Numeric and math and pylab.
##
Christian Wood, 2006 for Part III Individual Project, [EMAIL PROTECTED]
(Last modified: Wood 16/03/1006)

from Tkinter import *

#Tkinter User Interface
class MoC:
   def __init__(self, master):
   frame = Frame(master, width=600, height=800, bd=1)

   frame.pack()

   #Button frame
iframe4 = Frame(frame, bd=2, relief=SUNKEN)
#Using this button below, I want to update the text box in iframe5.
   Button(iframe4, text='Display table.txt', 
command=self.DisplayUpdate).pack(side=LEFT, padx=5)
   Button(iframe4, text='Quit', command=self.quit).pack(side=LEFT, padx=5)
   iframe4.pack(expand=1, fill=X, pady=10, padx=5)

   #Text box frame
   iframe5 = Frame(frame, bd=2, relief=SUNKEN)
   text=Text(iframe5, height=10, width =70)
   fd = open('table.txt')  #table.txt must be in the same folder
   lines = fd.read()
   fd.close()
   text.insert(END, lines)
   text.pack(side=LEFT, fill=X, padx=5)
   sb = Scrollbar(iframe5, orient=VERTICAL, command=text.yview)
   sb.pack(side=RIGHT, fill=Y)
text.configure(yscrollcommand=sb.set)
   iframe5.pack(expand=1, fill=X, pady=10, padx=5)


   #Command definitions
   def quit(self):
   root.destroy()

   def DisplayUpdate(self): #The command definition used to update the display.
   #Could I insert a line here to remove the existing frame/text box first?
   iframe5 = Frame(root, bd=2, relief=SUNKEN)
   text = Text(iframe5, height=10, width =70)
   fd = open('table.txt')
   lines = fd.read()
   fd.close()
   text.insert(END, lines)
   text.pack(side=LEFT, fill=X, padx=5)
   sb = Scrollbar(iframe5, orient=VERTICAL, command=text.yview)
   sb.pack(side=RIGHT, fill=Y)
text.configure(yscrollcommand=sb.set)
   iframe5.pack(expand=1, fill=X, pady=10, padx=5)
   
root = Tk()

root.option_add('*font', ('arial', 10))
all = MoC(root)
root.title('2D Method of Characteristics')
root.update
root.mainloop()

Results Table - Mexit=3.00, 10 waves, gamma=1.40

Isentropic area ratio=4.234568, MoC area ratio=4.223553
Difference between the area ratios=0.011015

node   K-  K+  Theta   Nu  M   Mu  xy
10.00 0.00 0.00 0.00 1.0088.94 0.01 0.00
25.53 0.00 2.76 2.76 1.1758.99 0.30 0.55
3   11.06 0.00 5.53 5.53 1.2851.58 0.35 0.63
4   16.59 0.00 8.29 8.29 1.3846.62 0.39 0.69
5   22.11 0.0011.0611.06 1.4742.82 0.43 0.74
6   27.64 0.0013.8213.82 1.5639.72 0.46 0.78
7   33.17 0.0016.5916.59 1.6637.08 0.49 0.82
8   38.70 0.0019.3519.35 1.7534.79 0.52 0.86
9   44.23 0.0022.1122.11 1.8532.75 0.54 0.90
   10   49.76 0.0024.8824.88 1.9530.92 0.57 0.94
   11   49.76 0.0024.8824.88 1.9530.92 0.90 1.42
   125.53-5.53 0.00 5.53 1.2851.58 0.70 0.00
   13   11.06-5.53 2.76 8.29 1.3846.62 0.83 0.16
   14   16.59-5.53 5.5311.06 1.4742.82 0.93 0.27
   15   22.11-5.53 8.2913.82 1.5639.72 1.02 0.37
   16   27.64-5.5311.0616.59 1.6637.08 1.10 0.46
   17   33.17-5.5313.8219.35 1.7534.79 1.18 0.55
   18   38.70-5.5316.5922.11 1.8532.75 1.26 0.65
   19   44.23-5.5319.3524.88 1.9530.92 1.34 0.74
   20   49.76-5.5322.1127.64 2.0529.26 1.43 0.84
   21   49.76-5.5322.1127.64 2.0529.26 

Re: [Tutor] Python MP3

2006-03-21 Thread Python
On Tue, 2006-03-21 at 10:50 +0100, Johanna wrote:
 Hallo
 
  
 
 This is my first post, so hallo to everyone. Im just a newbee with
 python so I hope my msg will make some sense. J
 
  
 
 Is it possible to work with MP3 in python? 
yumex lists
python-eyed3
python-mad
as python packages that deal with mp3 files. eyed3 is geared towards
tags (id3).  mad appears to be closer to what you are looking for.  I
have no first hand experience with either.

 
 I’m looking for a library to modify MP3s (like fade in, fade out,
 etc..). I know there are actually some libraries for doing this work
 with .wav but I didn’t find one for working with MP3. I’m not sure but
 should be something like - http://effbot.org/librarybook/wave.htm .
 Anyone?
 
  
 
 Thanks.
 
  
 
 Jo
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Struggling with writing results of loop into txt file

2006-03-21 Thread Matt Dempsey
I'm using xmltramp to process some U.S. House of Rep. vote data. I can get it to print what I want but when I try to write it to a text file I had all sorts of problems. Can someone tell me what I'm doing wrong? I've done quite a bit of searching for the solution but as a novice to Python I'm at a loss.
Here's the script:#votes data #import xmltramp for reading XML files import xmltramp#load up the house page with the vote I wantd= xmltramp.load('
http://clerk.house.gov/evs/2006/roll002.xml' )#loads up the vote data off the sitevd= d['vote-data']#makes a happy nonhyphenated variable out of metamd= d['vote-metadata']#counts the number of votes per roll
votes= len(vd)#Produces the name, party and outcome of every Arizona house member on this votefor each in range(votes): st= str(vd[each].legislator('state')) vt= str(vd[each].vote) nm= (vd[each].legislator('unaccented-name'))
 pt= str(vd[each].legislator('party')) f= file('housevote.txt', 'w') if st == 'AZ': f.write(nm) else: passf.close()Before trying to write it to a file, my loop looked like this:
for each in range(votes): st= str(vd[each].legislator('state')) if st == 'AZ': print vd[each].legislator('unaccented-name'), vd[each].legislator('party'), vd[each].vote else: pass
Any help would be most appreciated. Thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pythonic? Building a full path from a visual file tree

2006-03-21 Thread stv
Hey all,

I would like to expand the visual representation of a tree
hierarchy, given below, where child-ness is defined by indentation,
and folder-ness is highlighted with a trailing '/'

Input (test.txt):
dir1/
file1
file2
1-1/
file3
file4
dir2/
file5

The desired output is a fully qualified path for each input line:
dir1/
dir1/file1
dir1/file2
dir1/1-1/
dir1/1-1/file3
dir1/1-1/file4
dir2/
dir2/file5

I considered several brute-force solutions, but I persevered and came
to, what I think, is a more Pythonic solution. What do you think?

import string

def expand_tree(filetree):
  indent = '\t'
  stack = []
  for f in filetree:
indents = f.count(indent)
while len(stack)  indents: stack.pop()
stack.append(f.strip())
yield string.join(stack,'')
if not f.endswith('/'): stack.pop()

lines = [line.rstrip() for line in file('test.txt')]
for i in expand_tree(lines): print i

Those familiar with subversion (particularly, svnlook tree
/path/to/repos) may recognize the problem space and the sample input
(except that I simplified things a bit here, using a tab to indicate
level-of-hierarchy instead of a single space, which could appear in
the filename).  The real-world solution will use a regex to find run
of spaces at the start of element 'f'. It will also get input from
stdin instead of a file.

Questions:

Is the list comprehension the right idiom for getting a file into a
list, without the EOL chars? I'm hard-pressed to see how it could be
more concise, but this is Python :) and the rtrim() feels a little
off.

Is string.join() preferred to ''.join? Does importing all of string
outweigh the readability of string.join()?

Any subversion geeks know of way to eliminate this code with a native
svn command?

Did other folks choke on generators for as long as I did? I'm not
going to admit, publicly, how long that was :) But I found this little
test illustrative:

def gen():
  yield 1
  yield 2
  yield 3

g = gen()
g.next()
 1
g.next()
 2
g.next()
 3
g.next()
 [stack trace]

Beyond simple, but the obviousness of it is hidden in many of the
examples I saw.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Control Flow Graph

2006-03-21 Thread Danny Yoo


On Tue, 21 Mar 2006, Brian C. Lum wrote:

 I have been looking for a good way to convert python code into a control
 flow graph.

[text cut]

Hi Brian,

I think you may want to ask your question to the pypy folks, since your
question is a bit specialized.  Check out pypy, which is an implemenation
of Python in Python:

http://codespeak.net/pypy/dist/pypy/doc/news.html

They've developed tools that I think will be very helpful for you.  For
example, pypy's object spaces appear applicable here:

http://codespeak.net/pypy/dist/pypy/doc/objspace.html#the-flow-model
http://codespeak.net/pypy/dist/pypy/doc/objspace.html#introduction

Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic? Building a full path from a visual file tree

2006-03-21 Thread Kent Johnson
stv wrote:
 I considered several brute-force solutions, but I persevered and came
 to, what I think, is a more Pythonic solution. What do you think?

Looks pretty sweet to me :-)
 
 import string
 
 def expand_tree(filetree):
   indent = '\t'
   stack = []
   for f in filetree:
 indents = f.count(indent)
 while len(stack)  indents: stack.pop()
 stack.append(f.strip())
 yield string.join(stack,'')
 if not f.endswith('/'): stack.pop()
 
 lines = [line.rstrip() for line in file('test.txt')]  
 for i in expand_tree(lines): print i
 
 Questions:
 
 Is the list comprehension the right idiom for getting a file into a
 list, without the EOL chars? I'm hard-pressed to see how it could be
 more concise, but this is Python :) and the rtrim() feels a little
 off.

The list comp is fine but I don't think you need it at all, since you 
strip() the string before you add it to stack.
 
 Is string.join() preferred to ''.join? Does importing all of string
 outweigh the readability of string.join()?

string.join() is deprecated, ''.join() is preferred.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TKinter question

2006-03-21 Thread Alan Gauld
 My code writes to a text file 'table.txt', and 'table.txt' is displayed in
 the GUI. The user can generate new data at the click of a button
 which re-writes 'table.txt', but I can only add the new table to the GUI
 window rather than 'update' the existing one.

class MoC:
def __init__(self, master):
frame = Frame(master, width=600, height=800, bd=1)
frame.pack()

you are not storing the widgets so they will be lost when you leave 
__init__.

use self.frame, self.text etc so you can access them in other methods.

#Text box frame
text=Text(iframe5, height=10, width =70)
fd = open('table.txt')  #table.txt must be in the same folder
lines = fd.read()
fd.close()
text.insert(END, lines)

This putes the lines at the end of the text box.
You want to use '1.0' as the position instead of END.
Check the documentation on the Text widget in the Tkinter
reference manual.

#Command definitions
def quit(self):
root.destroy()

def DisplayUpdate(self): #The command definition used to update the 
display.
#Could I insert a line here to remove the existing frame/text box 
first?
iframe5 = Frame(root, bd=2, relief=SUNKEN)
text = Text(iframe5, height=10, width =70)

This creates a new text widget rather than using the one created in init.
If you use self.text in init you can reference thatv same widget here.

fd = open('table.txt')
lines = fd.read()
fd.close()

Since you do this in two places it might be worth making it a
loadFile() method or similar?

text.insert(END, lines)

If you use '1.0' it should overwrite the old contents. However if
the second is shorter you will get remnants so you might want
to clear the contents too, look at the delete method and use
a start of '1.0' and an end of END...

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] function signatures for callbacks

2006-03-21 Thread Don Taylor
I have a piece of code that wants a callback from a client:

The code looks like this right now:

class pawprints:
 def __init__(self, callback_fun = None)
 ...


at the client calling site I have something like this:

def printme(modulename, codename, lineno, line):
 ...

paws = pawprints(callback_fun = printme)
 ...


My questions:

1) Is this the correct way to do this (the code does seem to work OK).

2) If so, then is there a way to specify the function signature at 
callback site rather than the client site?

It seems backwards to me because because if I get the function 
definition wrong in the client site then I get a traceback to the 
callback site - which is meant to be an opaque library that the client 
should not have to know about.

Thanks,

Don.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic? Building a full path from a visual file tree

2006-03-21 Thread stv
 The list comp is fine but I don't think you need it
 at all, since you strip() the string before you
 add it to stack.

Ahh yes. I used the rstrip() in development, printing intermediary
output to stdout, so I could see what my input file-to-list looked
like (and it looked ugly with all those EOLs). The strip() to the
stack is there primarily to remove the indentation but, of course, it
can do double duty.


 string.join() is deprecated, ''.join() is preferred.


Well, I'll live with it ;-) fugly as it looks. I'm really finding that
Python nudges me into pleasant code. Doing the above in somthing like
VB, I would just brute-force it and it would feel right. Brute forcing
it in Python ... well, it just feels wrong  ... Thanks for the input.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function signatures for callbacks

2006-03-21 Thread Danny Yoo


 I have a piece of code that wants a callback from a client:

 The code looks like this right now:

 class pawprints:
  def __init__(self, callback_fun = None)
  ...


 at the client calling site I have something like this:

 def printme(modulename, codename, lineno, line):
  ...

 paws = pawprints(callback_fun = printme)
  ...


 My questions:

 1) Is this the correct way to do this (the code does seem to work OK).

Yes, the passing of printme to the pawprints() looks fine.



 2) If so, then is there a way to specify the function signature at
 callback site rather than the client site?

By function signature, do you mean being able to properly check for
weird inputs and outputs?  If so, then a qualified Yes.  One possible idea
is to use a concept called contracts:

http://www.python.org/dev/peps/pep-0316/

The problem of providing good error messages for code that uses
higher-order function callbacks is more difficult.  I'm starting to
learn about how this problem is handled by the Scheme community, and they
do attack this problem head on:

http://people.cs.uchicago.edu/~robby/pubs/papers/ho-contracts-icfp2002.pdf



So this problem is known.  I have not yet read through the PyProtocols
documentation at:

http://peak.telecommunity.com/PyProtocols.html

and perhaps this handles callbacks in a clean way too, but on a quick
glance, I don't see this yet.  (That means I have to read more carefully!
*grin*)  So it's possible that the research being done in this area has
yet to be fully absorbed into the APIs of more mainstream languages like
Python.



 It seems backwards to me because because if I get the function
 definition wrong in the client site then I get a traceback to the
 callback site - which is meant to be an opaque library that the client
 should not have to know about.

Yes, what you're asking makes sense: we want to blame the right party,
and if it's the callback provider that messed up, we should only attribute
them.  (The same kind of problem happens in Tkinter, where bugs in
callbacks end up exposing Tkinter internals.)

Unfortunately, the stack traceback shows the entire stack trace at the
point where bad things happen, so it does a little more than assign proper
blame.  The stack traceback is an imperfect mechanism for figuring out
what went wrong.  I don't know yet what the right solution is.


Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function signatures for callbacks

2006-03-21 Thread Danny Yoo
  It seems backwards to me because because if I get the function
  definition wrong in the client site then I get a traceback to the
  callback site - which is meant to be an opaque library that the client
  should not have to know about.

 Yes, what you're asking makes sense: we want to blame the right party,
 and if it's the callback provider that messed up, we should only
 attribute them.  (The same kind of problem happens in Tkinter, where
 bugs in callbacks end up exposing Tkinter internals.)


Hi Don,

As a quick-and-dirty hack, we can do a kind of wrapped exception handling
to hide the internals of the system.

Here's an example of this:

#
A small example of attaching callbacks and wrapping exceptions.

class CallbackError(Exception): pass

class Announcer(object):
def __init__(self):
self.listeners = []

def add_listener(self, listener):
self.listeners.append(listener)

def shout(self, msg):
try:
self._internal_shout(msg)
except Exception, e:
raise CallbackError, str(e)

def _internal_shout(self, msg):
for l in self.listeners:
l(msg)
#


Here's a small demonstration:

##
 announcer = Announcer()
 def f1(x):
... print f1 sees, x
...
 def f2(x):
... 1 / 0
...
 announcer.add_listener(f1)
 announcer.add_listener(f2)
 announcer.shout(foo)
f1 sees foo
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/tmp/python-213928MGH.py, line 16, in shout
__main__.CallbackError: integer division or modulo by zero
##


The traceback we see here starts off at the entry point --- at shout()
--- and because we're returning a new exception object at that point, we
don't show that we were at _internal_shout().


If we look at the implementation of shout():

def shout(self, msg):
try:
self._internal_shout(msg)
except Exception, e:
raise CallbackError, str(e)

then we can probably make this a little more sophisticated by properly
extracting more information out of the original exception to make error
debugging a little easier.


However, if we're going to go through this sophisticated route, we'd
better make extra sure not to discard useful debugging information.  One
thing that beginners will often do is something like:

try:
...
except:
print Something bad happened

which is just silly.  *grin*

There's a happy medium between error messages being too detailed and not
detailed enough; I'd personally lean toward being too detailed at first,
but maybe that's just me.



I hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unicode issue?

2006-03-21 Thread Matt Dempsey
I'm having a new problem with my House vote script. It's returning the following error: Traceback (most recent call last): File C:/Python24/evenmorevotes, line 20, in -toplevel- f.write(nm+'*'+pt+'*'+vt+'*'+md['vote-result'][0]+'*'+md['vote-desc'][0]+'*'+'\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 172: ordinal not in range(128)Here's the code: http://pastebin.com/615240What am I doing wrong?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode issue?

2006-03-21 Thread Danny Yoo


On Tue, 21 Mar 2006, Matt Dempsey wrote:

 I'm having a new problem with my House vote script. It's returning the
 following error:

 Traceback (most recent call last):
   File C:/Python24/evenmorevotes, line 20, in -toplevel-
 f.write
 (nm+'*'+pt+'*'+vt+'*'+md['vote-result'][0]+'*'+md['vote-desc'][0]+'*'+'\n')
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in
 position 172: ordinal not in range(128)


Hi Matt,

Just wondering: how familiar are you with Unicode?  What's going on is
that one of the strings in the string concatenation above contains a
Unicode string.


It's like an infection: anything that touches Unicode turns Unicode.
*grin*

##
 'hello' + u'world'
u'helloworld'
##


This has repercussions: when we're writing these strings back to files,
because we have a Unicode string, we must now be more explicit about how
Unicode is written, since files are really full of bytes, not unicode
characters.  That is, we need to specify an encoding.


'utf-8' is a popular encoding that turns Unicode reliably into a bunch of
bytes:

##
 u'\u201c'.encode('utf8')
'\xe2\x80\x9c'
##

and this can be written to a file.  Recovering Unicode from bytes can be
done by going the other way, by decoding:

##
 '\xe2\x80\x9c'.decode(utf8)
u'\u201c'
##



The codecs.open() function in the Standard Library is useful for handling
this encode/decode thing so that all we need to do is concentrate on
Unicode:

http://www.python.org/doc/lib/module-codecs.html#l2h-991

For example:

##
 import codecs

 f = codecs.open(foo.txt, wb, utf8)
 f.write(u'\u201c')
 f.close()

 open('foo.txt', 'rb').read()
'\xe2\x80\x9c'

 codecs.open(foo.txt, rb, utf-8).read()
u'\u201c'
##


We can see that if we read and write to a codec-opened file, it'll
transparently do the encoding/decoding step for us as we write() and
read() the file.


You may also find Joel Spolsky's post on The Absolute Minimum Every
Software Developer Absolutely, Positively Must Know About Unicode And
Character Sets (No Excuses!) useful in clarifying the basic concepts of
Unicode:

http://www.joelonsoftware.com/articles/Unicode.html


I hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic? Building a full path from a visual file tree

2006-03-21 Thread stv
On 3/21/06, stv [EMAIL PROTECTED] wrote:

 import string

 def expand_tree(filetree):
   indent = '\t'
   stack = []
   for f in filetree:
 indents = f.count(indent)
 while len(stack)  indents: stack.pop()
 stack.append(f.strip())
 yield string.join(stack,'')
 if not f.endswith('/'): stack.pop()

 The real-world solution will use a regex to find run
 of spaces at the start of element 'f'.

Hmmm, I'm having to rethink this ... regex will probably not do what I
want (count instance of indent ... or, even if regex will do,
there's probably a cleaner solution without it.

Given the subversion problem space (where I can count on 1 space for
each level of child-ness), are there cleaner solutions than this:

indents = len(f) - len(f.lstrip())
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode issue? (fwd)

2006-03-21 Thread Danny Yoo

 A friend of mine showed me where the unicode is showing up but we still
 can't get script to work right. We tried encoding the appropriate
 variable but it still is spitting back the error. Would I just have:
 u'\u201c'.encode('utf8') in my script or should it be
 md['vote-desc'][0].encode('utf8')


[Keeping tutor in CC.  Please do not send replies only to me; you need to
give other people on Tutor the opportunity to answer as well.


Hi Matt,


I should clarify: when I said:

 What's going on is that one of the strings in the string concatenation
 above contains a Unicode string.

I was a bit imprecise.  What I should really have said was:

What's going on is that at least one --- there could be more! ---
strings in the string concatenation contains a Unicode string.

I'm positive you have more than one Unicode string in there.  *grin*


Rather than hunt-and-peck for all the places where Unicode is coming from,
it's probably a better approach to just wholesale encode() the whole
string after you do the concatenation and before passing it off to
write().

Alternative, take a close look at the codecs example I showed before near
the bottom of the last message: it handles encoding and decoding for you.
Using the codecs module is probably the better approach here, since
otherwise you have to look at every file write(), and that can be a bit
tiring.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to get a line text from input file.

2006-03-21 Thread Keo Sophon
Hi all,

i am new to programming language and python. I wonder how to get a line text 
from input file.

Thanks,
sophon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to set a value to a block of memory

2006-03-21 Thread Keo Sophon
Hi all,

How can i set a value to a bytes of block of memory. In C, i think they use 
memset like this.

Thanks,
Sophon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python MP3

2006-03-21 Thread Bill Burns
Johanna wrote:
 Hallo
 
  
 
 This is my first post, so hallo to everyone. Im just a newbee with 
 python so I hope my msg will make some sense. J
 
  
 
 Is it possible to work with MP3 in python?
 
 I’m looking for a library to modify MP3s (like fade in, fade out, 
 etc..). I know there are actually some libraries for doing this work 
 with .wav but I didn’t find one for working with MP3. I’m not sure but 
 should be something like - http://effbot.org/librarybook/wave.htm . Anyone?
 
  

You may want to have a look at PyMedia:

http://www.pymedia.org/

HTH,

Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to set a value to a block of memory

2006-03-21 Thread Kent Johnson
Keo Sophon wrote:
 Hi all,
 
 How can i set a value to a bytes of block of memory. In C, i think they use 
 memset like this.

Python does not support direct access to memory, you will need to use 
another language or maybe a C extension to Python to do this.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get a line text from input file.

2006-03-21 Thread Kent Johnson
Keo Sophon wrote:
 Hi all,
 
 i am new to programming language and python. I wonder how to get a line text 
 from input file.

The simplest Python idiom to do something with each line of a file is this:
   for line in open('somefile.txt'):
 # do something with line

You can find out more here:
http://docs.python.org/tut/node9.html#SECTION00920

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python MP3

2006-03-21 Thread Gabriel S Farrell
On Tue, Mar 21, 2006 at 09:35:15PM -0500, Bill Burns wrote:
 Johanna wrote:
  Is it possible to work with MP3 in python?
  
  I?m looking for a library to modify MP3s (like fade in, fade out, 
  etc..). 
 
 You may want to have a look at PyMedia:
 
 http://www.pymedia.org/

I agree with Bill, pymedia looks like the closest thing to what you're
after.  There's also pyxmms (python-xmms in Debian) if you don't mind
going through xmms.  pygame might do the trick, also (check out
http://www.pygame.org/docs/ref/music.html).

gsf
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get a line text from input file.

2006-03-21 Thread Danny Yoo


On Wed, 22 Mar 2006, Keo Sophon wrote:

 i am new to programming language and python. I wonder how to get a line
 text from input file.

Hi Sophon,

You may want to look at:

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Many of the tutorials there talk about reading from files, including Alan
Gauld's How to Program:

http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm

How are you learning how to program?  Is there a particular tutorial that
you're reading from?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to set a value to a block of memory

2006-03-21 Thread Danny Yoo


On Tue, 21 Mar 2006, Kent Johnson wrote:

  How can i set a value to a bytes of block of memory. In C, i think
  they use memset like this.

Hi Sophon,

Secondary question: why are you trying to do this?  Are you trying to
represent a collection or array of things?


Some concepts in C aren't well represented in Python because they only
make sense from a low-level hardware perspective.  For example, asking for
an equivalent for C's malloc() or free() functions is nonsensical in the
sense that, since Python is garbage collected, it provides no such
functions to the casual Python user.

(Such functions ARE available through third-party modules such as SWIG,
but unless you are really trying to integrate with a C library, you don't
need this.)


As an extended example: C programmers often use malloc() to dynamically
build structures, such as linked lists:

/**/
/*** C Code **/
#include stdio.h
#include stdlib.h

struct IntList {
  int first;
  struct IntList *rest;
};

struct IntList* construct(int head, struct IntList* rest) {
  struct IntList* newlist;
  newlist = malloc(sizeof(struct IntList));
  newlist-first = head;
  newlist-rest = rest;
  return newlist;
}

void printList(struct IntList* list) {
  while (list != NULL) {
printf(%d\n, list-first);
list = list-rest;
  }
}

int main() {
  struct IntList *mylist = NULL;
  mylist = construct(5, mylist);
  mylist = construct(1, mylist);
  mylist = construct(4, mylist);
  mylist = construct(1, mylist);
  mylist = construct(3, mylist);
  printList(mylist);
  return 0;
}
/**/


But in Python, we can do this structure building without explicitely
malloc()ing.  The code above has a possible translation which looks
like:



## Python Code ##
import sys
class LinkedList:
def __init__(self, first, rest):
self.first, self.rest = first, rest

def printList(list):
while list != None:
print list.first
list = list.rest

def main():
mylist = None
mylist = LinkedList(5, mylist)
mylist = LinkedList(1, mylist)
mylist = LinkedList(4, mylist)
mylist = LinkedList(1, mylist)
mylist = LinkedList(3, mylist)
printList(mylist)
sys.exit(0)

if __name__ == '__main__':
main()


where most of the low-level details of allocating memory are all handled
by the Python runtime.

So rather than ask for direct equivalents to C, it might help to ask about
what you're trying to do.  We'll do what we can to help translate between
C concepts and Python concepts, and for the most part, what you already
know will have close analogues.  But some concepts will require a bit of
tweaking.


Good luck!


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to set a value to a block of memory

2006-03-21 Thread Danny Yoo


 On Tue, 21 Mar 2006, Kent Johnson wrote:
   
   How can i set a value to a bytes of block of memory. In C, i think
   they use memset like this.


Whoops, sorry about that Kent!  I completely messed up the attribution
when cutting-and-pasting.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hi

2006-03-21 Thread Kaushal Shriyan
Hi

I am new to python and I am going through the URL
http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment
I am going through the Chapter 7 Strings, I am stuck with understanding
slice which is a part of a String, I am not able to understand how it functions

Awaiting your earnest reply

Thanks in Advance

Regards

Kaushal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hi

2006-03-21 Thread Danny Yoo

 I am new to python and I am going through the URL
 http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going
 through the Chapter 7 Strings, I am stuck with understanding slice which
 is a part of a String, I am not able to understand how it functions

Hello,


A slice takes a string and returns a substring of that string.  For
example, if we have a string like:

##
 mystring = supercalifragilisticexpialidocious
##

then we can select different portions of the string by indicating the
start and end positions.  For example, the first ten characters of
mystring can be extracted using a slice:

##
 mystring[0:10]
'supercalif'
##


Is this what you are confused about?

Please give us more details on where you're getting stuck, and we will do
what we can to help clarify.


Please continue to reply to '[EMAIL PROTECTED]': do not email me
directly. Although I may not personally have the time to answer, I'm sure
at least one of the other helpers on the list do, so by continuing the
conversation on python-help, we'll be able to guarantee that your
questions are not lost.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hi

2006-03-21 Thread Kaushal Shriyan
On 3/22/06, Danny Yoo [EMAIL PROTECTED] wrote:

  I am new to python and I am going through the URL
  http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment I am going
  through the Chapter 7 Strings, I am stuck with understanding slice which
  is a part of a String, I am not able to understand how it functions

 Hello,


 A slice takes a string and returns a substring of that string.  For
 example, if we have a string like:

 ##
  mystring = supercalifragilisticexpialidocious
 ##

 then we can select different portions of the string by indicating the
 start and end positions.  For example, the first ten characters of
 mystring can be extracted using a slice:

 ##
  mystring[0:10]
 'supercalif'
 ##


 Is this what you are confused about?

 Please give us more details on where you're getting stuck, and we will do
 what we can to help clarify.


 Please continue to reply to '[EMAIL PROTECTED]': do not email me
 directly. Although I may not personally have the time to answer, I'm sure
 at least one of the other helpers on the list do, so by continuing the
 conversation on python-help, we'll be able to guarantee that your
 questions are not lost.



Thanks Danny Yoo

I got this, Lets say if its mystring[n:m] where n may be another
number and m may be another number so how will it work in that case,
so this becomes general and makes more clear

Lets say if its mystring[3:8] so how will i evaluate it

Thanks for all the help

Regards

Kaushal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hi

2006-03-21 Thread Noufal Ibrahim
On Wed, March 22, 2006 12:11 pm, Kaushal Shriyan wrote:
 Hi

 I am new to python and I am going through the URL
 http://www.ibiblio.org/obp/thinkCSpy/index.htm, At the moment
 I am going through the Chapter 7 Strings, I am stuck with understanding
 slice which is a part of a String, I am not able to understand how it
 functions

Can you be a bit more specific? String slices are copies of pieces of
strings. As for the values of indices, take a look at
http://nibrahim.net.in/slice.png

It's something I tried to use during a presentation at my workplace.
You create something like that by doing
foo = corrupt
Then the indices are as per the diagram.
If you say foo[0], you'll get back c. foo[1] will give you o etc.

It helps to think of the indices as pointing to in between the letters.
Not to the letters themselves.

Now, try something like foo[1:3], you'll get back or and if you refer
the diagram, it's fairly straightforward why (slice starts at position 1
and ends at position 3. Everything in between is displayed).

foo [:3] is the same as saying foo[0:3]. foo[3:] is similar.

Negative indices start from the position shown. There's a bit of asymmetry
here since foo[0] refers to the first element of the string but foo[-1]
refers to the last one. You'll get used to it once you get used to the
idea of indices pointing to in between the elements though.

Another thing you should understand (python experts, please correct me if
I'm wrong) is that the slice operator actually creates a new string and
doesn't return a piece of the existing string. So, when you say foo[:],
you'll get a string that's a copy of the original one.

Please let me know if I can help you out with this anymore.

-- 
-NI

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor