Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread emile

Dave Angel wrote:



> The whole Y2K problem was caused because
too many programmers made unwarranted assumptions about their data (in 
that case about the range of valid dates).  


Well, yes.  But we knew then that the stuff we were writing wouldn't 
still be in play 25 years out.  :)


And they were also saving 
space, in an era where hard disks were available for maybe three 
thousand dollars for 10 megabytes.


I remember it well... if not fondly.  5Mb internal and 5Mb removable. 
Eventually (by 1980) we could buy 80Mb drives dumbed down to 35Mb for 
$20k.  Quite a bit better than the IBM mag-card system I started with, 
itself a step up from single use punch cards...


Emile


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


Re: [Tutor] managing memory large dictionaries in python

2012-10-16 Thread emile

On 10/16/2012 01:03 PM, Prasad, Ramit wrote:

Abhishek Pratap wrote:

Sent: Tuesday, October 16, 2012 11:57 AM
To: tutor@python.org
Subject: [Tutor] managing memory large dictionaries in python

Hi Guys

For my problem I need to store 400-800 million 20 characters keys in a
dictionary and do counting. This data structure takes about 60-100 Gb
of RAM.
I am wondering if there are slick ways to map the dictionary to a file
on disk and not store it in memory but still access it as dictionary
object. Speed is not the main concern in this problem and persistence
is not needed as the counting will only be done once on the data. We
want the script to run on smaller memory machines if possible.

I did think about databases for this but intuitively it looks like a
overkill coz for each key you have to first check whether it is
already present and increase the count by 1  and if not then insert
the key into dbase.

Just want to take your opinion on this.

Thanks!
-Abhi


I do not think that a database would be overkill for this type of task.


Agreed.


Your process may be trivial but the amount of data it has manage is not 
trivial. You can use a simple database like SQLite. Otherwise, you
could create a file for each key and update the count in there. It will
run on a small amount of memory but will be slower than using a db.


Well, maybe -- depends on how many unique entries exist.  Most vanilla 
systems are going to crash (or give the appearance thereof) if you end 
up with millions of file entries in a directory.  If a filesystem based 
answer is sought, I'd consider generating 16-bit CRCs per key and 
appending the keys to the CRC named file, then pass those, sort and do 
the final counting.


Emile

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


Re: [Tutor] Doubt!

2012-10-23 Thread emile

On 10/23/2012 04:14 PM, Nitin Ainani wrote:

Dear Sir/Madam,

I am  new to python I have a question. It is as follows:

Suppose *s* is a variable and *s* stores empty string

s=""
Now if we write following statement


print(s[0])  # it gives error


print(s[0:])# it does not give error

why?


See http://docs.python.org/tutorial/introduction.html and in particular 
section 3.1.2 on Strings where you'll find


"Degenerate slice indices are handled gracefully: an index that is too 
large is replaced by the string size, an upper bound smaller than the 
lower bound returns an empty string."


HTH,

Emile

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


Re: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL

2013-04-19 Thread emile

On 04/19/2013 03:07 PM, Alan Gauld wrote:

On 19/04/13 22:19, Chetan Sai wrote:


I'm a beginner in Python Programming.


The language isn't really the issue here the issue is the algorithm.
So how would you do it manually with a paper and pen? (forget about
fetching the list from the URL for now)

One possibility is to use sets (Python has a set data type).
create a set of words.
Now create a set of reversed words.
The intersection of those sets is the set of words which
also have a reversed pair.

print the intersection set.


The gotcha with this approach is the border case of self paired words 
that aren't pairs.  (pop,wow,mom,etc)


I got 94 distinct pairs.  Which is a better result than the 124.5 pairs 
I got the first pass through.


Emile



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


Re: [Tutor] How to post: Was Re: The Charms of Gmail

2013-12-23 Thread emile

On 12/23/2013 07:11 AM, Steven D'Aprano wrote:


Are you now even a
*tiny* bit moved to use a single space after full stops?)


No.  See http://www.heracliteanriver.com/?p=324

Emile

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


Re: [Tutor] ValueError: could not convert string to float: '13,2'

2014-01-03 Thread emile

On 12/31/2013 12:56 PM, Mark Lawrence wrote:

import locale

# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
print(locale.atof("3,14"))



This is a good solution, but be aware that it could impact other parts 
of your porgram as well, particularly if this is a read in data set from 
a non-local region.  Also, in places where commas are used as decimal 
points, it's also common to use periods as commas:


>>> print(locale.atof("123.456,14"))
123456.14

Emile





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


Re: [Tutor] run a python script from access form

2014-01-31 Thread emile

On 01/31/2014 08:20 AM, Ahmed, Shakir wrote:

Hi,

I am trying to run a python script from Microsoft Access form.  Your help is 
highly appreciated.


I've not done this with Access, but I have created com servers in python 
that were used from Excel.  I'd start with ActiveState's python 
distribution which includes Mark Hammond's windows extensions.  Then 
read through the docs on com servers.  It's been a while since I've done 
so, but I expect that should get you going.


Emile



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


Re: [Tutor] auto completion before initially running program

2014-01-31 Thread emile

On 01/31/2014 01:13 AM, Ian D wrote:

I notice that until a program has been run once, and I presume loaded its 
imports, I cannot use auto completion.

I don't suppose there is a way to have it load modules in a way that would give 
me access to the module functions straight away other than running the program

I presume there is no way around this.


Autocompletion is provided by the editor you're using.  You'll need to 
place some more context around this question to get appropriate responses.


Emile



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


Re: [Tutor] is an alias a variable

2014-01-31 Thread emile

On 01/31/2014 01:57 AM, Ian D wrote:

Hi

is
import longModuleName  as lmn

or

lmn = longModuleName

creating an alias or assigning to a variable. or both?


Yes (I'm not goint to get into the symantic issues of what's an alias or 
variable)


Python 2.7.3 (default, Nov  2 2012, 09:35:42)
[GCC 2.96 2731 (Red Hat Linux 7.1 2.96-85)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys as s
>>> m = s
>>> id(m)
1075446500
>>> id(s)
1075446500
>>>

The id's are the same so they refer to the same object.

Emile



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


Re: [Tutor] for: how to skip items

2014-02-17 Thread emile

On 02/17/2014 08:05 AM, Gabriele Brambilla wrote:

Hi,

I'm wondering how I can (if I can) make a for loop in which I don't use all
the elements.

for example

a100 = list(range(100))

for a in a100:
  print(a)

it print out to me all the numbers from 0 to 99
But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every
10 elements) how can I do it WITHOUT defining a new list (my real case is
not so simple) and WITHOUT building a list of indexes?


Look into python's slice notation --

[root@whfw2 root]# python
Python 2.7.1 (r271:86832, Dec  6 2010, 13:47:21)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a100 = list(range(100))
>>> a100[::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>>


HTH,

Emile




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


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread emile

On 08/08/2014 01:50 AM, Greg Markham wrote:



die_1 = """
.-.
| |
|  o  |
| |
`-'"""

die_2 = """
.-.
|o|
| |
|o|
`-'"""



I'll leave the cleanup as an exercise for you.

HTH,

Emile


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


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread emile

On 08/08/2014 10:58 AM, emile wrote:

On 08/08/2014 01:50 AM, Greg Markham wrote:



die_1 = """
.-.
| |
|  o  |
| |
`-'"""

die_2 = """
.-.
|o|
| |
|o|
`-'"""




Not quite sure how this part was dropped...

>>> for line in zip(die_1.split("\n"),die_2.split("\n")): print line
...
('', '')
('.-.', '.-.')
('|     |', '|o|')
('|  o  |', '| |')
('| |', '|o|')
("`-'", "`-'")




I'll leave the cleanup as an exercise for you.

HTH,

Emile


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




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


Re: [Tutor] Searching in a file

2010-01-13 Thread Emile van Sebille

On 1/13/2010 9:49 AM Paul Melvin said...

Hi,

I have a file generated from a webpage.

I want to search that file for a specific keyword, in my case 'NEW'.

Once I have found that keyword I want to retrieve information below it, e.g.
web link, size of file etc.

When I have this information I move off until I find another 'NEW' and the
process starts all over.

Please can someone give me some pointers on how to do this.

I can find the line containing 'NEW' which I get using a simple for loop on
every line in the file, but how do I then traverse the next x amount of
lines, taking what I want until either the next 'NEW' or eof.

e.g.

for line in file:
if re.findall('NEW', line)  # or search
list.append(line)   # to do something to later





I cannot 'get' to the following lines because I would need to get out of the
loop.


How about (untested):

additionalLines = 3
remainingLines = 0

for line in file:
  if 'NEW' in line or remainingLines:
mylist.append(line)
if not remainingLines:
  remainingLines = additionalLines
else:
  remainingLines -= 1

Emile



I did use enumerate and was wondering if I could use the line number, or
maybe I could use an re iterator.

Any advice would be much appreciated.

Thanks

paul


__ Information from ESET Smart Security, version of virus signature
database 4767 (20100113) __

The message was checked by ESET Smart Security.

http://www.eset.com


___
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] length of a string? Advice saught

2010-01-27 Thread Emile van Sebille

On 1/27/2010 2:25 PM Kirk Z Bailey said...

I wrote a program to let me edit web-pages without bothering with ftp;
it loads up a simple form with the page guts in it, and saves it through
another script. Until yesterday, EditMyPage worked fine. Alas, I had a
rather long winded page and it truncated it- completely omitted the last
1/4 of the original file, creating big problems. Looking everything
over, I can only conclude that somehow python 2.23 (ok, it's an old
server; shoot me, I'm poor) has a limit on a simple string variable. Can
I declare the variable as a long winded version and save the trouble, or
do AI need a witchdoctor here?



Also consider that closing a connection before the buffer is fully 
flushed can cause loss of data.


Emile

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


Re: [Tutor] hash value input

2010-01-29 Thread Emile van Sebille

On 1/29/2010 5:03 AM spir said...

Hello,

What actually is hashed when a data item is used a dict key? If possible, I 
would also like some clues on the method used to produce the hash value. (Maybe 
a pointer to the the relevant part of the python source, if clear and/or 
commented.)

The reason why I ask is the well known limitation for dict keys to be immutable 
data (same for sets, indeed). This seems to imply that the value itself is used 
as source for the hash func. Or am I wrong on this?
I recently discovered that Lua uses the data's address (read: id) as input to 
the hash func. This allows Lua tables (a kind of more versatile associative 
array) to use _anything_ as key, since the id is guaranteed not to change, per 
definition.
[Aside this consideration, hashing addresses ensures a constant type as input 
(so allows a specific efficient hash method) and the simplest possible one.]

So, how does python do this?



Start here...

http://effbot.org/zone/python-hash.htm

Emile

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


Re: [Tutor] imaplib command to delete messages

2010-02-27 Thread Emile van Sebille

On 2/26/2010 11:48 AM Bill Campbell said...

I've written a script to go through varions Sent folders on
IMAP servers to archive the messages on a central server using
imaplib to do the heavy lifting.  Perhaps I'm a bit thick, but I
have not been able to figure out how to delete messages in the
folders after processing them.  The imaplib documentation as lots
of ways to delete mailboxes (folders) and expunge messages from
folders, but I don't see anything about marking individual
messages as deleted.


I can't confirm it's still current, but this tip from Donn Cave might help:

It's only a flag, to identify the message that as you noted
will be actually deleted later by an expunge.


 ok, error = imapobject.store(number, 'FLAGS', '(\Deleted)')



(from 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfd041398e86c1fd/884359798ce1e025?q=python+imaplib+delete+message)


Emile



What am I missing?

Bill



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


Re: [Tutor] getting diagonals from a matrix

2010-03-03 Thread Emile van Sebille

On 3/2/2010 2:54 PM David Eccles (gringer) said...

I've managed to drum up some code to obtain a list containing joined diagonal
elements of a matrix (I'm making a word finder generator), but am wondering if
there's any better way to do this:


This works.  Lots of other ways would work too.  What would make one 
better than another?  Anyway, here's my take on it...


#

# setup so code snippet works properly
sizeW = 4
sizeH = 3
puzzleLayout = ['spam'] * (sizeW * sizeH)

# this allows the result to match your example

from string import digits,letters
puzzleLayout = (digits+letters)[:sizeW * sizeH]


# Starting with, say, an array with these indices:

# It might help to consider the indices numbers as that's what
# python does, so I've assumed these to be the values instead.

# 0 1 2 3
# 4 5 6 7
# 8 9 A B

# Looking at the index table above, note that all the results
# start on an edge and work diagonally from there.  I'll guess
# you found the back diags easier -- no messy 'in-the-same-row'
# problems -- but the forward diags are harder.  Note if we
# flype the table the forward diags can be built from the back
#
diag instructions

#FpuzzleLayout
# 8 9 A B
# 4 5 6 7
# 0 1 2 3

# so we'll build it once like this...
FpuzzleLayout = "".join(
  [ puzzleLayout[ii-sizeW:ii]
for ii in range(sizeW*sizeH,0,-sizeW)
] )

#So now, the only starting positions we need to worry about are
# on the left and top edge ignoring the start and end corners.
edge = (range(sizeW * sizeH,0,-sizeW)+range(sizeW-1))[2:]

# and to avoid any modular impact, we'll add a length constraint
lens = range(2,sizeH+1)+range(sizeW-1,1,-1)

# and do it
result = []

for ii,ln in zip(edge,lens):
  result.append(puzzleLayout[ii::sizeW+1][:ln])
  result.append(FpuzzleLayout[ii::sizeW+1][:ln])


# now add in the reversed results
for ii in result[:]:
  result.append("".join(reversed(ii)))

# and the corners
result.extend([puzzleLayout[0],
   puzzleLayout[-1],
   FpuzzleLayout[0],
   FpuzzleLayout[-1]])


#

Emile



# I want the following items for a back diagonal (not in square brackets):
# [-2],[3],8 (+5) | div 4 = -1, 1, 2
# [-1],4,9 (+5)   | div 4 = -1, 1, 2
# 0,5,A (+5)  | div 4 =  0, 1, 2
# 1,6,B (+5)  | div 4 =  0, 1, 2
# 2,7,[C] (+5)| div 4 =  0, 1, 3
# 3,[8],[D] (+5)  | div 4 =  0, 2, 3

# in other words, increase sequence by sizeW + 1 each time (sizeW - 1
# for forward diagonals), only selecting if the line you're on matches
# the line you want to be on

# back as in backslash-like diagonal
puzzleDiagBack = [(''.join([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos])) \
for i in range(-sizeH+1,sizeW)]
puzzleDiagBackRev = [(''.join(reversed([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos]))) \
for i in range(-sizeH+1,sizeW)]
# fwd as in forwardslash-like diagonal
puzzleDiagFwdRev = [(''.join([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos])) \
for i in range(sizeW+sizeH-1)]
puzzleDiagFwd = [(''.join(reversed([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos]))) \
for i in range(sizeW+sizeH-1)]

Cheers,
David Eccles (gringer)
___
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] Opening a dos exe

2010-03-11 Thread Emile van Sebille

On 3/10/2010 11:33 AM Armstrong, Richard J. said...

The problem comes in that the dos program requires three
inputs (input1.txt, input2.txt and input3.txt - see attached picture)
but I cannot find a way of getting this information to the dos program
from python. Any ideas?


I've sometimes written python code to create wsh (and other) scripts 
that I then run from within python.  WSH include a sendkeys command IIRC 
that works with dos/command/cmd windows.  There's likely ways to use the 
win32 api as well (win32api.keybd_event?).


I currently use a tool called macroScheduler from www.mjtnet.com just 
for the windows automation tasks I run into (scripted from within python).


There's also http://pypi.python.org/pypi/SendKeys/0.3, but at this point 
if I were to start over I'd look closely at 
http://www.rutherfurd.net/python/sendkeys/


HTH,

Emile

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


Re: [Tutor] Problems with iterations and breaking loops.

2010-03-17 Thread Emile van Sebille

On 3/17/2010 8:02 AM Karjer Jdfjdf said...

I'm having problems with iterations and loops. So I'm curious about the best 
Python-way to do iterations of lists (in if, while etc statements) and breaking 
of loops.

I have a list of tuples with 2 values. I want to perform calculations on all of 
these for each value in a range of values (e.g. 100 to 110).


list_of_tuples = [(90629, 4644), (90706, 4617), (90729, 4709)]

#start value
n = 100
#maximum value
nmax = 110

#First I create a list for the values
range_list = []
while n<  int(nmax+1):
 range_list.append(n)
 n = n + 1

print range_list



Look up the documentation for range -- there is an easier answer.



for i in range_list:
 for t in list_of_tuples:
 val1 = t[0]
 val2 = t[1]


you can also unpack a tuple like:

for val1,val2 in list_of_tuples:


 print "do stuff with\t" + str(val1) + '\t' + str(val2) + \
   '\tfor rangevalue\t' + str(i)

But I think that the rangelist is not needed and it can be done better (and 
faster for large quantities of data). I think it's better to have somethng like 
the code below. But I'm having problems with breaking the second loop and 
returning to the first loop. If I put in another while-statement befor the 
for-statement it stops after 1 run and it has to continue until the end of the 
range.






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


Re: [Tutor] Assertion Error

2010-03-18 Thread Emile van Sebille

On 3/17/2010 11:02 PM sitharak said...


I tried this statement to store in RDF form


This is too specialized for this list.  I couldn't find a dedicated news 
group for this project, but there is an IRC support channel -- see 
http://en.wikipedia.org/wiki/RDFLib#Support


HTH,

Emile




store=TripleStore()

But i'm getting this error

Traceback (most recent call last):
   File "", line 1, in
 store=TripleStore()
   File "C:\Users\Administrator\Desktop\TripleStore.py", line 13, in __init__
 super(TripleStore, self).__init__(backend=backend)
   File "build\bdist.win32\egg\rdflib\Graph.py", line 1008, in __init__
 super(BackwardCompatGraph, self).__init__(store=backend)
   File "build\bdist.win32\egg\rdflib\Graph.py", line 815, in __init__
 assert self.store.context_aware, ("ConjunctiveGraph must be backed by"
AssertionError: ConjunctiveGraph must be backed by a context aware store.

plz help



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


Re: [Tutor] Efficiency and speed

2010-03-19 Thread Emile van Sebille

On 3/19/2010 9:41 AM James Reynolds said...


OK, so starting here:

def mcrange_gen(self, sample):
lensample = len(sample)
nx2 = self.nx1
nx2_append = nx2.append
nx2_sort = nx2.sort
nx2_reverse = nx2.reverse
nx2_index = nx2.index
nx2_remove = nx2.remove
for s in range(lensample):
q = sample[s]
nx2_append(q)
nx2_sort()
nx2_reverse()
i = nx2_index(q)
nx2_remove(q)
yield i


First, the two lines:

for s in range(lensample):
q = sample[s]

variable s is never used again, so instead we'll do:

for q in sample:

Which renders lensample as unused, so throw out

lensample = len(sample)

We now have:


def mcrange_gen(self, sample):
nx2 = self.nx1
nx2_append = nx2.append
nx2_sort = nx2.sort
nx2_reverse = nx2.reverse
nx2_index = nx2.index
nx2_remove = nx2.remove
for q in sample:
nx2_append(q)
nx2_sort()
nx2_reverse()
i = nx2_index(q)
nx2_remove(q)
yield i


Now, let's see what's going on for each q. You append it to self.nx1 
(through the nx2 reference), then sort nx1, then reserve nx1, then scan 
for the new position of q, note the index, remove it from nx1, and yeild 
the index.  OK, so that way you find out between which two elements of 
nx1 the current q falls, and i becomes the bin.


So, how about something like (untested):

def mcrange_gen(self, sample):
self.nx1.sort() # now the bin boundries are in order
for q in sample:
ii = -1
for binlimit in self.nx1:
if qhttp://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why this Difference in Importing NumPy 1.2 vs 1.4?

2010-03-26 Thread Emile van Sebille

On 3/26/2010 12:44 PM Wayne Watson said...

I wrote a program in Python 2.5 under Win7 and it runs fine using Numpy 1.2 ,
but not on a colleague's machine who has a slightly newer 2.5. We both use IDLE
to execute the program. During import he gets this:

  >>>
Traceback (most recent call last):
File "C:\Documents and Settings\HP_Administrator.DavesDesktop\My
Documents\Astro\Meteors\NC-FireballReport.py", line 38, in
from scipy import stats as stats # scoreatpercentile
File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in
from stats import *
File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in
import scipy.special as special
File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, 
in
from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest
  >>>

Comments?


Version specific variations of packages with dedicated mailing lists are 
likely beyond the scope of this group.  I'd ask on the numpy list.


See http://www.scipy.org/Mailing_Lists

Emile




--
 Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

   (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
Obz Site:  39°  15' 7" N, 121°  2' 32" W, 2700 feet
 Poisoned Shipments. Serious illegal waste dumping may be
 occuring in the Meditrainean. Radioactive material,
 mercury, biohazards. -- Sci Am Mag, Feb., 2010, p14f.

  Web Page:



___
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] "IOError: [Errno 32] Broken pipe" when running python with cron (alternatives?)

2010-03-28 Thread Emile van Sebille

On 3/27/2010 5:45 AM Karjer Jdfjdf said...

I have made an extensive script that runs fine when started from the command 
line or IDLE.

When I try to run it with cron it keeps giving errors:


Often when I have trouble running scripts from cron it's because 
something in the environment is different.


Try restructuring the way you start the script from cron.  Say your cron 
entry looks like:


* * * * * someone /usr/local/bin/myscript.py

Then something like:

env > /usr/local/bin/myscript.sh
echo /usr/local/bin/myscript.py >> /usr/local/bin/myscript.sh
chmod a+x /usr/local/bin/myscript.py

and change cron to

* * * * * someone /usr/local/bin/myscript.sh

and see if that helps.

Emile





Error in sys.exitfunc:
Traceback (most recent call last):
   File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
 func(*targs, **kargs)
   File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
 h.flush()
   File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
 self.stream.flush()
IOError: [Errno 32] Broken pipe


The script has the following structure:
1. retrieves data from database 1
2. modifies the data
3. inserts the modified data in another database

In a previous script I solved this problem with directing the stdout and stderr 
to /dev/null, but doing this isn't possible because I use pickle and write some 
data to files. It seems to have anything to do with the stdout/stderr and cron, 
but after a lot of googling I don't have any clues how to fix this.

How can I solve this? Does anybody know how to solve this or is there a 
python-friendly alternative to cron that I can use.







___
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] automatic output file naming scheme

2010-03-28 Thread Emile van Sebille

On 3/28/2010 8:44 AM kevin parks said...

okay. I got the subprocess bit to work and i have os walk doing its walk. But 
now for something i did not think about until i started to think about how to 
fit these two bits to work together.

os walk is going to traverse my dirs from some given starting point and process 
files that it finds that fit my criteria. So i my case it will look for all 
sound files in a given directly structure and then call sox and do a 
conversion. This part i can already probably do just by combining the working 
code that i have … but now i need to have some kind of automagic naming scheme 
that creates an output file name that is based on the input name but is unique, 
either adding a number or suffix before the file extension, or even a time 
stamp. Since we want to create file names that are unique and not clobber 
existing files, but also will tells us something meaningful about how the file 
was created so that finding:

foo01.aif or foo.1.aif would yield something like foo-out01.aif or 
foo01-out.aif or something similar.

How can you do such a thing in python? is there some elegant way to take the 
input file name and combine it with some other string to create the output file 
name?


So you've really got two issues -- building a new name to use, and 
confirming it's unique.


You can build a new name with the replace method of strings or 
concatenating pieces of the new name using join or string interpolation.


os.path has some functions you may find helpful:






-kp


___
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] automatic output file naming scheme

2010-03-28 Thread Emile van Sebille

On 3/28/2010 8:44 AM kevin parks said...

okay. I got the subprocess bit to work and i have os walk doing its walk. But 
now for something i did not think about until i started to think about how to 
fit these two bits to work together.

os walk is going to traverse my dirs from some given starting point and process 
files that it finds that fit my criteria. So i my case it will look for all 
sound files in a given directly structure and then call sox and do a 
conversion. This part i can already probably do just by combining the working 
code that i have … but now i need to have some kind of automagic naming scheme 
that creates an output file name that is based on the input name but is unique, 
either adding a number or suffix before the file extension, or even a time 
stamp. Since we want to create file names that are unique and not clobber 
existing files, but also will tells us something meaningful about how the file 
was created so that finding:

foo01.aif or foo.1.aif would yield something like foo-out01.aif or 
foo01-out.aif or something similar.

How can you do such a thing in python? is there some elegant way to take the 
input file name and combine it with some other string to create the output file 
name?


So you've really got two issues -- building a new name to use, and 
confirming it's unique.


You can build a new name with the replace method of strings or 
concatenating pieces of the new name using join or string interpolation.


>>> sourcefile = "/home/someone/somedir/foo01.aif"

>>> sourcefile.replace(".aif","-001.aif")
'/home/someone/somedir/foo01-001.aif'

or

>>> sourcefile.replace(".aif","-%03d.aif" % sequence)


os.path has some functions you may find helpful:

>>> os.path.split(sourcefile)
('/home/someone/somedir', 'foo01.aif')
>>> os.path.basename(sourcefile)
'foo01.aif'
>>> os.path.splitext(sourcefile)
('/home/someone/somedir/foo01', '.aif')
>>> os.path.exists(sourcefile)
False

HTH,

Emile

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


Re: [Tutor] First extension

2010-03-28 Thread Emile van Sebille

On 3/26/2010 7:03 PM James Reynolds said...

Hello All,

I'm trying to write my first extension module, and I am getting the
following error in my command prompt and I was hoping you all could help me.


Hi James,

You'll probably get further asking on the setuptools support list. 
Checking http://pypi.python.org/pypi/setuptools I see links to the list 
at http://mail.python.org/pipermail/distutils-sig/


Those are the guys that will want this info and will most likely help 
you work through it.


HTH,

Emile




I have taken the following steps already:


1. My path is set for mingw/bin as well as python31.
2. There is a file in my disutils folder called disutils.cfg that says
[build] compiler = mingw32
3. The instructions in the 3.1 documentation state the following: "These
instructions only apply if you’re using a version of Python prior to 2.4.1
with a MinGW prior to 3.0.0 (with binutils-2.13.90-20030111-
   1. http://docs.python.org/py3k/install/index.html
   2. I am using Python 3.1 and the latest MinGW.
4. I tested gcc/mingw by doing C:\python31>gcc -shared pdv.c -o pdv.dll
and the test was succesful (or at least I was not given any errors while
doing the compile)
5. I searched on the internet and the closest thing I can find is the
following: http://bugs.python.org/issue4709


Below you will find the following

One, the error report
two,my setup.py file
three, the file I am trying to turn into a python extension module by
running the following two commands:

python setup.py build
python setup.py install


#1


Microsoft Windows [Version 6.1.7600]

Copyright (c) 2009 Microsoft Corporation.  All rights reserved.



c:\Python31\Lib\finance>python setup.py build


running build

running build_ext

building 'finance' extension

creating build

creating build\temp.win-amd64-3.1

creating build\temp.win-amd64-3.1\Release

C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python31\include

-IC:\Pytho


n31\PC -c finance.c -o build\temp.win-amd64-3.1\Release\finance.o

finance.c: In function `PyInit_finance':

finance.c:31: warning: implicit declaration of function `Py_Module_Create'

finance.c:31: warning: return makes pointer from integer without a cast

writing build\temp.win-amd64-3.1\Release\finance.def

creating build\lib.win-amd64-3.1

C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s

build\temp.win-amd64-3.1\Release\fin


ance.o build\temp.win-amd64-3.1\Release\finance.def -LC:\Python31\libs

-LC:\Pyth


on31\PCbuild\amd64 -lpython31 -lmsvcr90 -o

build\lib.win-amd64-3.1\finance.pyd


build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x2b): undefined

ref


erence to `_imp__PyArg_ParseTuple'

build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x5c): undefined

ref


erence to `_imp__Py_BuildValue'

build\temp.win-amd64-3.1\Release\finance.o:finance.c:(.text+0x74): undefined

ref


erence to `Py_Module_Create'

collect2: ld returned 1 exit status

error: command 'gcc' failed with exit status 1



c:\Python31\Lib\finance>




#2


from distutils.core import setup, Extension



setup(name = "finance",


   version = "1.0",

   ext_modules = [Extension("finance", ["finance.c"])])



#3

#include

#include



static PyObject *


pdv(PyObject *self, PyObject *args)

{

double value, rate, timex, denom, pdvx;

if (!PyArg_ParseTuple(args, "ddd",&value,&rate,&timex))

return NULL;

 denom = (double) pow ((1 + rate), (timex));

 pdvx = value / denom;

return Py_BuildValue("d", pdvx);

}

PyMethodDef pdvMethods[] = {

 {"pdv", pdv, METH_VARARGS, "Returns the Present Discounted Value given

of a single future value"},


 {NULL, NULL, 0, NULL}

};



static struct PyModuleDef financemodule = {


PyModuleDef_HEAD_INIT,

"finance",   /* name of module */

NULL, /* module documentation, may be NULL */

-1,   /* size of per-interpreter state of the module,

 or -1 if the module keeps state in global variables. */

pdvMethods

};



PyMODINIT_FUNC


PyInit_finance(void)

{

 return Py_Module_Create(&financemodule);

}




___
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] ask

2010-03-28 Thread Emile van Sebille
On 3/28/2010 10:28 AM Shurui Liu (Aaron Liu) said...
> You know what, I just don't understand this line:
> the name of the file containing the translated output is storyAmer.txt
> and it is to located.

It sounds to me like we wants you to read in the source(british)
version, swap in the american spellings, then write the resulting text
to storyAmer.txt

You might investigate the replace (1) method of strings and use it along
the lines of:

whole_thing = whole_thing.replace(british_spelling,american_spelling)

Also, look up the parameters for open (2), specifically those related to
enabling write mode for the new file.  And the write (3) method of an
open file.

(1)
http://docs.python.org/library/stdtypes.html?highlight=replace#str.replace
(2) http://docs.python.org/library/functions.html#open
(3) http://docs.python.org/library/stdtypes.html?highlight=write#file.write

You're almost there it seems.

HTH,

Emile


> 
> 
> I don't know what kind of translated output he need. I guess:
> 
> 1. the name of the file containing the translated output is *
> storyAmer.txt* and it is to located in a subdirectory off your cset1100py
> *assign19*, that is *./cset1100py/assign19/storyAmer.txt* directory named
> 
> 
> What kind of translated output do you want?
> 
> (1) A list of wrong words and a list of right words, like this:
> 
>  Wrong words in the text are: ..
> 
>   Right words should be: ..
> 
> 
> 
> OR
> 
> 
> 
> (2) The content of the text but has already been translated, like this:
> 
> 
> 
> I am really glad that I took CSET 1100.
> We get to *analyze* all sorts of real-world problems.
> We also have to *memorize* some programming language syntax.
> But, the *center* of our focus is game programming and it is fun.
> Our instructor adds *color* to his lectures that make them interesting.
> It is an honour to be part of this class!
> 
> 
> 
> 在 2010年3月28日 下午12:26,Shurui Liu (Aaron Liu)写道:
> 
>> Since English is not my native language, so I got confused by some
>> requirement of my assignment. I already done, just want to make sure what I
>> did is what the assignment required, thank you!
>>
>> BTW, I don't know how to do this:
>> If I want to fix some wrong words in a text file, how can I print out the
>> right/fixed text file? Like this:
>> My favor colour is blue. → My favourite color is blue. (Just print out the
>> right thing directly)
>>
>> Thank you!
>>
>> assignment:
>>
>> 1 Write a Python program named british2american.py
>>   that reads the contents of a text file, looks for occurances of uniquely 
>> British spelling, and translates the occurances into the acceptes American 
>> spelling.
>>
>> 1
>> Specifically, you will be looking for the following words: colour, analyse, 
>> memorise, centre and recognise. If found, they are to be
>> replaced with color, analyze, memorize, center and recognize.
>>
>> 1 The following is needed for you to write your program:
>>
>> 1 the name of the file containing the text to be translated is
>> storyBrit.txt
>>   and it is to be located in your cset1100py directory. Copy it from this
>> link<http://cset.sp.utoledo.edu/cset1100py/storyBrit.txt>
>>   to the designated location.
>>
>> 1 your program, british2american.py, should be located in your cset1100py
>>   directory on et791
>>
>> 1 the name of the file containing the translated output is storyAmer.txt
>>   and it is to located in a subdirectory off your cset1100py directory named
>> assign19, that is ./cset1100py/assign19/storyAmer.txt
>>
>> 1 the original file, storyBrit.txt, should be left unchanges
>> This is british2american.py
>> # Translate wrong British words
>> #Create an empty file
>> print "\nReading characters from the file."
>> raw_input("Press enter then we can move on:")
>> text_file = open("storyBrit.txt", "r+")
>> whole_thing = text_file.read()
>> print whole_thing
>> raw_input("Press enter then we can move on:")
>> print "\nWe are gonna find out the wrong British words."
>> # Press enter and change the wrong words
>> if "colour" in whole_thing:
>>  print "The wrong word is 'colour' and the right word is 'color'"
>> if "analyse" in whole_thing:
>>  print "the wrong word is 'analyse' and the right word is 'analyze'"
>> if "memorise" in whole_thing:
>>  print "the wrong word is 'memorise' and the right wor

Re: [Tutor] how to change some words in a text file

2010-03-28 Thread Emile van Sebille

On 3/28/2010 2:23 PM Shurui Liu (Aaron Liu) said...

Here's the thing, I wanna change some wrong words from a text file like this:

"I am a studaet." ->  "I am a student."

I have tried to use this command:
str = "I am a studaet."
newstr = str[0:8] + "ent"
print newstr


But the system said TypeError: 'type' object is unsubscriptable

What's wrong?

str is an unfortunate variable name choice -- try oldstr instead.  What 
you've done is often called shadowing.  I don't get the error here, but 
I'm guessing that's because I'm on 2.6 and you're on 3.x?


Emile

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


Re: [Tutor] How do I find information about a Python object.

2010-03-30 Thread Emile van Sebille

On 3/30/2010 8:23 AM Mike Baker said...

Random Googling shows that there are things like process identification
numbers available - such as proc.pid.  How do I find the other options?


try dir(proc) or help(proc) for starters...

Emile

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


Re: [Tutor] constructor

2010-04-04 Thread Emile van Sebille

On 4/4/2010 11:11 AM Shurui Liu (Aaron Liu) said...

Sorry, let me specify. I think comptuter will print out those two
sentences like this:



It's a little more interesting as you move forward from here.  This is a 
small step...


class Critter(object):
"""A virtual pet"""
def __init__(self,name):
print "A new critter has been born!"
self.name = name
def talk(self):
print "\nHi.  I'm %s, an instance of class Critter." % self.name


# main
crit1 = Critter('Polly')
crit2 = Critter('Spot')

crit1.talk()
crit2.talk()

HTH,

Emile

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


Re: [Tutor] create a wrapper for a C program

2010-04-06 Thread Emile van Sebille

On 4/6/2010 8:17 AM anjali nair said...

Hi,,,

I am new to python. My doubt is related to wrapping a C program with a
python script.. I am running Netperf for Network Performance Benchmarking.
The code is written in C and has an associated Makefile. I thought of
writing a Python script which should be able to run Netperf with the
associated arguments on executing it. Do I need to go for SWIG? I tried
invoking by using subprocess, but that did not work.

Can somebody help?



Looks like that's a command line tool -- you probably do want to use 
subprocess.  Show us what didn't work...


Emile

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


Re: [Tutor] ftp and python

2010-04-07 Thread Emile van Sebille

On 4/7/2010 6:51 AM Matjaz Pfefferer said...

I'm Py newbie and I have some beginners problems with ftp
handling.
What would be the easiest way to copy files from one ftp
folder to another without downloading them to local system?


The easiest is of course command line access on the hosting system.  FTP 
is essentially a file transfer protocol designed and inteded to move 
data between systems.


If what you're asking for is essentially how to do a cp (or copy on 
win??) from a remote machine you may want to look at "scp - secure copy 
(remote file copy program)"


HTH,

Emile

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


Re: [Tutor] Python Examples of processing MS Outlook

2010-04-21 Thread Emile van Sebille

On 4/16/2010 2:13 AM Peter Meagher said...

Does anyone have references to simple MS Outlook 2007
processing code that I could vulture for my purposes?  (The
code that I adapted was from an old Office 2000 vba text, so
the version 2007 may not be that essential to my purposes)


You may what to dig into the spambayes code -- see 
http://spambayes.sourceforge.net/


Emile

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


Re: [Tutor] the binary math "wall"

2010-04-21 Thread Emile van Sebille

On 4/21/2010 8:37 AM Lowell Tackett said...


So, I am setting my self very high standards of accuracy,
simply because those are the standards imposed by the project
I am adapting, and I can require nothing less of my finished project.


Then keep the source data in tenths (or 100ths or 1000ths) as whole 
numbers and only convert upon presentation and your calculations will 
always be accurate for the source measurements taken.


In accounting systems I've always keep dollar amounts in whole pennies 
for this same reason.


Emile



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


Re: [Tutor] Binary search question

2010-04-23 Thread Emile van Sebille

On 4/23/2010 7:05 AM Robert Berman said...

Hi,

Given a list, list1 having 100,000 non repeating, sorted integers ,  which of
the following methods is fastest to find an item fully understanding the item
may or may not be in the list: The binary search method which is the standard
search for such a small sample size, or the more python type statement is
  in list1?

What I am really trying to ascertain is how expensive or how efficient is  'is
  in list1'.



It's expensive enough that for a list this size I'd convert it to a dict 
and use in on that.  eg,


a = range(10)
d = dict(zip(a,a))

5 in d


Emile

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


Re: [Tutor] Binary search question

2010-04-23 Thread Emile van Sebille

On 4/23/2010 2:21 PM Alan Gauld said...


"Emile van Sebille"  wrote

It's expensive enough that for a list this size I'd convert it to a
dict and use in on that. eg,

a = range(10)
d = dict(zip(a,a))



Surely that would depend on how often you do the search? If its a one
off occurence I'd expect the overhead of zipping and converting to a
dict would outweight the savings?


Oh sure, but in practical terms, if it's a one-off situation who cares 
which you us?  For a one-off I'd just use in and not be concerned.




If the search was inside a loop however then I'd definitely agree.
Although I'd opt for a set rather than a dict...


Old habits...

Emile

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


Re: [Tutor] Binary search question

2010-04-23 Thread Emile van Sebille

On 4/23/2010 2:55 PM Hugo Arts said...

For completeness sake, on a 1 item list, using the in operator
takes *in the worst case* around 7 seconds.


:)

Well on my system checking for the last element of a 100k item list 
returns true almost upon hitting the enter key.  Surely 7 seconds for a 
list 1/10th the size is a typo?


Anyway, I think we're all on the same page.

Nice benchmarks, btw.

Regards,

Emile

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


Re: [Tutor] sqrt?

2010-04-25 Thread Emile van Sebille

On 4/24/2010 9:00 PM Steven D'Aprano said...

On Sun, 25 Apr 2010 01:00:50 pm Kirk Z Bailey wrote:

Importing math does not import a sqrt function.



Hmm... mine's there, but hey, it's easy to roll your own:

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> def sqrt(x): return x**.5
...
>>> sqrt(4)
2.0
>>> sqrt(12)
3.4641016151377544


Emile


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


Re: [Tutor] Modify inherited methods

2010-04-28 Thread Emile van Sebille

On 4/28/2010 3:20 AM Walter Wefft said...

spir ☣ wrote:

On Wed, 28 Apr 2010 07:53:06 +0100
Walter Wefft  wrote:



===
class MyDict0(dict):
pass
class MyDict1(dict):
def __init__(self, *args, **kw):
pass
class MyDict2(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
===

d0 = MyDict0(a=1) ; d1 = MyDict1(a=1) ; d2 = MyDict2(a=1)
print d0,d1,d2 # ==> {'a': 1} {} {'a': 1}



You reiterate my point. To say that dict.__init__ can be omitted in a
subclass's __init__ with no effect, is not a correct statement.



It wasn't the omitted case that exhibits the difference.  When 
sub-classing, any methods omitted defer to the parent's version so the 
init from the dict parent happened.


Emile

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


Re: [Tutor] Modify inherited methods

2010-04-28 Thread Emile van Sebille

On 4/28/2010 9:32 AM Walter Wefft said...

Emile van Sebille wrote:

On 4/28/2010 3:20 AM Walter Wefft said...

You reiterate my point. To say that dict.__init__ can be omitted in a
subclass's __init__ with no effect, is not a correct statement.



It wasn't the omitted case that exhibits the difference. When
sub-classing, any methods omitted defer to the parent's version so the
init from the dict parent happened.



"omitted in a subclass's __init__", ie. a *call* to the superclass's method



You're right.  Failure to read on my part.  Sorry.

Emile

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


Re: [Tutor] Python 2.5.4 - error in rounding

2010-05-21 Thread Emile van Sebille

On 5/21/2010 8:30 AM Neven Goršić said...

Thanks!
It's pity that Python has such unreliable functions so you never know in
advanced when you will hit new one ...


The problem is with floats, and all languages suffer similarly.  Most of 
us develop various techniques for avoiding these types of issues after 
being bitten.


Emile

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


Re: [Tutor] Recursion - Beginner

2010-05-28 Thread Emile van Sebille

On 5/28/2010 3:09 PM Shawn Blazer said...

Hello! I'm a high school student, and I'm having some trouble learning
recursion in my class...
For example:

Trace the sequence of recursive calls that glee(2,1) spawns:


I imagine what you'd need to do is manually follow the code for glee 
step-by-step when the values (2,1) are passed into it, so I'd write 
something like:


-pass---idolscrub--1stReturn--2ndReturn--3rdReturn
  1   2   1  n/an/a   pass2
  2   1   2  n/an/a   pass3
  3  -1   1

and continue until the the recursion completes.



def glee ( idol , scrub ) :
if idol == 0 :
return scrub
elif idol < 0 :
return scrub + glee ( idol + 10 , idol % 3 )
else :
return scrub + glee ( idol - scrub , idol % 3 )

Also, I'm not really sure what a question like this is asking...



To answer that you'd need the code for getLeaves, which isn't here.  It 
must have been provided to you somewhere...


Emile




getLeaves ( jenny )

[5,3,0,9]


getLeaves ( joshua )

[15,17,19,11,13]

I know its really simple, but I'm really new to this and I'd really
appreciate some help.
Thanks!




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


Re: [Tutor] Misc question about scoping

2010-06-03 Thread Emile van Sebille

On 6/3/2010 8:50 AM Tino Dai said...

Hi All,

 Is there a way to express this:
 isThumbnail = False
 if size == "thumbnail":
 isThumbnail = True

  like this:
  [ isThumbnail = True if size == "thumbnail" isThumbnail = False ]
  and the scoping extending to one level above without resorting to the
global keyword?



If by 'extending one level above' you mean 'outside the current scope', 
then yes if isThumbnail is mutable.  ie, something like:


isThumbnail = [False]

# create scope

def inner(size):
isThumbnail[0] = bool(size == "thumbnail")


inner('not thumbnail')
print isThumbnail


inner('thumbnail')
print isThumbnail

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


Re: [Tutor] Misc question about scoping

2010-06-04 Thread Emile van Sebille

On 6/4/2010 5:46 AM Tino Dai said...

 I'm at a point where I can do most things in Python (maybe) ,
now I'm looking to do them succinctly and elegantly. For instance, I
had about 10 - 15 lines of code to do this before with a bunch of
loops and if blocks, I distilled the product down to this:

answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \
   x.values(),Answer.objects.filter(fk_questionSet=1). \
   filter(fk_question=1).values('widgetAnswer').order_by(). \
   annotate(widgetCount=Count('widgetAnswer')



The first time there's a suspected problem with this code, you'll 
probably end up with a similar refactored set of 10-15 lines.  I'm sure 
because I've got code like that scattered throughout my codebase and 
that's what I end up doing.  The difference is that I rattle off the 
one-liners as part of the original coding effort, and only break it out 
when there's a need to -- I'm not striving to compact things into 
one-liners.


BTW, doesn't

   dict(map(lambda x: (str(x[1]),x[0]),map(lambda x:x.values()

simply map the values of a dict back into a dict?

Emile






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


Re: [Tutor] What's the catch with ZopeDB?

2010-06-11 Thread Emile van Sebille

On 6/11/2010 12:42 PM Knacktus said...


So, has anyone experience with ZopeDB? Are there some drawbacks I should
be aware of before getting a book and dive in? (It sounds too good ;-))



I've been using it as part of a couple applications I wrote 10 years ago 
that use zope.  I'm not sure how my comments relate to non-zope usage or 
the recent versions so YMMV.


The two things that bother me most are that without packing the 
database, it grows -- apparently without bound.  It'll pack a 1Gb source 
DB down to 32Mb.  Also, I once experienced corruption and found it 
impossible to recover the lost data, and I've a fair amount of 
experience recovering lost data even from unmountable partitions and 
drives that don't power up.


I'm not opposed to the idea so I think I'd try it out, but those are 
issues I'd watch for.


Emile



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


Re: [Tutor] Repeat function until...

2010-06-23 Thread Emile van Sebille

On 6/23/2010 6:51 AM Steven D'Aprano said...

# untested
def call_again(n, func, *args):
 """call func(*args) every n seconds until ctrl-D"""
 import time
 try:
 while 1:
 start = time.time()
 func(*args)
 time.sleep(n - (time.time()-start))


Watch out for this -- you may want to do

  time.sleep(n - max(0,(time.time()-start)))

to avoid passing sleep a negative number which causes the big sleep...

Emile

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


Re: [Tutor] Use flag to exit? (OT - PEP 8 Gripe)

2010-06-25 Thread Emile van Sebille

On 6/25/2010 1:33 AM ALAN GAULD said...

Copy and pasting is a PITA.


Why would you want to copy and paste?


Because it makes it easy to work on code.  My preferred editor (TextPad) 
allows block selection of indented text such that I can copy and paste 
functions and methods into the python CLI and work with them there.  I 
find it very easy when developing to keep the CLI open for this purpose 
and interactively test as I write.  Unfortunately, PEP 8 doesn't support 
this use case as once the blank lines separating methods are pasted in, 
your class definition is complete.  So I either put hash marks in or 
leave the blank lines out...


Emile

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


Re: [Tutor] Use flag to exit? (OT - PEP 8 Gripe)

2010-06-25 Thread Emile van Sebille

On 6/25/2010 9:08 AM Steve Willoughby said...

On 25-Jun-10 08:23, Emile van Sebille wrote:

On 6/25/2010 1:33 AM ALAN GAULD said...

Copy and pasting is a PITA.


Why would you want to copy and paste?


Because it makes it easy to work on code. My preferred editor (TextPad)
allows block selection of indented text such that I can copy and paste
functions and methods into the python CLI and work with them there. I


If what you're trying to do is a PITA, that should raise two questions:



Points taken, but understand that the OP termed it a PITA, from which 
Alan asked why cut 'n paste.  I don't find it a PITA at all and am quite 
comfortable with my approach (editor choice being a religious issue 
after all).  My gripe is only that complying with PEP 8 is not possible.


Regards,

Emile

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


Re: [Tutor] endless loop

2010-07-05 Thread Emile van Sebille

On 7/5/2010 8:31 AM prasad rao said...

hi
   I am trying problem 6 in projecteuler.org.
What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?


def rr(z,m=1):
   q=lambda n:m%n==0
   s=lambda False : 0
   a=filter(s,map(q,range(1,z)))
   if not a:
   m+=1
   rr(z,m)
   else:return m

This code is going into endless loop.



You don't show us how you're invoking this function, but it seems to me 
the result of passing a terminally false function result (s is always 
false) into filter will always result in [] (so a is always false) and 
will thereby cause the else clause never to be reached.


Emile


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


Re: [Tutor] Help return a pattern from list

2010-07-05 Thread Emile van Sebille

On 7/5/2010 4:19 PM Alan Gauld said...


But for the specific case of file extensions the os.path.splitext() is
a better solution.





If, as the names suggest, the source is the file system, then I'd reach 
for glob.


Emile


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


Re: [Tutor] module for fingerprint and pictures

2010-07-12 Thread Emile van Sebille

On 7/12/2010 12:22 PM Dipo Elegbede said...

Hello people,

I am working on an interface that is supposed to interact with a webcam and
capture pictures into a database and also fingerprint from a fingerprint
hardware.


I've done this a couple different times now, one time using panasonic 
webcams pushing out ftp images once a second and capturing validated 
fingerprints on a biometric timeclock from acroprint.




Is there any python module or library I can work with.


Not that I found.



I need suggestions, assistance and information where necessary.

To be truthful, I need to do a demo for that app and then go commercial if
my project impresses the client.


What's the app going to do?

Emile


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


Re: [Tutor] LOCATION ISSUES

2010-07-12 Thread Emile van Sebille

On 7/12/2010 11:13 PM Dipo Elegbede said...

Hello All,

Kindly help me with the location for the files created by this codes.

I have already compiled the codes and it has no error.

I copied the code from the following url:
http://www.pythonware.com/library/pil/handbook/image.htm

This is supposed to create thumbnails of picture in the directory where I
saved my file.


Which is what it will do when python is started from that directory.

How are you starting python?

Emile

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


Re: [Tutor] LOCATION ISSUES

2010-07-13 Thread Emile van Sebille

On 7/12/2010 11:52 PM Dipo Elegbede said...


Which is what it will do when python is started from that directory.

I actually found the copies that were made by the code in the same
directory but found out that they all had a .thumbnail ext which would not
open and it is understandable.

I have however chaged that part of the code to carry .jpg hoping to let it
make thumbnails with jpg extensions.



How are you starting python?



I am new to python.


:)  What I meant to ask was what are you typing in to actually start 
python and execute your code?  You need to open a command window, 
navigate to the directory where the images are stored, and start python 
from there so that glob will find the files.


HTH,

Emile

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


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 8:31 AM Corey Richardson said...

I was under the impression that when you define a function, it doesn't
try to evaluate anything yet. If I had called the function before I
defined the variable, I would understand, but I haven't.



The difference is in understanding what's executed and what's deferred.

Consider the following:

#-Start File test.py-
def test():
  print "in def test"

class Test:
  print "in class Test"
  def __init__(self):
print "in class Test.__init__"

print "in __main__"

test()
t = Test()

#-End File test.py-

Output:

in class Test
in __main__
in def test
in class Test.__init__

-

As you can see, the print statements at the class level are executing 
when encountered, but the prints in defs only when executed.


HTH,

Emile


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


Re: [Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Emile van Sebille

On 7/14/2010 8:46 AM Eric Hamiter said...

Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the following:


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
 if line in aisle_one:


So it's failing this test.


print "success"
 else:
print "no joy"


Try adding some debugging code here, maybe changing the print to:
  print "no joy matching %s" % line

Then read up on readlines and string.strip.

HTH,

Emile


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


Re: [Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Emile van Sebille

On 7/14/2010 9:22 AM Eric Hamiter said...

Fantastic! I have this, which now works. Is there a better place to put
string.strip?


I might make the changes below, but there's nothing wrong with the way 
you've got it.




aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")


grocery_list= [ item.strip()
   for item in open("grocery_list.txt", "r").readlines() ]


for line in grocery_list.readlines():


for item in grocery_list:


 if line.strip() in aisle_one:


if item in aisle_one:


print "success! i found %s" % line
 else:
print "no joy matching %s" % line
grocery_list.close()




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


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 9:33 AM Corey Richardson said...

Hmm..If I add a few debugging lines like that into my code, I get this:


The point was that statements in a class at class level (ie, not in 
defs) are executed sequentially and expect referenced variables to exist 
(ie, defined somewhere 'above' the current statement) -- there is no 
forward peeking going on.  Statements within def's (think 'deferred 
execution' if it helps) expect that the variables referred to will exist 
by the time the def is invoked.


Python executes code top to bottom.  def's create an executable object 
and defers execution until invoked.  Other statements execute when 
encountered.  The statements in your class that start


top = tk.Tk()
thru...
F.mainloop()

execute in top-down sequence as they are outside of def's.  That's your 
problem.  It's unusual to have that done within a class definition and I 
expect it shouldn't be there.


HTH,

Emile

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


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 11:11 AM Serdar Tumgoren said...

But I was wondering (for my own
edification), can anyone point to the portion of the docs that clearly
spells out the order of execution (top to bottom, classes vs. functions,
etc.).


I found this in the tutorial in the modules section:
  ( see http://docs.python.org/tutorial/modules.html )

   "A module is a file containing Python definitions and statements."

Ergo, stuff that executes and stuff that defines.

Further clarification provided:
"""A module can contain executable statements as well as function 
definitions. These statements are intended to initialize the module. 
They are executed only the first time the module is imported somewhere."""


... and a Footnote:
"""In fact function definitions are also statements that are executed; 
the execution of a module-level function enters the function name in the 
modules global symbol table."""


The same applies to the class namespaces created and the contained defs.

As to the execution order, that's apparently buried in the c sources of 
the scanner and tokenizer bits.  I didn't see anything more specific 
than "stream processing" and "*file" pointers hinting at serial 
processing of the source py file.



I also found this interesting (but possibly not to newbies :) :
  http://www.shinetech.com/attachments/108_python-language-internals.pdf

Emile

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


Re: [Tutor] How to deal failed function and 0xDEADBEEF type errors...

2010-07-15 Thread Emile van Sebille

On 7/15/2010 11:07 AM Sean Carolan said...


Try to print it and it throws this error:

print testNestEggFixed




That's not an error -- that's what testNestEggFixed -- a function 
located at 0x0214D5F0.  If you intended to _execute_ the function, add 
parens and the appropriate parameters to your print statement.


HTH,

Emile

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


Re: [Tutor] append, list and variables

2010-07-15 Thread Emile van Sebille

On 7/15/2010 11:32 AM Mary Morris said...

Hi,
I'm working on a program that parses through all of our source code at my
office and i need to get my code to print a list of the decorators.  I used
a find(@) to locate all the decorators, but I need to assign them to a
variable somehow to get it to print a list. How do I do this? How do I
assign a variable to all the indexed strings after the @ symbol?



So, decorator lines start with an '@'.  Source files end in '.py'.

Pseudo code could be:

initialize result container

with each sourcefilename in globbed list:
  for eachline in opened(sourcefilename):
if line.startswith('@'):
  append [sourcefilename, line] to result

# print it

for eachline in result:
  print eachline
----

Hope this gets you going,

Emile




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


Re: [Tutor] append, list and variables

2010-07-16 Thread Emile van Sebille

On 7/16/2010 8:37 AM Mary Morris said...

Thanks-that helps a lot.
The only question I have about your pseudocode is what the 'initialize
result container' does.  I'm pretty new to python and scripting in general
so I'm still trying to figure everything out.


It creates an empty data storage container for use within the processing 
loop -- if it wasn't defined before use, you'd get an error the first 
time you tried to append to it.  There's some good info in the tutorial 
-- see http://docs.python.org/tutorial/datastructures.html for details.


Emile





On Thu, Jul 15, 2010 at 12:58 PM, Emile van Sebille  wrote:


On 7/15/2010 11:32 AM Mary Morris said...

  Hi,

I'm working on a program that parses through all of our source code at my
office and i need to get my code to print a list of the decorators.  I
used
a find(@) to locate all the decorators, but I need to assign them to a
variable somehow to get it to print a list. How do I do this? How do I
assign a variable to all the indexed strings after the @ symbol?



So, decorator lines start with an '@'.  Source files end in '.py'.

Pseudo code could be:

initialize result container

with each sourcefilename in globbed list:
  for eachline in opened(sourcefilename):
if line.startswith('@'):
  append [sourcefilename, line] to result

# print it

for eachline in result:
  print eachline


Hope this gets you going,

Emile




___
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



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


Re: [Tutor] Decorator listing

2010-07-27 Thread Emile van Sebille

On 7/27/2010 1:11 PM Mary Morris said...

I'm writing a program with python that compiles a list of decorators from my
company's source code.  I'm new to python and need help with the following:
I'm trying to make the program find ".com" in any lines and not include them
in the list of decorators that gets returned.  THis is because I had the
program look for the @ symbol to find the decorators and it returned email
addresses in the list.


You can probably sidestep this issue by looking for the @ symbol in the 
first non-whitespace position in the line, rather than in any position 
of the line.


IE, instead of something like:

  if "@" in line:

...try something more like:

  if line.strip().startswith("@"):


This way you won't pick up the email addresses at all, and won't 
subsequently need to filter them out of your results set.


HTH,

Emile



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


Re: [Tutor] Distributing Python Code for Commercial Porpoises?

2010-08-06 Thread Emile van Sebille

On 8/6/2010 10:51 AM Wayne Watson said...

Yes, porpoises was a (old) pun.

Back in Feb. I raised a question related to Subject. I just wanted to
know if Python code could be compiled in some sense. Robert Berman
pitched in with some help. Although I was making progress, I put it off
for a future date. I really don't want to get into py2exe here, but am
wondering if there are Python vendors who in some way sell their product
in compiled form?



I think you're making it harder.  Go to your partners site, build an 
appropriate base environment, document and leave instructions on where 
to put new *.py modules you send him, run through it, and you're done.


A little education will likely go a lot further than delving deeper into 
heavier technologies in an attempt to 'simplfy'.


HTH,

Emile

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


Re: [Tutor] Distributing Python Code for Commercial Porpoises?

2010-08-07 Thread Emile van Sebille

On 8/7/2010 8:16 AM Wayne Watson said...


An easy way out might be to ask him to uninstall Python and any modules
like numpy. I'm not even sure how to do that.


More reasons to start out simpler.  Have your partner install one of the 
remote access tools (GoToMyPC, LogMeIn, VNC, etc) and do the work 
yourself.  And then install the changes yourself.  Again, the practice 
on both systems will probably benefit you more at this stage than 
advanced technologies.  Familiarizing yourself with the actions 
automated installation is required to perform will help you understand 
the tools better, and provides clues debugging the results when it 
doesn't quite work right. Don't make it any harder than it needs to be. 
Ultimately, a single byte update to a .py file shouldn't be any more 
involved than replacing the old file with the new revised file.


I'd use the links below -- there doesn't yet seem to be a 2.7 compatible 
released version of scipy yet, so this lists the most current compatible 
set of installable binaries.


As others have mentioned, don't use idle as you're doing.  Give 
pythonwin (included with the activestate distribution) a try.  Or try 
one of the free versions of Komodo or Wing.


HTH,

Emile



http://downloads.activestate.com/ActivePython/releases/2.6.5.14/ActivePython-2.6.5.14-win32-x86.msi

http://sourceforge.net/projects/numpy/files/NumPy/1.5.0b1/numpy-1.5.0b1-win32-superpack-python2.6.exe/download

http://sourceforge.net/projects/scipy/files/scipy/0.8.0/scipy-0.8.0-win32-superpack-python2.6.exe/download

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


Re: [Tutor] import errors

2010-08-11 Thread Emile van Sebille

On 8/11/2010 8:48 AM Pete said...

Hi,

A common line I've seen in Python code I come across is:

#!/usr/bin/python
import os
import sys
import errors



... so there seem to be more than one 'errors.py' - one for the email module, 
one for Skype4Py, etc.

How does the interpreter know which one to import?


Importing looks in directories in sequence as held in sys.path

Python 2.4.3 (#1, Sep  3 2009, 15:37:12)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> for ii in sys.path: ii
...
''
'/usr/lib/python24.zip'
'/usr/lib/python2.4'
'/usr/lib/python2.4/plat-linux2'
'/usr/lib/python2.4/lib-tk'
'/usr/lib/python2.4/lib-dynload'
'/usr/lib/python2.4/site-packages'
'/usr/lib/python2.4/site-packages/Numeric'
'/usr/lib/python2.4/site-packages/gtk-2.0'


HTH,

Emile

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


Re: [Tutor] Need help understanding output...

2010-08-11 Thread Emile van Sebille

On 8/11/2010 2:04 PM Laurens Vets said...

Hello list,

I'm learning Python and I'm currently facing an issue with a small
script I'm writing.

I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4,
5 & 6. However, I cannot have more than 2 numbers which are the same
next to each other. I came up with the following (Please ignore the fact
that I'm trying to avoid an IndexError in a stupid way :)):

import random
reeks = []
while len(reeks) <= 1:
number = random.randrange(1, 7, 1)
reeks.append(number)

while len(reeks) <= 29:
nummer = random.randrange(1, 7, 1)
if nummer != reeks[-1] and nummer != reeks[-2]:
reeks.append(nummer)
print reeks

So far so good (I think). From what I can see from the output, I get 30
numbers, without more than 2 being the same next to each other.

However, I wanted to look deeper in the above script and I created the
following:

import random
iteraties = 5
cijferreeks = 6
aantal_cijfers = iteraties * cijferreeks
reeks = []
while len(reeks) <= 1:
nummer = random.randrange(1, cijferreeks + 1, 1)
print 'Nummer: ', nummer
print 'Reeks: ', reeks
reeks.append(nummer)
print '\n'

while len(reeks) <= aantal_cijfers:
nummer = random.randrange(1, cijferreeks + 1, 1)
print 'Nummer: ', nummer
print 'Voorlaatste vd reeks (-2): ', reeks[-2]
print 'Laatste vd reeks (-1): ', reeks[-1]
print 'Reeks: ', reeks
if nummer != reeks[-1] and nummer != reeks[-2]:


You're testing here if nummer is niet gelijk van _both_ vorige twee 
nummers, maar je wil testen als het niet gelijk is van _either_ nummer:


if nummer != reeks[-1] _or_ nummer != reeks[-2]:

For then it is true that

   nummer == reeks[-1] and nummer == reeks[-2]

You should review/create or/and truth tables to determine the validity 
of your logical tests.  Also, particularly when starting, it is known 
that negatives often lead to confusion, with use of multiple negatives 
leading to even more confusion.  Next time, try eliminating the 
negatives and look for a positive test when you have this kind of issue. 
 Then you might have written:


if nummer == reeks[-1] and nummer == reeks[-2]:
  print "it's the same as the prior two"
else:
  reeks.append(nummer)

HTH,

Emile





reeks.append(nummer)
else:
print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1],
'&', reeks[-2], '!'
print '\n'
print reeks

When I run that, I can see there's something wrong with my if statement,
it triggers the else condition even when the 2 previous numbers in my
list are not the same... I'm not sure what is happening here...



___
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] Question about Dictionaries

2010-08-16 Thread Emile van Sebille

On 8/16/2010 10:44 AM Chorn, Guillaume said...

Hi All,

I know that I can look up the value for a particular key in a
dictionary, but can I look up the key associated with a particular
value?


Yes.  But you'll need to implement it.  There are likely modules out 
there that'll do this, but it'd take more time to look up and evaluate 
than to simply write and implement exactly what you need.



I understand that this could be problematic from the standpoint
of multiple keys having the same value, but even then I feel like Python
could just return a list of keys with that value.



So, in untested code you'd have a function something like:

result = []

for ky, val in dict.items():
  if val == targetval:
  result.append(ky)
return result

If you need repeated access such that iterating over a large dict 
frequently impacts performance, you could subclass dict and maintain a 
second index allowing instant access to the keys associated with a 
specific value.


HTH,

Emile



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


Re: [Tutor] Moving from Python 2.5.4 to 2.5.2?

2010-08-16 Thread Emile van Sebille

On 8/16/2010 2:41 PM Luke Paireepinart said...

The core issue here is: are there actually issues exacerbated by the
difference in Python versions?  If so, which issues?  There shouldn't
be hardly any reason to force you all to maintain the exact same
python version, especially if you're in the same sub-version (2.5)



I agree.  2.5.4 is a bug release for the 2.5 series and by decree may 
not introduce backward incompatibilities of any kind.  If there's a 
compatibility issue, please provide details so it can be verified as it 
ought to be reported.


Emile

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


Re: [Tutor] Question about Dictionaries

2010-08-16 Thread Emile van Sebille

On 8/16/2010 4:12 PM Huy Ton That said...

What do you mean by subclass?





If you need repeated access such that iterating over a large dict frequently
impacts performance, you could subclass dict and maintain a second index
allowing instant access to the keys associated with a specific value.

HTH,

Emile




Something along these lines:

class myDict(dict):
def __init__(self):
self.altKeys = {}
def __setitem__(self,ky,val):
self.altKeys[val]=ky
return dict.__setitem__(self, ky,val)
def lookup(self,ky):
return self.altKeys[ky]


a = myDict()

a[1] = 111
a[2] = 222
a[3] = 333

a[3]

a.lookup(333)


Emile

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Emile van Sebille

On 8/19/2010 7:51 AM Pete said...

Hi,

I've been reading up on list comprehensions lately, all userful and powerful 
stuff - trying to wrap my brain around it :)

As the examples all seem to relate to lists, I was wondering if there is an 
elegant similar way to apply a function to all keys in a dictionary?

(without looping over it, of course)


Just fyi, as it sounds you may not understand.  List Comprehensions loop 
over the list.  There's no other magic going on that avoids that.


result = [ ii for ii in lst if cond ]

is just shorthand for

result = []
for ii in lst:
  if cond:
result.append(ii)

Emile


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


[Tutor] Overloaded Brackets

2010-08-20 Thread Emile van Sebille

Hi All,

I just had reason the write the following:

itemCodes = [UPCxref['0'+xx[:10]][0] for xx in itemUPCs]

... and it occurred to me exactly how overloaded square brackets are.

This is certainly not something you want to see as a beginning python 
programmer, but I thought it might be an interesting example to parse.


Regards,

Emile


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


Re: [Tutor] monodevelop 2.2

2010-08-21 Thread Emile van Sebille

On 8/21/2010 12:37 PM Thomas said...

I was wondering if someone could tell me if you can use the gui designer
in monodevelop 2.2+ with python.



Searching groups.google.com with "use the gui designer in monodevelop 
2.2+ with python" yields a first hit that says "I just used MonoDevelop 
2.2 for Python under Ubuntu. IT'S AMAZING!"


http://www.daniweb.com/forums/thread286328.html

So, sounds like a yes to me.

Emile


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


Re: [Tutor] Function object

2010-08-25 Thread Emile van Sebille

On 8/25/2010 9:56 AM Daniel said...

Hello again, seems like in my journey to learn Python I have stumbled into
another problem regarding understanding a concept- function object. As I
said, I do not understand what a function object is, what it does, and what
can I do with it? I'm currently reading Think python, but the book is not
clear for me. Python is my first programming language.
Please, can you give me some examples and if it is possible can you explain
in a more beginner orientated way?


Generally speaking, everything in python is an object.  As such, objects 
have methods and attributes.  At a certain level for certain projects, 
manipulating code objects helps solve problems.


Here's a simple example.

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit 
(Intel)] on

win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def test(ii): print "my name is %s" % ii.func_name
...
>>> def test1(ii): print "my name is %s" % ii.func_name
...
>>> def test2(ii): print "double ii is %s-%s" % (ii,ii)
...
>>> for funcobj in (test1,test2): funcobj('spam')
...
single ii is spam
double ii is spam-spam
>>>for funcobj in (test1,test2): test(funcobj)
...
my name is test1
my name is test2

Once defined, code is an object.  try dir(test) on the above.

HTH,

Emile

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


Re: [Tutor] Function object

2010-08-25 Thread Emile van Sebille

On 8/25/2010 10:56 AM Emile van Sebille said...

 >>> def test1(ii): print "my name is %s" % ii.func_name
...


Oops -- my bad editing  s/b or once was:

def test1(ii): print "single ii is %s" % ii


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


Re: [Tutor] exercise problem

2010-08-26 Thread Emile van Sebille

On 8/26/2010 12:02 PM Roelof Wobben said...


Hello,

I have this exercise:

Lists can be used to represent mathematical vectors. In this exercise and 
several that follow you will write functions to perform standard operations on 
vectors. Create a file named vectors.py and write Python code to make the 
doctests for each function pass.
Write a function add_vectors(u, v) that takes two lists of numbers of the same 
length, and returns a new list containing the sums of the corresponding 
elements of each.


def add_vectors(u, v):
 """
   >>>  add_vectors([1, 0], [1, 1])
   [2, 1]
   >>>  add_vectors([1, 2], [1, 4])
   [2, 6]
   >>>  add_vectors([1, 2, 1], [1, 4, 3])
   [2, 6, 4]
   >>>  add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
   [13, -4, 13, 5]
 """

add_vectors should pass the doctests above



I think that u is the name of the new list and v is the number which represent 
the number which must be eveluated.


No.  u,v are the parameters names for the two lists of numbers of the 
same length.  So in the example add_vectors([1, 0], [1, 1]), u will take 
on the value [1, 0] and v the value [1, 1].


HTH,

Emile






Is this right or do I mis understood the exercise ?



Roelof






___
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] Serial communication ...

2010-09-13 Thread Emile van Sebille

On 9/13/2010 8:36 AM Markus Hubig said...

Hi @all!

I'm about to write a class for serial communication on Win32 and Linux which
provides a method called "talk" to send something over the serial line,
wait for
the answer and returns it. My problem is, that I don't know how long the
answer
will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

1. Will this work on Win32 (with select)?
2. Should I better use twisted.internet.serialport?
3. Will self.read(260)block until it reads the full 260 bytes?



You're subclassing Serial -- the answers to your questions depend on 
what that is.  So, what is it? Does it support windows? Has anyone 
compared/contrasted it to twisted.internet.serialport?  What does its 
read do?  And finally, perhaps, does it have it's own support 
group/list?  You'll probably get better answers directly from there than 
here.


HTH,

Emile





class SerialDevice(Serial):

 def __init__(self,port):
 Serial.__init__(self)
 self.port = port
 self.baudrate = 57600
 self.bytesize = EIGHTBITS
 self.parity = PARITY_ODD
 self.stopbits = STOPBITS_TWO
 self.timeout = 0
 self.xonxoff = 0
 self.rtscts = 0
 self.dsrdtr = 0
 self.open()
 self.flush()

 def _write(self, packet):
 fileno = self.fileno()
 while True:
 readable, writeable, excepts = select( [], [fileno], [], 0.2 )
 if fileno in writeable:
 time.sleep(0.1)
 length = self.write(packet)
 break
 return length

 def _read(self):
 fileno = self.fileno()
 while True:
 readable, writeable, excepts = select( [], [fileno], [], 0.2 )
 if fileno in readable:
 time.sleep(0.1)
 packet = self.read(260)
 break
 return packet

 def talk(self, packet):
 self._write(packet)
 responce = self._read()
 return responce

Thank you, Markus




___
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] What's the best way to ask forgiveness here?

2010-09-13 Thread Emile van Sebille

On 9/13/2010 11:31 AM Brian Jones said...

I've been coding Python long enough that 'asking forgiveness instead of
permission' is my first instinct, but the resulting code is sometimes
clumsy, and I wonder if someone can suggest something I'm missing, or at
least validate what's going on here in some way.

What I'm trying to do is write a file to a directory. However, the directory
may not exist the first time I try to write a file there, so I'm going to
first try to write the file, and if I get an exception, create the directory
(er, *try* to), and *then* write the file there. Here's my first shot at the
code:

 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 # directory doesn't exist. Try to create it.
 try:
 os.makedirs(picfile_fullpath)
 except OSError as oserr:
 logging.error("Can't create file path: %s (%s)" %
(picfile_fullpath, oserr))
 else:
 # Created dir, now write file.
 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 logging.error("Bailing. Couldn't save file %s (%s)" %
(picfile_fullpath, err))
 return False


Unless this is in a tight loop, I think I'd write:

try:
os.makedirs(picfile_fullpath)
try:
self.save_file(picfile_fullpath, picdata)
return True
# all/only error handling code follows.
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

return False
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

return False

which eliminates the duplicated save_file step.



Doesn't this seem less readable than the 'ask permission' equivalent? I
think it does, but in this case asking permission for every single operation
when the dir will only need to be created a single time (and then may be
written to several hundred times) is pretty wasteful.


Agreed -- if it's in a loop, you'd want to only check once.  Of course, 
if the directory is eg an nfs share, continued access could be an issue.


HTH,

Emile




I suppose I could set some sentinel variable and check for it in a while
loop, but then I need some other scaffolding code to make sure I don't
infinitely loop trying to create the directory, and probably some other
stuff I'm forgetting, so it strikes me as being just as messy.

Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian






___
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] Comparing two lists

2010-09-16 Thread Emile van Sebille

On 9/16/2010 11:27 AM Michael Powe said...

Hello,

I have two lists.

alist = ['label', 'guid']

blist = ['column0label', 'column1label', 'dimension0guid',
'description', 'columnid']



Something like this?

>>> [ ii for jj in alist for ii in blist if jj in ii ]
['column0label', 'column1label', 'dimension0guid']

Emile

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


Re: [Tutor] Why are arguments sometimes on the left side?

2010-09-20 Thread Emile van Sebille

On 9/20/2010 7:16 AM Michael Scharf said...

Why is it
list0.extend(list1)
and not
extend(list 0, list1)
or
stri0 = stri0.strip()
and not
stri0 = strip(stri0)
Why have arguments on the left side at all, when usually the dot notation
left to right implies a hierarchical relation: file.class or class.method
etc.



You can also have it your way...

>>> def extend(*args):
... try:
... args[0].extend(*args[1:])
... except:
... raise AttributeError
...
>>>
...
>>>
>>> a = []
>>> a.extend([1,2,3])
>>> a
[1, 2, 3]
>>> extend(a,[4,5,6])
>>> a
[1, 2, 3, 4, 5, 6]
>>>


Emile


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


Re: [Tutor] Why are arguments sometimes on the left side?

2010-09-20 Thread Emile van Sebille

On 9/20/2010 9:54 AM Joel Goldstick said...

That's pretty creative I think, but not sure its quite on the mark for
beginners? ;)


With this one fitting into context so easily, it seemed appropriate.

Emile

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


Re: [Tutor] trouble with a small Tkinter example

2010-09-21 Thread Emile van Sebille

On 9/21/2010 1:50 PM Chuck Mayers said...

Hello,

I'm having trouble with this small example program:

http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29

When I run it, I only get a blank grey window. I'm running Python 2.6 under
Windows XP.


It looks like they've got you assembling the program from bits and 
pieces as it's presented and reviewed.  Can you post your program as 
you've reassembled it so we can see what's actually coded?


Emile

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


Re: [Tutor] trouble with a small Tkinter example

2010-09-21 Thread Emile van Sebille

On 9/21/2010 1:50 PM Chuck Mayers said...

Hello,

I'm having trouble with this small example program:

http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29

When I run it, I only get a blank grey window. I'm running Python 2.6 under
Windows XP.

If there's a problem with the code, I can't see it... it seems like it
should work. Can anyone else try this and see if it works for them?


If I stick this line in before the loop, it does draw a red line, so I know
my copy of Python/Tkinter is working:
canvas.create_line(10, 100, 5, 50 , fill='red')



Using this form of the line,

canvas.create_line(xstart, ystart, xend, yend, fill="red")

seems to do it, although I can't say what versions allowed the author to 
(apparently successfully) write


canvas.draw_line(xstart, ystart, xend, yend, color="blue")

HTH,

Emile


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


Re: [Tutor] __import__()

2010-09-23 Thread Emile van Sebille

On 9/23/2010 8:26 AM Pete said...

Hiya,

still working on my plugin architecture. I figured out how to import modules of 
which I don't know the name yet at compile time,
by using __import__() instead of import.

So that works fine when I want to have the equivalent of

import spam

... by using

__import__('spam')

Question:

what is the equivalent of

from spam import *


Something you probably really don't want to do as it will pollute your 
namespace. But, if you insist, you could play with:


ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38)
[MSC v.1500 32 bit (Intel)] on win32
>>> xx = __import__('httplib')
>>> dir(xx)
['ACCEPTED', 'BAD_GATEWAY', ...]

>>> for ii in dir(xx): globals()[ii] = xx.__dict__[ii]
...
>>> dir()
['ACCEPTED', 'BAD_GATEWAY', ...]
>>>

Note, this really is for consenting adults only, and changing globals() 
is not really supported and may change in the future.  Note that from 
the docs, globals() is defined to "Return a dictionary representing the 
current global symbol table" and not as "Return the dictionary holding 
the current global symbol table" so the fact that it works on may 
version (and perhaps all others) doesn't mean it'll work everywhere.


HTH,

Emile









































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


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Emile van Sebille

On 9/27/2010 10:54 AM Alex Hall said...

What is wrong with the following line?
self.am=[[(a,b)
  for a in range(len(self.lines)) a=0]
  for b in range(len(self.lines)) b=0]


The a=0 and b=0 -- what do you think they're doing?

Emile




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


Re: [Tutor] if value in list of dictionaries

2010-09-27 Thread Emile van Sebille

On 9/27/2010 1:22 PM Norman Khine said...


what is the correct way to ensure that {'industry': 'travel', 'name':
'other','value': MSG(u"Other")} is always added to the end of this
list after all the items have been sorted?

here is the code which returns this list:


   options.sort(key=itemgetter('name'))
   return options

So, to answer the question you ask above, you can do:

   options.sort(key=itemgetter('name'))
   options.append({'industry':'travel',
  'name':'other','value':MSG(u"Other")}
   return options

But I don't think that's the question you're looking to get answered.

I think you want "other" to be found only at the end and not elsewhere.

Then you might try excluding other from options allowing the above to 
append it to the end:


for index, row in enumerate(topics.get_rows()):
if row[0] != 'other':
options.append({'name': row[0], 'value': MSG(row[1])})

HTH,

Emile



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


Re: [Tutor] pyMVPA and OSError

2010-09-28 Thread Emile van Sebille

On 2/18/2010 8:10 AM Juli said...

I am very much new to python, and thus I am likely to feel stupid about
asking. But I need to get past this to continue with my work.
I need pyMVPA module to run some analysis on fMRI data, but as a start I
want to at first play around with the sample data provided on pyMVPA
website. I have downloaded Python2.6,


Just a guess, but the pyMVPA site specifically mentions using version 
2.5, and whenever I have issues with a new package, I go back to the 
installation documentation and follow it closely as it's typically 
written by an experienced user while installing and yields a functioning 
implementation.  I'd reinstall and pay close attention to the version 
numbers and dependencies.


http://www.pymvpa.org/installation.html#macos-x

Then, always check if there's a user group for the package.  Diagnosing 
installation problems of specific packages and related dependencies are 
rarely an area of expertise outside the users of the package.  Join the 
mailing list.


See http://lists.alioth.debian.org/mailman/listinfo/pkg-exppsy-pymvpa

HTH,

Emile



my operating system is Mac Leopard
(i get a depracation warning when I try to >>> import mvpa, which is not
the problem, however, when I attempt to use the following line
 >>> import mvpa.suite as mvpa
which i assume to mean the same thing, I dont get deprecation warning,
but I do get a bunch of errors as follows:
 >>> import mvpa.suite as mvpa

Traceback (most recent call last):
File "", line 1, in 
import mvpa.suite as mvpa
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/suite.py",
line 38, in 
from mvpa.algorithms.cvtranserror import *
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py",
line 15, in 
from mvpa.measures.base import DatasetMeasure
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.py",
line 31, in 
from mvpa.clfs.stats import autoNullDist
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/stats.py",
line 772, in 
if externals.exists('pylab'):
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
line 432, in exists
exec _KNOWN[dep]
File "", line 1, in 
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
line 249, in __check_pylab
import pylab as P
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylab.py",
line 1, in 
from matplotlib.pylab import *
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pylab.py",
line 206, in 
from matplotlib import mpl # pulls in most modules
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/mpl.py",
line 2, in 
from matplotlib import axis
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py",
line 10, in 
import matplotlib.font_manager as font_manager
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
line 1297, in 
_rebuild()
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
line 1288, in _rebuild
fontManager = FontManager()
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
line 980, in __init__
self.ttffiles = findSystemFonts(paths) + findSystemFonts()
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
line 337, in findSystemFonts
for f in get_fontconfig_fonts(fontext):
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
line 298, in get_fontconfig_fonts
pipe = subprocess.Popen(['fc-list', '', 'file'], stdout=subprocess.PIPE)
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 621, in __init__
errread, errwrite)
File
"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 1126, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

-

I am not sure why OSError is popping and I am sure I am doing something
wrong, I just do not know enough to pinpoint what exactly.

Any feedback is appreciated. And I do once more apologize for asking
very stupid questi

Re: [Tutor] if value in list of dictionaries

2010-09-28 Thread Emile van Sebille

On 9/28/2010 7:12 AM Norman Khine said...

thanks for the reply, i think i have it now, perhaps it could be done better



I think I'd use a helper function to sort:

def sortOtherToEnd(val):
  if val['name'] == 'other:
return ''
  return val['name']

#then sort it

topics.sort(key=sortOtherToEnd)

But, generally, I'd stop once I got it going without worrying too much 
about 'better' ways -- that's a subjective measure.  There is often one 
obvious way to do it, but unless you've seen that way before, there'll 
often be many alternatives that work as well.


HTH,

Emile

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


Re: [Tutor] if value in list of dictionaries

2010-09-28 Thread Emile van Sebille

On 9/28/2010 9:37 AM Norman Khine said...

thank you, here is the updated version:

http://pastie.org/1186860




The only obvious redundancy is the duplicated sort of options just 
before the return.  You only need the newer sort_key based one.


Emile

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


Re: [Tutor] if value in list of dictionaries

2010-09-28 Thread Emile van Sebille

On 9/28/2010 11:13 AM Norman Khine said...

ok, great.

one thing i wanted to ask is how could i extend the class so that i
can just change the name of the csv file?


Python provides for instance initialization with a class __init__ 
method, so you could modify your class as follows:




def sort_key(option):
return "other" in option.itervalues(), option["name"]


class BusinessType(Enumerate):
def __init__(self,cvsfile):
self.cvsfile = cvsfile
def get_options(cls):
context = get_context()
here = context.resource
root = here.get_root().handler
topics = root.get_handler(self.cvsfile)
options = []
for index, row in enumerate(topics.get_rows()):
options.append({'name': row[0], 'value': MSG(row[1])})
options.sort(key=sort_key)
return options

Then, instead of invoking:

options = BusinessType().get_options()

You'd write:

options = BusinessType('topics.cvs').get_options()


Emile

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


Re: [Tutor] Doubly linked list

2010-09-30 Thread Emile van Sebille

On 9/30/2010 6:24 AM T MURPHY said...

I was having trouble, where on the python site can i find steps on classes and 
making a doubly linked list, is there a help option for linked lists.


Python itself doesn't provide a doubly linked list so I wouldn't expect 
to find support ifo on the python site therefore, but google yields 
multiple hits some of which appear to provide working classes providing 
doubly linked lists.  See for example 
http://bytes.com/topic/python/answers/523772-how-implement-linked-list-python 
but if you're new to python but not to programming you'll find a lot of 
useful info working the tutorial.


HTH,

Emile





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


Re: [Tutor] Using contents of a document to change file names

2010-10-02 Thread Emile van Sebille

On 10/2/2010 8:56 AM Josep M. Fontana said...

Hi,

This is my first posting to this list. Perhaps this has a very easy answer
but before deciding to post this message I consulted a bunch of Python
manuals and on-line reference documents to no avail. I would be very
grateful if someone could lend me a hand with this.



Hi Josep,

Break the problem into pieces.

Conceptually, you'll need to:

  -a- get the list of file names to change then for each
  -b- determine the new name
  -c- rename the file

For -a- you'll need glob. For -c- use os.rename.  -b- is a bit more 
involved.  To break -b- down:


  -b1- break out the x-xx portion of the file name
  -b2- look up the corresponding year in the other file
  -b3- convert the year to the century-half structure
  -b4- put the pieces together to form the new file name

For -b2- I'd suggest building a dictionary from your second files 
contents as a first step to facilitate the subsequent lookups.


You haven't included any code and we can't gauge how far along you are, 
so follow up and post the code you write as you go and we'll be better 
able to help out.


Hope this is enough to get you started,

Emile






Here's the problem I want to solve. I have a lot of files with the following
name structure:

A-01-namex.txt
A-02-namey.txt
...
N-09-namez.txt

These are different text documents that I want to process for an NLP project
I'm starting. Each one of the texts belongs to a different century and it is
important to be able to include the information about the century in the
name of the file as well as inside the text.

Then I have another text file containing information about the century each
one of the texts was written. This document has the following structure:

A-01, 1278
A-02, 1501
...
N-09, 1384

What I would like to do is to write a little script that would do the
following:

. Read each row of the text containing information about the centuries each
one of the texts was written
. Change the name of the file whose name starts with the code in the first
column in the following way

 A-01-namex.txt -->  A-01-namex_13-2.txt

 Where 13-1 means: 13th 2nd half. Obviously this information would com
from the second column in the text: 1278 (the first two digits + 1 =
century; if the 3rd and 4th digits>  50, then 2; if<  50 then 1)

Then in the same script or in a new one, I would need to open each one of
the texts and add information about the century they were written on the
first line preceded by some symbol (e.g @13-2)

I've found a lot of information about changing file names (so I know that I
should be importing the os module), but none of the examples that were cited
involved getting the information for the file changing operation from the
contents of a document.

As you can imagine, I'm pretty green in Python programming and I was hoping
the learn by doing method would work.  I need to get on with this project,
though, and I'm kind of stuck. Any help you guys can give me will be very
helpful.

Josep M.




___
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] function error

2010-10-02 Thread Emile van Sebille

On 10/2/2010 10:16 AM Joel Goldstick said...

##
import turtle, random

def checkForward(distance):
old_position = turtle.position()
turtle._pen.up()
# no show/hide turtle methods in my turtle module !
turtle.forward(distance)
forward_failed = outOfBounds()
turtle.setx(old_position[0]); turtle.sety(old_position[1])
turtle._pen.down()
# no show/hide turtle methods in my turtle module !
if outOfBounds() == 'false':
turtle.forward(distance)

def stuck():
return forward_failed

def outOfBounds():
if (abs(turtle.position()[0])>  turtle.window_height()/2) or
(abs(turtle.position()[1])>  turtle.window_width()/2):
return "true"
else:
return "false"

def randomMove2(d1, d2, a1, a2):
 while 1:
 turtle.left(random.uniform(a1,a2))
 checkForward(random.uniform(d1,d2))
 if outOfBounds() == 'true':
 turtle.right(180)
#


I copied your code between the hash lines and get this:

   File "my_turtle.py", line 19
 if (abs(turtle.position()[0])>  turtle.window_height()/2) or
^
SyntaxError: invalid syntax


Is that all of your code?  it seems to be cut off



Do you see it now?  Your reply contained the 10 ten lines or so of code 
that follows.


Emile

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


Re: [Tutor] function error

2010-10-02 Thread Emile van Sebille

On 10/2/2010 10:45 AM Steve Willoughby said...

On 02-Oct-10 10:32, Emile van Sebille wrote:


Well, not really -- this is the OPs code.  I was responding to Joel's 
comment of not seeing the entire post.



File "my_turtle.py", line 19
if (abs(turtle.position()[0]) > turtle.window_height()/2) or
^
SyntaxError: invalid syntax


How does Python know that the next line is the continuation of your if
statement, instead of the beginning of a new line of code?


Because of the paren count -- I didn't actually parse the OPs code and 
so I assumed that, but now I'll assume the line break probably resulted 
post send.


Continuing-to-assume-ly y'rs,

Emile


Here's the code fragment now paren'd...

import turtle, random

def checkForward(distance):
old_position = turtle.position()
turtle._pen.up()
# no show/hide turtle methods in my turtle module !
turtle.forward(distance)
forward_failed = outOfBounds()
turtle.setx(old_position[0]); turtle.sety(old_position[1])
turtle._pen.down()
# no show/hide turtle methods in my turtle module !
if outOfBounds() == 'false':
turtle.forward(distance)

def stuck():
return forward_failed

def outOfBounds():
if ((abs(turtle.position()[0])>turtle.window_height()/2) or
(abs(turtle.position()[1])>  turtle.window_width()/2)):
return "true"
else:
return "false"

def randomMove2(d1, d2, a1, a2):
 while 1:
 turtle.left(random.uniform(a1,a2))
 checkForward(random.uniform(d1,d2))
 if outOfBounds() == 'true':
 turtle.right(180)



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


Re: [Tutor] how to learn python from scratch, (for simpe people)?

2010-10-02 Thread Emile van Sebille

On 10/2/2010 8:22 AM a a said...

Dear Friends,

I am writing for some assistence from an expert.
I give you a short background to understand my need.
(for your information I work with a macbook normally), but I do have desktop in 
Microsoft)
I am not a programmer. My work has to do with old manuscripts and Philosophy.
But recently, being in need of building a web site I did learn alone some html, 
dreamweaver, css and I made two web sites who came out pretty good.
So, I have done of it my hobby, since I do like web design.
But now I would like to go further, although remaining always an hobby.
I would like to learn some programming, since I wish to build a program to run 
a database. Mybe more in the future if this goes well.
I have some text, several books, text format. I want to make a program to vew 
and research these texts. Perhaps on a cd and on a desktop.

On the internet I have read that an easy to learn and yet powerful language to 
start with is python.
Now my questions:
1) Is python enough and complete to build a simple program of the kind 
deskribed above?
2) Will I be able to build standalone program with it?
2) where do I start learning? SOMETHING AS SIMPE AS POSSIBLE!

Thank you very much
Jerome




I'd suggest you check out Alan's site at

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

He hangs out here and you'll be able to get any additional clarification 
you need.


You might also find this helpful

  http://diveintopython.org/toc/index.html

Finally, i'd suggest you start with python2 (vs python3) -- most of the 
info you'll find on the net is python2 and not always up to date for 
python3.


Good luck!

Emile

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


Re: [Tutor] how to learn python from scratch, (for simpe people)?

2010-10-02 Thread Emile van Sebille

On 10/2/2010 4:21 PM Emile van Sebille said...

On 10/2/2010 8:22 AM a a said...

Now my questions:
1) Is python enough and complete to build a simple program of the kind
deskribed above?


Yes


2) Will I be able to build standalone program with it?


Yes


Sorry - Forget to answer your questions.  Python's a great choice.

Regards,

Emile

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


Re: [Tutor] Downloading data from web

2010-10-04 Thread Emile van Sebille

On 10/4/2010 7:01 PM Crusier said...

I am trying to extract web data and put it into a database for
analysis.I am just wondering what is the best way to do it and I will
try to dig up information from there.

Please help me how can I kick start this project.


Check out beautiful soup.

http://www.crummy.com/software/BeautifulSoup/

Emile

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


Re: [Tutor] how to extract data only after a certain condition is met

2010-10-06 Thread Emile van Sebille

On 10/6/2010 9:25 AM Eduardo Vieira said...



Of course this solution is simpler:
extracted = a[a.index("i")+1:]
But I didn't want to build a list in memory with "readlines()" in the
case of a file.


This is what I do unless the files are _really big_

For-me-really-big-is-over-200Mb-ish-ly y'rs,

Emile

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


Re: [Tutor] how to extract data only after a certain condition is met

2010-10-06 Thread Emile van Sebille

On 10/6/2010 11:58 AM Joel Goldstick said...

On Wed, Oct 6, 2010 at 2:50 PM, Emile van Sebille  wrote:


On 10/6/2010 9:25 AM Eduardo Vieira said...



  Of course this solution is simpler:

extracted = a[a.index("i")+1:]
But I didn't want to build a list in memory with "readlines()" in the
case of a file.



This is what I do unless the files are _really big_

For-me-really-big-is-over-200Mb-ish-ly y'rs,

Emile


Why not loop with readline() and then the slice.  That way only one line at
time in memory



Because I'd consider that a premature optimization.  I don't commonly 
worry about managing the memory footprint until there's a reason to. 
I've found that you can work to minimize the footprint, but as it's 
often indeterminate, you can't really control it.  So I don't.


Emile

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


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Emile van Sebille

On 10/8/2010 12:34 PM Susana Iraiis Delgado Rodriguez said...

Hello members:
I developed a Python module to make a list which contains all the files
ending with .shp and .dbf extensions, I have solved this already, but now I
want to write an excel file from it. The file should show the full path from
the found files. This is the code:

import os
a = open ("directorio.xls","w")
allfiles = [] #store all files found
  for root,dir,files in os.walk("C:\\"):
filelist = [ os.path.join(root,fi) for fi in files if
fi.endswith(".shp") or fi.endswith(".dbf") ]
for f in filelist:
 allfiles.append(f)
for i in allfiles:
   print i
   a.write(i)
   a.write("\n")

With the code above, I have the print and the .xls file with
this information in it, the issue here is that my file doesn't have the
complete information that I got in the console. Any idea? The last line from
excel is C:\Python26



You may find that finishing with a.flush() and a.close() fixes your problem.

Also, it appears that you're doing more than is required -- 
specifically, looping through filelist appending its members to allfiles 
can be done more simply with append, so where you're saying:


filelist = [...

you could say

allfiles.extend([...

and forget about filelist entirely.

HTH,

Emile


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


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-09 Thread Emile van Sebille

On 10/8/2010 8:55 PM Steven D'Aprano said...


I'm sorry to tell you that you've just reinvented the wheel. This was
already solved, a long, long time ago. It is called the glob module:



Only if glob now descends into the file system... which is why you'd 
choose os.walk instead.


Emile

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


  1   2   3   4   5   6   >