Re: [Tutor] Regex to find files ending with one of a given set of extensions

2010-02-22 Thread Dayo Adewunmi

Steven D'Aprano wrote:

On Mon, 22 Feb 2010 04:23:04 am Dayo Adewunmi wrote:
  

Hi all

I'm trying use regex to match image formats:



Perhaps you should use a simpler way.

def isimagefile(filename):
ext = os.path.splitext(filename)[1]
return (ext.lower() in 
('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'))



def findImageFiles():
someFiles = [
sdfinsf.png,dsiasd.dgf,wecn.GIF,iewijiefi.jPg,iasjasd.py]
return filter(isimagefile, someFiles)


  

$ python test.py
Traceback (most recent call last):
  File test.py, line 25, in module
main()
  File test.py, line 21, in main
findImageFiles()
  File test.py, line 14, in findImageFiles
findImages = imageRx(someFiles)
TypeError: '_sre.SRE_Pattern' object is not callable



The error is the line 


findImages = imageRx(someFiles)


You don't call regexes, you have to use the match or search methods. And 
you can't call it on a list of file names, you have to call it on each 
file name separately.


# untested
for filename in someFiles:
mo = imageRx.search(filename)
if mo is None:
# no match
pass
 else:
print filename




  

I incorporated this into my code:

def isimagefile(filename):
   ext = os.path.splitext(filename)[1]
   return (ext.lower() in 
   ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'))



And it's working fine now. Thanks! :-)

Dayo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Drawing faces

2010-02-22 Thread Olufemi Onanuga
Hello,
I am trying to write and test a function to meet the following specifications
 
drawFace(center,size,win),center is a point,size is an int,and win is a 
GraphWin.Draws a simple face of the given size in win.
 
I want the function to be able to draw three differnet faces in a single 
window,when i invoke drawFace(center,size,win) into def main().
 
thanks
kola


  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Extracting comments from a file

2010-02-22 Thread Kent Johnson
On Mon, Feb 22, 2010 at 1:06 AM, Lao Mao laomao1...@googlemail.com wrote:
 Hi,

 I have an html file, with xml style comments in:

 !--
 Some comments here
 Blah
 ...
 --

 I'd like to extract only the comments.  My sense of smell suggests that
 there's probably a library (maybe an xml library) that does this already.

Take a look at BeautifulSoup:
http://www.crummy.com/software/BeautifulSoup/documentation.html

Your code will look something like this (untested):

from BeautifulSoup import BeautifulSoup, Comment
data = open('myfile.html').read()
soup = BeautifulSoup(data)
current = soup

while current:
if isinstance(current, Comment):
print current.string
current = current.next

 Otherwise, my current alogorithm looks a bit like this:

 * Iterate over file
 * If current line contains !---
   - Toggle 'is_comment' to yes
 * If is_comment is yes, print the line
 * If current line contains --
   - Toggle 'is_comment' to no

 This feels crude, but is it effective, or ok?

It will break on comments like
!-- This is a comment !-- still the same comment --

It will print too much if the comment doesn't start and end at the
start and end of the line.

Kent

 Thanks,

 Laomao

 ___
 Tutor maillist  -  tu...@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Drawing faces

2010-02-22 Thread Steven D'Aprano
On Mon, 22 Feb 2010 12:49:51 pm Olufemi Onanuga wrote:
 Hello,
 I am trying to write and test a function to meet the following
 specifications 
 drawFace(center,size,win),center is a point,size is an int,and win is
 a GraphWin.Draws a simple face of the given size in win. 
 I want the function to be able to draw three differnet faces in a
 single window,when i invoke drawFace(center,size,win) into def
 main(). 
 thanks
 kola

Do you actually have a question?

Please show the code you have already written, and tell us what doesn't 
work.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python file escaping issue?

2010-02-22 Thread Steven D'Aprano
On Mon, 22 Feb 2010 06:37:21 pm spir wrote:

  It *seems* to work, because \d is left as backlash-d. But then you
  do this, and wonder why you can't open the file:

 I consider this misleading, since it can only confuse newcomers.
 Maybe lonely single backslashes (not forming a code with
 following character(s)) should be invalid. Meaning literal
 backslashes would always be doubled (in plain, non-raw, strings).
 What do you think?

Certainly it can lead to confusion for beginners, but it follows the 
convention of languages like bash and (I think) C++.

There are three main ways to deal with an unrecognised escape sequence:

* raise an error
* ignore the backslash, e.g. \d - d
* keep the backslash, e.g. \d - \d

There are good arguments for all three, so I don't think you'll get 
consensus for any change.




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Functions returning multiple values

2010-02-22 Thread Giorgio
Ok, thankyou.

So, in other words, i must pay attention to what i set as default value in a
function. I should NEVER set empty lists as default values.

The guide i've linked says To learn more about this, you should read the
documentation and look for the difference between *identity* and *equality*.
.

Can you please help me also with that? Where can i read what is the
difference?

And, i have some difficulties understanding the other strange example in
that howto. Just scroll down to: However, the *point* is that the value of
x is picked up from the *environment* at the time when the function is
defined. How is this useful? Let’s take an example — a function which
composes two other functions.

He is working on a function that compose other 2 functions. This is the
final solution

def compose(fun1, fun2):
def inner(x, fun1=fun1, fun2=fun2):
return fun1(fun2(x))
return inner

But also tries to explain why this example:

# Wrong version
def compose(fun1, fun2):
def inner(x):
return fun1(fun2(x))
return inner

def fun1(x):
return x +  world!

def fun2(x):
return Hello,

sincos = compose(sin,cos)  # Using the wrong version

x = sincos(3)

Won't work. Now, the problem is that the inner function gets fun1 and fun2
from other 2 functions.

My question is: why? inner is a sub-function of compose, where fun1 and fun2
are defined.

Giorgio

2010/2/21 Steven D'Aprano st...@pearwood.info

 On Mon, 22 Feb 2010 03:00:32 am Giorgio wrote:
  Hi,
 
  do you know if there is a way so that i can get multiple values from
  a function?
 
  For example:
 
  def count(a,b):
   c = a + b
   d = a - b
 
  How can I return the value of C and D?

 Return a tuple of c and d:

  def count(a, b):
 ... c = a + b
 ... d = a - b
 ... return c, d
 ...
  t = count(15, 11)
  t
 (26, 4)

 You can also unpack the tuple immediately:

  x, y = count(15, 11)
  x
 26
  y
 4



  Then, i have another question: i've read, some time ago, this guide
  http://hetland.org/writing/instant-python.html, skipping the
  object-related part. Now i've started reading it, and have found
  something strange: just go where it says Of course, now you know
  there is a better way. And why don’t we give it the default value of
  [] in the first place? Because of the way Python works, this would
  give all the Baskets the same empty list as default contents.. Can
  you please help me understanding this part?

 When you declare a default value in a function like this:

 def f(a, b, c=SOMETHING):

 the expression SOMETHING is calculated once, when the function is
 defined, and *not* each time you call the function.

 So if I do this:

 x = 1
 y = 2

 def f(a, b, c=x+y):
return a+b+c

 the default value for c is calculated once, and stored inside the
 function:

  f(0, 0)
 3

 Even if I change x or y:

  x = 
  f(0, 0)
 3

 So if I use a list as a default value (or a dict), the default is
 calculated once and stored in the function. You can see it by looking
 at the function's defaults:

  def f(alist=[]):
 ... alist.append(1)
 ... return alist
 
  f.func_defaults[0]
 []

 Now, call the function without an argument:

  f()
 [1]
  f()
 [1, 1]
  f()
 [1, 1, 1]
  f.func_defaults[0]
 [1, 1, 1]

 How is this happening? Because every time you call the function, it
 appends 1 to the argument. If you don't supply an argument, it appends
 1 to the default, changing it in place.

 Why doesn't the same thing happen here?

  def g(x=0):
 ... x += 1
 ... return x
 ...
  g.func_defaults[0]
 0
  g()
 1
  g()
 1
  g.func_defaults[0]
 0

 The answer is that ints are immutable: you can't change their value.
 When you do x+=1, it doesn't modify the int 0 in place, turning it into
 1. It leaves 0 as zero, and gives you a new int equal to one. So the
 default value stored in the function never changes.

 The difference boils down to immutable objects, which can't be changed
 in place, and mutable objects, which can.

 Immutable:
 ints, floats, strings, tuples, frozensets

 Mutable:
 lists, dicts, sets, most custom classes



 --
 Steven D'Aprano
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
--
AnotherNetFellow
Email: anothernetfel...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Functions returning multiple values

2010-02-22 Thread Kent Johnson
On Mon, Feb 22, 2010 at 9:13 AM, Giorgio anothernetfel...@gmail.com wrote:

 And, i have some difficulties understanding the other strange example in
 that howto. Just scroll down to: However, the point is that the value
 of x is picked up from the environment at the time when the function is
 defined. How is this useful? Let’s take an example — a function which
 composes two other functions.
 He is working on a function that compose other 2 functions. This is the
 final solution
 def compose(fun1, fun2):
     def inner(x, fun1=fun1, fun2=fun2):
         return fun1(fun2(x))
     return inner
 But also tries to explain why this example:
 # Wrong version
 def compose(fun1, fun2):
     def inner(x):
         return fun1(fun2(x))
     return inner
 def fun1(x):
     return x +  world!
 def fun2(x):
     return Hello,
 sincos = compose(sin,cos)  # Using the wrong version
 x = sincos(3)
 Won't work. Now, the problem is that the inner function gets fun1 and fun2
 from other 2 functions.
 My question is: why? inner is a sub-function of compose, where fun1 and fun2
 are defined.

It does work:
In [6]: def compose(fun1, fun2):
   ...: def inner(x):
   ...: return fun1(fun2(x))
   ...: return inner
   ...:

In [7]: def fun1(x):
   ...: return x +  world!
   ...:

In [8]: def fun2(x):
   ...: return Hello,
   ...:

In [9]: from math import sin, cos

In [10]: sincos = compose(sin,cos)  # Using the wrong version

In [11]:

In [12]: x = sincos(3)

In [13]:

In [14]: x
Out[14]: -0.8360218615377305

That is a very old example, from python 2.1 or before where nested
scopes were not supported. See the note A Note About Python 2.1 and
Nested Scopes - that is now the default behaviour.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Functions returning multiple values

2010-02-22 Thread Giorgio
Ahah Kent this is amazing.

I was reading the ITALIAN
http://www.python.it/doc/articoli/instpy-0.html version
of that guide that is not updated. But, when i decided to post there i've
posted the link of the guide in english, but actually that's not what i've
readen.

Ok, so in the new python version it works. Tha manual also states that: The
features recognized by Python 2.6 are unicode_literals, print_function,
absolute_import, division, generators, nested_scopes andwith_statement.
generators, with_statement, nested_scopes are redundant in Python version
2.6 and above because they are always enabled.

Kent, as i'm learning py, can you please spend some words on nested scopes?
What are them? And why are supported anymore?

And, if i'm not asking you too much: can you plase post an example on how
that function can return HEllo World in py 2.6?

Thankyou!

Giorgio

2010/2/22 Kent Johnson ken...@tds.net

 On Mon, Feb 22, 2010 at 9:13 AM, Giorgio anothernetfel...@gmail.com
 wrote:

  And, i have some difficulties understanding the other strange example
 in
  that howto. Just scroll down to: However, the point is that the value
  of x is picked up from the environment at the time when the function is
  defined. How is this useful? Let’s take an example — a function which
  composes two other functions.
  He is working on a function that compose other 2 functions. This is the
  final solution
  def compose(fun1, fun2):
  def inner(x, fun1=fun1, fun2=fun2):
  return fun1(fun2(x))
  return inner
  But also tries to explain why this example:
  # Wrong version
  def compose(fun1, fun2):
  def inner(x):
  return fun1(fun2(x))
  return inner
  def fun1(x):
  return x +  world!
  def fun2(x):
  return Hello,
  sincos = compose(sin,cos)  # Using the wrong version
  x = sincos(3)
  Won't work. Now, the problem is that the inner function gets fun1 and
 fun2
  from other 2 functions.
  My question is: why? inner is a sub-function of compose, where fun1 and
 fun2
  are defined.

 It does work:
 In [6]: def compose(fun1, fun2):
...: def inner(x):
   ...: return fun1(fun2(x))
   ...: return inner
...:

 In [7]: def fun1(x):
   ...: return x +  world!
   ...:

 In [8]: def fun2(x):
   ...: return Hello,
   ...:

 In [9]: from math import sin, cos

 In [10]: sincos = compose(sin,cos)  # Using the wrong version

 In [11]:

 In [12]: x = sincos(3)

 In [13]:

 In [14]: x
 Out[14]: -0.8360218615377305

 That is a very old example, from python 2.1 or before where nested
 scopes were not supported. See the note A Note About Python 2.1 and
 Nested Scopes - that is now the default behaviour.

 Kent




-- 
--
AnotherNetFellow
Email: anothernetfel...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two Card Monty with File Operations--Reading from Wrong Folder (W7?) !!!

2010-02-22 Thread Wayne Watson
Well, it looks very much like my stab in the dark is very much correct  
( see end of msg below). I changed the name of the file in the folder 
from which I copied the file to place elsewhere.  When I tried to open 
the file, it started searching for the file.Properties clearly shows it 
pointing to the wrong file.


Good grief. What has Win7 brought?

On 2/21/2010 7:29 PM, Wayne Watson wrote:

...

The question is why does Report see the folder in the wrong folder? 
Although I think I've verified matters, I could be off. Is  there a  
way to ensure  I'm really getting to the right folder?  There may be a 
Win7 problem here. See below.


Here's a diagram that might help. Cap names means folder.

BINGO
EVENTS
  a1.txt
  a2.txt
  report.py

CARDS
  track.py
  EVENTS
b1.txt
b2.txt
b3.txt

Now copy report.py to CARDS

BINGO
  EVENTS
a1.txt
a2.txt
report.py

CARDS
  track.py
  EVENTS
b1.txt
b2.txt
b3.txt
   report.py

While working on this problem, I came up with a Win7 puzzler. It 
amounts to this. If I search for files in EVENTS of CARDS for b, it 
only finds one of the b-files. I had a long 1 hour talk with HP tech 
support. They had no answer, but will take it up with MS. It may be 
related to the first problem. Probably not, but curious. I suspect 
that Win7's new folder search has somehow used a filter. I had no idea 
of any filter use until I accidentally found it in W7 Help. Perhaps 
the filter was some how set. Not by me.


Here's a stab in the dark. Maybe the copied report.py really is a 
pointer to the other one?




--
There is nothing so annoying as to have two people
 talking when you're busy interrupting. -- Mark Twain

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] generating coordinates between two pairs

2010-02-22 Thread Jojo Mwebaze
Hello There,

I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i
would like to generate two lists

[4, 4, 4, 4, 4,5, 5, 5, 5, 5,6, 6, 6, 6, 6,7, 7, 7, 7, 7]

and

[5, 6, 7, 8, 9,5, 6, 7, 8, 9,5, 6, 7, 8, 9,   5, 6, 7, 8, 9]

i am actually generating all coordinates that fall within (4,5) and (7,9)

Any help

cheers

Johnson
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] generating coordinates between two pairs

2010-02-22 Thread Jojo Mwebaze
sorry guys, i found a solution, ignore the post

cheers

Johnson

On Mon, Feb 22, 2010 at 4:57 PM, Jojo Mwebaze jojo.mweb...@gmail.comwrote:

 Hello There,

 I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i
 would like to generate two lists

 [4, 4, 4, 4, 4,5, 5, 5, 5, 5,6, 6, 6, 6, 6,7, 7, 7, 7, 7]

 and

 [5, 6, 7, 8, 9,5, 6, 7, 8, 9,5, 6, 7, 8, 9,   5, 6, 7, 8, 9]

 i am actually generating all coordinates that fall within (4,5) and (7,9)

 Any help

 cheers

 Johnson



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] generating coordinates between two pairs

2010-02-22 Thread Shashwat Anand
 [(i,j) for i in range(4, 5+1) for j in range(7, 9+1)]
[(4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9)]

On Mon, Feb 22, 2010 at 9:33 PM, Jojo Mwebaze jojo.mweb...@gmail.comwrote:

 sorry guys, i found a solution, ignore the post

 cheers

 Johnson


 On Mon, Feb 22, 2010 at 4:57 PM, Jojo Mwebaze jojo.mweb...@gmail.comwrote:

 Hello There,

 I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i
 would like to generate two lists

 [4, 4, 4, 4, 4,5, 5, 5, 5, 5,6, 6, 6, 6, 6,7, 7, 7, 7, 7]

 and

 [5, 6, 7, 8, 9,5, 6, 7, 8, 9,5, 6, 7, 8, 9,   5, 6, 7, 8, 9]

 i am actually generating all coordinates that fall within (4,5) and (7,9)

 Any help

 cheers

 Johnson




 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading large bz2 Files

2010-02-22 Thread Stefan Behnel
Norman Rieß, 19.02.2010 13:42:
 i am trying to read a large bz2 file with this code:
 
 source_file = bz2.BZ2File(file, r)
 for line in source_file:
 print line.strip()
 
 But after 4311 lines, it stoppes without a errormessage. The bz2 file is
 much bigger though.

Could you send in a copy of the unpacked bytes around the position where it
stops? I.e. a couple of lines before and after that position? Note that
bzip2 is a block compressor, so, depending on your data, you may have to
send enough lines to fill the block size.

Does it also stop if you parse only those lines from a bzip2 file, or is it
required that the file has at least the current amount of data before those
lines?

Based on this, could you please do a bit of poking around yourself to
figure out if it is a) the byte position, b) the data content or c) the
length of the file that induces this behaviour? I assume it's rather
unpractical to share the entire file, so you will have to share hints and
information instead if you want this resolved.

Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python file escaping issue?

2010-02-22 Thread Sithembewena Lloyd Dube
Wow, thank you Steve. This certainly answers a few questions i've had
simmering for a while.

On Mon, Feb 22, 2010 at 1:01 AM, Steven D'Aprano st...@pearwood.infowrote:

 On Mon, 22 Feb 2010 05:22:10 am Sithembewena Lloyd Dube wrote:
  Hi all,
 
  I'm trying to read a file (Python 2.5.2, Windows XP) as follows:
 
  assignment_file = open('C:\Documents and Settings\coderoid\My
  Documents\Downloads\code_sample.txt', 'r+').readlines()
  new_file = open(new_file.txt, 'w+')
  for line in assignment_file:
  new_file.write(line)
 
  new_file.close()
  assignment_file.close()
 
  When the code runs, the file path has the slashes converted to double
  slashes. When  try to escape them, i just seemto add more slashes.
  What am i missing?

 An understanding of how backslash escapes work in Python.

 Backslashes in string literals (but not in text you read from a file,
 say) are used to inject special characters into the string, just like C
 and other languages do. These backslash escapes include:

 \t tab
 \n newline
 \f formfeed
 \\ backslash

 and many others. Any other non-special backslash is left alone.

 So when you write a string literal including backslashes and a special
 character, you get this:

  s = 'abc\tz'  # tab
  print s
 abc z
  print repr(s)
 'abc\tz'
  len(s)
 5

 But if the escape is not a special character:

  s = 'abc\dz'  # nothing special
  print s
 abc\dz
  print repr(s)
 'abc\\dz'
  len(s)
 6

 The double backslash is part of the *display* of the string, like the
 quotation marks, and not part of the string itself. The string itself
 only has a single backslash and no quote marks.

 So if you write a pathname like this:

  path = 'C:\datafile.txt'
  print path
 C:\datafile.txt
  len(path)
 15

 It *seems* to work, because \d is left as backlash-d. But then you do
 this, and wonder why you can't open the file:

  path = 'C:\textfile.txt'
  print path
 C:  extfile.txt
  len(path)
 14


 Some people recommend using raw strings. Raw strings turn off backslash
 processing, so you can do this:

  path = r'C:\textfile.txt'
  print path
 C:\textfile.txt

 But raw strings were invented for the regular expression module, not for
 Windows pathnames, and they have a major limitation: you can't end a
 raw string with a backslash.

  path = r'C:\directory\'
  File stdin, line 1
path = r'C:\directory\'
  ^
 SyntaxError: EOL while scanning single-quoted string


 The best advice is to remember that Windows allows both forward and
 backwards slashes as the path separator, and just write all your paths
 using the forward slash:

 'C:/directory/'
 'C:textfile.txt'



 --
 Steven D'Aprano
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python file escaping issue?

2010-02-22 Thread Sithembewena Lloyd Dube
@spr, thanks for the explanation, especially on representations of strings.
To think that i freely used repr(variable_x) without fully understanding the
meaning and the power of that function..



On Mon, Feb 22, 2010 at 9:37 AM, spir denis.s...@free.fr wrote:

 Just a little complement to Steven's excellent explanation:

 On Mon, 22 Feb 2010 10:01:06 +1100
 Steven D'Aprano st...@pearwood.info wrote:

 [...]

  So if you write a pathname like this:
 
   path = 'C:\datafile.txt'
   print path
  C:\datafile.txt
   len(path)
  15
 
  It *seems* to work, because \d is left as backlash-d. But then you do
  this, and wonder why you can't open the file:

 I consider this misleading, since it can only confuse newcomers. Maybe
 lonely single backslashes (not forming a code with following
 character(s)) should be invalid. Meaning literal backslashes would always be
 doubled (in plain, non-raw, strings). What do you think?

  But if the escape is not a special character:
 
   s = 'abc\dz'  # nothing special
   print s
  abc\dz
   print repr(s)
  'abc\\dz'
   len(s)
  6
 
  The double backslash is part of the *display* of the string, like the
  quotation marks, and not part of the string itself. The string itself
  only has a single backslash and no quote marks.

 This display is commonly called representation, thus the name of the
 function repr(). It is a string representation *for the programmer* only,
 both on input and output:
 * to allow one writing, in code itself, string literal constants containing
 special characters, in a practical manner (eg file pathes/names)
 * to allow one checking the actual content of string values, at testing
 time

 The so-called interactive interpreter outputs representations by default.
 An extreme case:
  s = \\
  s
 '\\'
  print s, len(s)
 \ 1
  print repr(s), len(repr(s))
 '\\' 4
 
 The string holds 1 char; its representation (also a string, indeed) holds
 4.

  The best advice is to remember that Windows allows both forward and
  backwards slashes as the path separator, and just write all your paths
  using the forward slash:
 
  'C:/directory/'
  'C:textfile.txt'

 Another solution is to take the habit to always escape '\' by doubling it.


 Denis
 

 la vita e estrany

 http://spir.wikidot.com/
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python file escaping issue?

2010-02-22 Thread Sithembewena Lloyd Dube
I believe i encountered repr()in the Python tutorial, but i had not kept the
relevance of it in my memory..

On Mon, Feb 22, 2010 at 9:35 PM, Sithembewena Lloyd Dube
zebr...@gmail.comwrote:

 @spr, thanks for the explanation, especially on representations of strings.
 To think that i freely used repr(variable_x) without fully understanding the
 meaning and the power of that function..




 On Mon, Feb 22, 2010 at 9:37 AM, spir denis.s...@free.fr wrote:

 Just a little complement to Steven's excellent explanation:

 On Mon, 22 Feb 2010 10:01:06 +1100
 Steven D'Aprano st...@pearwood.info wrote:

 [...]

  So if you write a pathname like this:
 
   path = 'C:\datafile.txt'
   print path
  C:\datafile.txt
   len(path)
  15
 
  It *seems* to work, because \d is left as backlash-d. But then you do
  this, and wonder why you can't open the file:

 I consider this misleading, since it can only confuse newcomers. Maybe
 lonely single backslashes (not forming a code with following
 character(s)) should be invalid. Meaning literal backslashes would always be
 doubled (in plain, non-raw, strings). What do you think?

  But if the escape is not a special character:
 
   s = 'abc\dz'  # nothing special
   print s
  abc\dz
   print repr(s)
  'abc\\dz'
   len(s)
  6
 
  The double backslash is part of the *display* of the string, like the
  quotation marks, and not part of the string itself. The string itself
  only has a single backslash and no quote marks.

 This display is commonly called representation, thus the name of the
 function repr(). It is a string representation *for the programmer* only,
 both on input and output:
 * to allow one writing, in code itself, string literal constants
 containing special characters, in a practical manner (eg file pathes/names)
 * to allow one checking the actual content of string values, at testing
 time

 The so-called interactive interpreter outputs representations by default.
 An extreme case:
  s = \\
  s
 '\\'
  print s, len(s)
 \ 1
  print repr(s), len(repr(s))
 '\\' 4
 
 The string holds 1 char; its representation (also a string, indeed) holds
 4.

  The best advice is to remember that Windows allows both forward and
  backwards slashes as the path separator, and just write all your paths
  using the forward slash:
 
  'C:/directory/'
  'C:textfile.txt'

 Another solution is to take the habit to always escape '\' by doubling it.


 Denis
 

 la vita e estrany

 http://spir.wikidot.com/
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




 --
 Regards,
 Sithembewena Lloyd Dube
 http://www.lloyddube.com




-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Encryption

2010-02-22 Thread Antonio Buzzelli
Hi everyone!
I need a simple way to encrypt and decrypt some strings with a key

someone can help me??

Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encryption

2010-02-22 Thread Wayne Werner
On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli
anto.buzze...@gmail.comwrote:

 Hi everyone!
 I need a simple way to encrypt and decrypt some strings with a key

 someone can help me??


I'm sure someone can.

-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Searchlight/MVPA/ValueError

2010-02-22 Thread J
Dear all,
I am trying to run a very simple searchlight on fMRI data via PyLab (on Mac
Leopard).

My code is as follows:

from mvpa.suite import *
import os
from matplotlib.pyplot import figure, show
from mvpa.misc.io.base import SampleAttributes
from mvpa.datasets.nifti import NiftiDataset

if __debug__:
debug.active += [SLC]

attr = SampleAttributes(os.path.join(pymvpa_dataroot,
'attributes_test.txt'))
dataset = NiftiDataset(samples=os.path.join(pymvpa_dataroot,
'time_series_original_run_all.nii.gz'),
   labels=attr.labels,
   chunks=attr.chunks,
   mask=os.path.join(pymvpa_dataroot,
'anatomy_mask.nii.gz'))
detrend(dataset, perchunk=True, model='linear')
zscore(dataset, perchunk=True, baselinelabels=[1], targetdtype='float32')

# choose classifier
clf = LinearCSVMC()

# setup measure to be computed by Searchlight
# cross-validated mean transfer using an Odd-Even dataset splitter
cv = CrossValidatedTransferError(TransferError(clf),
 OddEvenSplitter())

cv = CrossValidatedTransferError(
transfer_error=TransferError(LinearCSVMC(),
splitter=OddEvenSplitter())
s1 = Searchlight(cv, radius=5)
s1_map = s1(dataset)
dataset.map2Nifti(s1_map).save('searchlight_5mm.nii.gz')

---

this runs fine for a while and then it crashes and gives me the following
errors which I am not sure what they mean.

optimization finished, #iter = 59
nu = 0.775000
obj = -0.03, rho = -0.86
nSV = 67, nBSV = 57
Total nSV = 414
---
ValueErrorTraceback (most recent call last)

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ipython
console in module()

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.pyc
in __call__(self, dataset)
103 container applying transformer if such is defined
104 
-- 105 result = self._call(dataset)
106 result = self._postcall(dataset, result)
107 return result

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/searchlight.pyc
in _call(self, dataset)
106
107 # compute the datameasure and store in results

-- 108 measure = self.__datameasure(sphere)
109 results.append(measure)
110

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.pyc
in __call__(self, dataset)
103 container applying transformer if such is defined
104 
-- 105 result = self._call(dataset)
106 result = self._postcall(dataset, result)
107 return result

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.pyc
in _call(self, dataset)
171
172 # run the beast

-- 173 result = transerror(split[1], split[0])
174
175 # unbind the testdataset from the classifier


/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/transerror.pyc
in __call__(self, testdataset, trainingdataset)
   1300 Returns a scalar value of the transfer error.
   1301 
- 1302 self._precall(testdataset, trainingdataset)
   1303 error = self._call(testdataset, trainingdataset)
   1304 self._postcall(testdataset, trainingdataset, error)

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/transerror.pyc
in _precall(self, testdataset, trainingdataset)
   1256 self.__clf.states._changeTemporarily(
   1257 enable_states=['training_confusion'])
- 1258 self.__clf.train(trainingdataset)
   1259 if self.states.isEnabled('training_confusion'):
   1260 self.training_confusion =
self.__clf.training_confusion

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/base.pyc
in train(self, dataset)
366
367 if dataset.nfeatures  0:
-- 368 result = self._train(dataset)
369 else:
370 warning(Trying to train on dataset with no features
present)

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/libsvmc/svm.pyc
in _train(self, dataset)
185 libsvm_param._setParameter('weight', weight)
186
-- 187 self.__model = svm.SVMModel(svmprob, libsvm_param)
188
189

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/libsvmc/_svm.pyc
in __init__(self, arg1, arg2)
267 msg = svmc.svm_check_parameter(prob.prob, param.param)
268 if msg:
-- 269   

Re: [Tutor] Encryption

2010-02-22 Thread Shashwat Anand
how about using base64? base64.encodestring(s) will do.



On Tue, Feb 23, 2010 at 2:30 AM, Wayne Werner waynejwer...@gmail.comwrote:

 On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli anto.buzze...@gmail.com
  wrote:

 Hi everyone!
 I need a simple way to encrypt and decrypt some strings with a key

 someone can help me??


 I'm sure someone can.

 -Wayne

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Drawing faces

2010-02-22 Thread Alan Gauld


Olufemi Onanuga femila...@yahoo.co.uk wrote

I am trying to write and test a function to meet the following 
specifications


drawFace(center,size,win),center is a point,size is an int,
and win is a GraphWin.Draws a simple face of the given size in win.

I want the function to be able to draw three differnet faces in a single
window,when i invoke drawFace(center,size,win) into def main().


Good for you. It sounds like an excellent practice exercise in using a GUI 
toolkit.

(Or even ASCII art in curses!)

BTW Which GUI toolkit are you using?
And which widget within it?
Is it the Canvas in Tkinter?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Strange list behaviour in classes

2010-02-22 Thread C M Caine
Or possibly strange list of object behaviour

IDLE 2.6.2
 class Player():
hand = []


 Colin = Player()
 Alex = Player()

 Players = [Colin, Alex]

 def hands():
for player in Players:
player.hand.append(A)

 hands()

 Colin.hand
['A', 'A']
 Alex.hand
['A', 'A']

I would have expected hand for each object to be simply ['A']. Why
does this not occur and how would I implement the behaviour I
expected/want?

Thanks in advance for your help,
Colin Caine
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encryption

2010-02-22 Thread Modulok
 I need a simple way to encrypt and decrypt some strings with a key.

Did you have any other requirements? Any specific algorithms or key lengths?

If you need real encryption, you might check out a 3rd party module
named 'PyCrypto'. It offers an implementation of the AES algorithm. A
less eloquent approach - you could also wrap the Unix command
'openssl' with a python process. Whether you can get these libraries
will depend on where you live. Strong encryption is still strictly
controlled in some regions. There are code examples in the 'README'
file of pycrypto. There are probably other AES implementations out
there as well. However, the only FIPS certified library I know of is
openssl.

-Modulok-

On 2/22/10, Shashwat Anand anand.shash...@gmail.com wrote:
 how about using base64? base64.encodestring(s) will do.



 On Tue, Feb 23, 2010 at 2:30 AM, Wayne Werner waynejwer...@gmail.comwrote:

 On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli anto.buzze...@gmail.com
  wrote:

 Hi everyone!
 I need a simple way to encrypt and decrypt some strings with a key

 someone can help me??


 I'm sure someone can.

 -Wayne

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange list behaviour in classes

2010-02-22 Thread Wayne Werner
On Mon, Feb 22, 2010 at 4:10 PM, C M Caine cmca...@googlemail.com wrote:

 Or possibly strange list of object behaviour

 IDLE 2.6.2
  class Player():
hand = []


  Colin = Player()
  Alex = Player()
 
  Players = [Colin, Alex]
 
  def hands():
for player in Players:
player.hand.append(A)

  hands()
 
  Colin.hand
 ['A', 'A']
  Alex.hand
 ['A', 'A']

 I would have expected hand for each object to be simply ['A']. Why
 does this not occur and how would I implement the behaviour I
 expected/want?

 Thanks in advance for your help,
 Colin Caine


This comes from the nature of the list object. Python lists are pass/shared
as reference objects. In your case, both Colin and Alex are pointing to the
Player object's copy of hands - they both get a reference to the same
object.

If you want to create different hand lists you could do something like this:

class Player:
def __init__(self, hand=None):
if isinstance(hand, list):
 self.hand = hand
else:
 print Player needs a list object for its hand!


ex:

In [11]: Alan = Player()
Player needs a list object for its hand!

In [12]: Alan = Player([])

In [13]: Jim = Player([])

In [14]: Alan.hand.append(3)

In [15]: Jim.hand
Out[15]: []

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange list behaviour in classes

2010-02-22 Thread Benno Lang
On 23 February 2010 08:16, Benno Lang transmogribe...@gmail.com wrote:
 class Hand:
    def __init__(self):
        self.hand = []

Of course, I meant class Player
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encryption

2010-02-22 Thread Steven D'Aprano
On Tue, 23 Feb 2010 07:50:12 am Antonio Buzzelli wrote:
 Hi everyone!
 I need a simple way to encrypt and decrypt some strings with a key

 someone can help me??

 Thanks.

I am the author of this package which might be enough for you:

http://pypi.python.org/pypi/obfuscate/

If all you want is to hide some text from casual snoopers (say, to 
hide strings in a game so that people can't just open the game in a hex 
editor and read the game messages) then obfuscate may be enough.

I can't emphasis this enough: the encryption algorithms in obfuscate are 
not up to modern standards and are NOT cryptographically secure. Do not 
use this where serious security is required.

Otherwise, google for python encryption. You might also like to ask on 
the Python newsgroup comp.lang.python for advice.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange list behaviour in classes

2010-02-22 Thread Benno Lang
On 23 February 2010 07:10, C M Caine cmca...@googlemail.com wrote:
 Or possibly strange list of object behaviour

 IDLE 2.6.2
 class Player():
        hand = []


 Colin = Player()
 Alex = Player()

 Players = [Colin, Alex]

 def hands():
        for player in Players:
                player.hand.append(A)

 hands()

 Colin.hand
 ['A', 'A']
 Alex.hand
 ['A', 'A']

 I would have expected hand for each object to be simply ['A']. Why
 does this not occur and how would I implement the behaviour I
 expected/want?

What you're accessing via Colin.hand and Alex.hand is actually
Player.hand, which is a class attribute. You want to set up attributes
on your instance objects instead; the standard way to do this is by
adding an __init__ method to your class:

class Hand:
def __init__(self):
self.hand = []

For more information, I suggest:
http://docs.python.org/tutorial/classes.html

HTH,
benno
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list to numpy record array

2010-02-22 Thread Vincent Davis
I must be missing something simple. I have a list of lists data = [['  0',
'  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', '
25'],.. and what to make a record array from it but it gets screwed up
or I don't get it, maybe both. Notice that at this stage the items are
strings, not numbers, and there is whitespace not sure this matters.
Here is what is happening
adata = numpy.array(data,numpy.float64)

 adata
array([[  0.e+00,   0.e+00,   2.3400e+02,
  2.4000e+01,   2.5000e+01],
   ...,
   [  4.7700e+02,   4.7700e+02,   2.0700e+02,
  4.5800e+01,   2.5000e+01]])

This is what I would expect except it is not a record array.

This is not what I expect. I think I have tried every iteration including
using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x',
int),('y', int),('mean',float),('stdv',float),('npixcels',int)])
What am I missing?

bdata = numpy.array(data, [('x', int),('y',
int),('mean',float),('stdv',float),('npixcels',int)])
 bdata
array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(1356161439282, 0, 0.0, 0.0, 0),
(54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
   [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   ...,
   [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(13561596370041137, 0, 0.0, 0.0, 0),
(62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
   [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)]],

  dtype=[('x', 'i8'), ('y', 'i8'), ('mean', 'f8'), ('stdv', 'f8'),
('npixcels', 'i8')])


  *Vincent Davis
720-301-3003 *
vinc...@vincentdavis.net
 my blog http://vincentdavis.net |
LinkedInhttp://www.linkedin.com/in/vincentdavis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor