Re: [Tutor] Importing Modules

2006-04-24 Thread ->Terry<-
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


Tomorrow (Apr 25, 2006) at 8:53am, John Connors spoke these wise words:

- ->G'day,
- ->
- ->I'm having trouble understanding the difference between,
- ->
- ->import sys
- ->and
- ->from sys import *
- ->
- ->It seems to me they both do the same thing.
- ->
- ->John

import sys imports sys elements in their own namespace
  use by preceding elements with 'sys.'

from sys import * imports sys elements in the local namespace
  use elements as any other local - no 'sys.' prefix

d:^)
- -- 
Terry 
 ',
  .-`-,\__
."`   `,
  .'_.  ._  `;.
  __ / `  `  `.\ .--.
 /--,| 0)   0) )`_.-,)
|;.-.__ _-');   /
 '--./ `.`/  `"`
:   '`  |.
| \ /  //
 \ '---'  /'
  `--' \
  jgs/a:f  _/   `--...

   

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2.2 (GNU/Linux)

iD8DBQFETXsAQvSnsfFzkV0RApBrAJ9gKu6tnxF8cAkmRpqfd8eFPxdEZACdGSk+
0AvUDxCmUZ+cZeHnp0VHid8=
=a8iW
-END PGP SIGNATURE-

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


Re: [Tutor] Avoiding the use of files to store intermediate results

2006-04-24 Thread Hugo González Monteverde
Remember duck typing. An object just needs to look like a file in order 
to be used like one.

Guido's time machine has already forseen your problem. Take a look at 
the StringIO module.  It allows you to use a string where you would 
normally pass a file object.

Hope that helps,

Hugo

> ##
> While this works, I find it "messy", as it creates some intermediate
> files.  I was wondering if there was a better way to do things all in
> memory, in an OS independent way.
> 
> [Note that the complete application is approximately 665 lines long
> ... a bit too much
> to post all here :-)]
> 
> André
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need to automate connection

2006-04-24 Thread Payal Rathod
Hi,
I need to automate connection to a IP like this. The IP (or domain name) 
is taken from command line or from user (whichever is easier for me to 
code). It should emulate,

telnet 127.0.0.1 25

mail from: 
250 ok
rcpt to: <[EMAIL PROTECTED]>
250 ok
quit

Can Python do this for me? How do I start?

With warm regards,
-Payal

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


Re: [Tutor] Tutor FAQ?

2006-04-24 Thread Fredrik Lundh
Mike Hansen wrote:

> I'll post the questions and answers to the list first. If I don't get
> any corrections or clarifications in a day or so after posting, I'll
> add it to the tutor suggestion page.

excellent!

> Ed mentioned that you are using restructured text. Should I put
> the entry in restructured text? I spent some time last night reading
> up on restructured text and docutils.

the infogami site uses markdown, which is a similar (but a bit simpler,
imo) syntax.  There's a very brief introduction on

   http://pyfaq.infogami.com/suggest-tutor

(which basically says that you should use ## to mark the entry title, and
indent all code snippets by at least four spaces)

and there's an on-line test editor here:

   http://daringfireball.net/projects/markdown/dingus

(that pages also contains a cheatsheet and links to full documentation).

When this is moved over to python.org, it'll either be handled as HTML
or converted to ReST (which is the main syntax used on python.org),
but that'll all be taken care of by tools.  The important thing now is to
get the content in place.

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


Re: [Tutor] Invoking Excel Macro

2006-04-24 Thread Mike Hansen
I guess I'm confused. You mentioned that it still throws and error 
while trying to save the workbook. hmmm Do you get this error when 
trying to close Excel in the macro? Many times, Excel pops up a dialog 
box when closing it if there's still a workbook open even if it has 
been saved. That's where the Application.DisplayAlerts comes in. So I 
may have been a little off on the part of saving. It might be the 
closing of Excel. Other than that, I'm stumped.

Mike

On Apr 24, 2006, at 7:32 AM, arun wrote:

> Hi Mike,
>    It doesn't  display any dialog box rather it gives a temporary name 
> to the file.
> Ex
>  newsheet.xls as newsheet1.xls
> So i'm not able to save it. Is  there an alternative to invoke the  
> macro and save the file from my script itself .(saving it through 
> macro wud be a better option : )  )
>  
> Thanx  and Regards,
> arun
>
>  
> On 4/21/06, Mike Hansen <[EMAIL PROTECTED]> wrote: In the macro, 
> you might try Application.DisplayAlerts = False  and reset it to True 
> after you save.
>> I think it might be trying to display a dialog box before it saves.
>>  
>> Mike
>>
>>> From: [EMAIL PROTECTED] [mailto: [EMAIL PROTECTED] On 
>>> Behalf Of arun
>>> Sent: Friday, April 21, 2006 1:44 AM
>>> To: tutor@python.org
>>> Subject: Re: [Tutor] Invoking Excel Macro
>>>
>>>  I'm sorry , there is something realy wrong with 'Run-time error 
>>> 1004':. I have fixed it now but still it throws an error while 
>>> trying to save the workbook.
>>
>> On 4/21/06, arun <[EMAIL PROTECTED]> wrote: Hi,
>>> I tried invoking a macro from my python script and  It is  throwing  
>>> an error message that reads 'Run-time error 1004':
>>>  
>>> "This operation requires the merged cells to be identically sized"
>>>  
>>> My script looks like this
>>>  
>>> from win32com.client import Dispatch
>>> xl = Dispatch('Excel.Application')
>>> xl.Workbooks.Add('E:\Templates\sample.xls')
>>> xl.Run('Import_file')  # name of the macro
>>>  
>>> Also while (running the macro)opening the workbook it  names it as 
>>>  "sample1.xls' ,and so
>>> It says there is no such file sample.xls
>>>  
>>> "
>>> Filename =  Myexcel.xls
>>> Workbooks("sample.xls").SaveAs Filename
>>> "
>>>  
>>> Can somebody help me with this issue : (
>>>  
>>>  
>>> Thanx
>>> arun 
>>>  
>>>  
>>>
>>>
>>>  
>>
>>
>> -- 
>> arun
>
>
>
> -- 
> arun___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Tutor FAQ?

2006-04-24 Thread Mike Hansen

On Apr 22, 2006, at 3:15 AM, Fredrik Lundh wrote:

> Ed wrote:
>
>> I don't think the FAQ is open to public editing yet.  I'm not sure
>> when it will be, but Fredrik might be able to give a timescale.
>
> There are a few known conversion issues to deal with (the FAQ uses
> a lot more "looks like markdown syntax" than the tutorial, which con-
> fused the converter).  I've made some progress, but it'll probably take
> another week before everything's sorted out.
>
> When Ed brought up the tutor/tutorial FAQ idea, my first thought
> was that Ed and other volunteers could add pages in a separate
> "tutor-" namespace (to avoid collisions with material from the
> existing FAQ), and ended up writing a couple of paragraphs on
> how to manually convert titles to page names.  When I found that
> I had written "this isn't quite as hard as it may look", I realized
> that it would be better if I just wrote a script that did this.
>
> So, while I'm working on that script, I suggest that you start adding
> stuff the "tutor suggestion" page that I just set up:
>
> http://pyfaq.infogami.com/suggest-tutor
>
> One entry per comment; use "## title" to mark the first line as the
> FAQ entry.  I've added Mike's examples.
>
> cheers /F
>

Hi,

I'll post the questions and answers to the list first. If I don't get 
any corrections or clarifications in a day or so after posting, I'll 
add it to the tutor suggestion page. Ed mentioned that you are using 
restructured text. Should I put the entry in restructured text? I spent 
some time last night reading up on restructured text and docutils.

Thanks,

Mike

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


[Tutor] Dictionaries and aggregation

2006-04-24 Thread Paul Churchill








 

I am trying to create a dictionary using data produced by a
load balancing admin tool and aggregate the results. 

 

 

When I invoke the tool from within the shell (‘sudo
~/ZLBbalctl --action="" the following output is produced:

 

Load Balancer 1 usage, over the last 30 seconds

Port 80, rules - /(nol)|(ws)

  server001  alive 18.1% 2 requests/s 14536543
total

  server002  alive 43.1% 7 requests/s 14842618
total

  server003  alive 21.2% 2 requests/s 14884487
total

  server004  alive 17.3% 2 requests/s 15092053
total

 

 

Load Balancer 2 usage, over the last 30 seconds

Port 80, rules - /(nol)|(ws)

  server001  alive 11.6% 2 requests/s 14482578
total

  server002  alive 35.6% 9 requests/s 14820991
total

  server003  alive 28.7% 6 requests/s 14928991
total

  server004  alive 23.7% 5 requests/s 15147525
total

  

 

 

I have managed to get something close to what I’m
looking for using lists i.e. the aggregate of the fourth column (requests/s)

 

lbstat = commands.getoutput("sudo ~/ZLBbalctl
--action="" | awk '$1 ~ /^server00/ { print $4 }'")  

rLst = lbstat.split('\n')

rLst = [ int(rLst[i]) for i in range(len(rLst)) ]

rTotal = reduce(operator.add, rLst)

 

However here’s what I’m now trying to do:

 

1)   Not have to
rely on using awk at all.

 

 

2)   Create a
dictionary with server names for keys e.g. server001, server002 etc and the aggregate
of the request for that server as the value part of the pairing.

 

 

I got this far with part 1)

 

lbstat =
commands.getoutput("sudo ~/ZLBbalctl
--action="">

tmpLst = lbstat.split('\n')

 

rLst = []

for i in tmpLst:

    m =
re.search('
server[0-9]+', i)

    if m:

    rLst.append(i)

 

for i in rLst:

    print i, type(i)

 

  

  

  server001  alive 22.3% 6 requests/s 14527762
total str'>

  server002  alive 23.5% 7 requests/s 14833265
total str'>

  server003  alive 38.2%    14 requests/s 14872750 total
str'>

  server004  alive 15.6% 4 requests/s 15083443
total str'>

  server001  alive 24.1% 8 requests/s 14473672
total str'>

  server002  alive 23.2% 7 requests/s 14810866
total str'>

  server003   
  alive 30.2% 8 requests/s 14918322
total str'>

  server004  alive 22.1% 6 requests/s 15137847
total str'>

 

 

 

 

At this point I ran out of ideas and began to think that
there must be something fundamentally wrong with my approach. Not least of my
concerns was the fact that I needed integers and these were strings.

 

Any help would be much appreciated.

 

Regards,

 

Paul

 

 

 

 

 






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


Re: [Tutor] Importing Modules

2006-04-24 Thread Alan Gauld
> I'm having trouble understanding the difference between,
>
> import sys

This brings the *name* "sys" into your module.
It does not give you access to any of the names inside sys itself
(such as exit for example). To access those you need to prefix them with 
sys, as in

sys.exit()

> from sys import *

This does NOT bring the name "sys" into your module, instead
it brings all of the names inside sys(like exit for example) into
your module. Now you can access those names without a prefix, like this:

exit()

So why not do that instead of

import sys?

The reason is that the second form will overwrite and names you
have already declared - like exit say.

exit = 42
from sys import *   # hides my exit variable.

OR more likely, the other way round

from sys import *
exit = 42   # now hides the sys.exit function so I can't use it.

Of course some of these are obvious but there can be a lot
of names in a module, and some modules have the same name
in them, for example:

from os import *
from urllib import *

open(foo)   # which open gets called, os.open or urllib.open?

Can you see how it gets confusing.
Bottom line is it is usually better to accept the extra typing and use

import foo

or for just a few names

from foo import bar,baz

> It seems to me they both do the same thing.

A subtle but very important difference!

HTH,

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



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


[Tutor] Importing Modules

2006-04-24 Thread John Connors

G'day,

I'm having trouble understanding the difference between,

import sys
and
from sys import *

It seems to me they both do the same thing.

John

_
New year, new job – there's more than 100,00 jobs at SEEK 
http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT


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


Re: [Tutor] Locking a specific variable (fwd)

2006-04-24 Thread Kent Johnson
> Yup, I'm familiar with those. In all of the examples, I have seen, the
> critical region happens in one specific area eg a part of a function with a
> lock and release around it. My question is there a way to lock a specific
> variable so that even though other functions are attempting to access it,
> they will not until the first function has released it. Examples below
> 
> # This example shows the way I have seen it in python tutorials
> def function1():
>   blah blah
>   function3()
>   blah blah
> 
> def function2():
>   blah blah
>   function3()
>   blah blah
> 
> def function3():
>  acquire lock
>  does some stuff
>  release lock
> 
> t = Thread.thread()
> t.start(function1())
> t.start(function2())

What is wrong with doing exactly this?
> 
> # The way I would like to do it, so we have two different instances of the
> same variable, and only # one function can access it at a time. If a

I don't understand what you mean by "two different instances of the same 
variable." Can you give an example?

> function comes to that variable and finds a lock on it, # it will wait until
> the lock is released.  And the variable happens to be a queue

Do you know that Queues are already thread safe? They use locks 
internally and are intended for multi-threaded use. You shouldn't have 
to use any additional locks to use a Queue.

> def function1():
>   blah blah
>   acquire lock of variable only so that only function1 can access this at
> a given time
>   increment some variable.
>   release the function2 lock on this variable
>   blah blah
> 
> def function2():
>   blah blah
>   acquire lock of variable only so that only function2 can access this at
> a given time
>   decrement some variable..
>   release the function2 lock on this variable
>   blah blah
> 
> t = Thread.thread()
> t.start(function1())
> t.start(function2())

This code is the same as the first version except function3() has been 
inlined. I don't see the benefit of this style, it just causes code 
duplication.

Kent

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


[Tutor] Avoiding the use of files to store intermediate results

2006-04-24 Thread Andre Roberge
I wrote a small wxPython based app to test code snippets.
(google for "python lightning compiler" if you want to see the full code).

In the basic mode, I redirect the standard input and output and
execute the code taken from the editor window so that the result
appears in the output window.

Here are the 4 main lines of code to accomplish this:

sys.stdout = self.outputWindow
sys.stderr = self.outputWindow
user_code = self.PythonEditor.GetText()
exec user_code in myGlobals

For example, if I have the following situation:
input window
print "Hello world!"


the result of running the program will be this:
output window===
Hello world!


Simple enough :-)  [Actually, there's more to it, but this description
should suffice for illustration purposes.]


Now, I want to be able to test the code using the doctest module.

I can't use exec as doctest.testmod() will be testing my entire
application, not simply the code in the input window!

The solution I chose was to
1. Create a new file which contains the code to be tested with the
appropriate "doctest" call.
2. Run this file with Python, redirecting the result to a second file.
3. Read the result from the second file into a string.
4. Print the string (which, because of redirection) appears in the
output window.

Here are the main lines of code to do this:

sys.stdout = self.outputWindow
sys.stderr = self.outputWindow
user_code = self.PythonEditor.GetText()

user_code += "\nimport doctest\ndoctest.testmod()"

f = open('_doctest_file.py', 'w')
f.write(user_code)
f.close()

if verbose:
os.popen("python _doctest_file.py -v> _doctest_file.output")
else:
os.popen("python _doctest_file.py> _doctest_file.output")
result = open("_doctest_file.output", 'r').read()
print result

##
While this works, I find it "messy", as it creates some intermediate
files.  I was wondering if there was a better way to do things all in
memory, in an OS independent way.

[Note that the complete application is approximately 665 lines long
... a bit too much
to post all here :-)]

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


Re: [Tutor] Object defined by initialization parameters ADDITION

2006-04-24 Thread Bob Gailer




Bob Gailer wrote:

  Andre Engels wrote:
  
  
Is it possible to define a class in such a way, that if twice an
object is made with the same initialization parameters, the same
object is returned in both cases?
  

  
  Use a "factory" function, and store a dictionary of instances as a class 
property:

class myObj(object):
  instances = {}
  def __init__(self,a):
# the rest of your code 

def makemyObj(a):
  if a in myObj.instances:
return myObj.instances[a]
  else:
new_instance =  myObj(a)
myObj.instances[a] = new_instance 
return new_instance 
 
  

I neglected to show the function call:

a = makemyObj("a")
b = makemyObj("b")

c = makemyObj("a")

a and c will point to the same object
b will be a different object


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


Re: [Tutor] Object defined by initialization parameters

2006-04-24 Thread Bob Gailer
Andre Engels wrote:
> Is it possible to define a class in such a way, that if twice an
> object is made with the same initialization parameters, the same
> object is returned in both cases?
>   
Use a "factory" function, and store a dictionary of instances as a class 
property:

class myObj(object):
  instances = {}
  def __init__(self,a):
# the rest of your code 

def makemyObj(a):
  if a in myObj.instances:
return myObj.instances[a]
  else:
new_instance =  myObj(a)
myObj.instances[a] = new_instance 
return new_instance 
 

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


Re: [Tutor] hash.update( argv[0] )

2006-04-24 Thread Danny Yoo


> where outputVersion is a manual set variable in the program
> (so I have to purge all the imageFile each time I adjust the
> program.  maybe this is going to work, less progressive approach
   ^^^

Hi George,

Just to make sure: by "progressive", I meant the technical concept:

 progressive: read the file a chunk at a time rather than sucking the
  file all at once.

*grin*


># Use a hash of the parameters to generate a cache filename.
>hash = sha.new(texData)
>hash.update( "%d %d" % (density, int(texMag)) )
>hash.update( open(argv[0]).read() )
>name = hash.hexdigest()
>imageFile = "%s/%s.%s" % (imagePath, name, 'png')
>
> I cannot test till the evening because of $WORK; but is that a
> good way to do it?

Yes, I think this will work.

One thing that it may not be robust against is changes to the current 
working directory.  I'd recommend capturing the program's filename at the 
program's entry as an absolute-pathed variable, so that if we shake things 
up by changing current working directory, we should still be able to work.

The os.path module may be useful here:

 http://www.python.org/doc/lib/module-os.path.html

It has a few path-normalizing functions that should make this a relatively 
easy fix.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Locking a specific variable (fwd)

2006-04-24 Thread Danny Yoo
> # The way I would like to do it, so we have two different instances of 
> the same variable, and only # one function can access it at a time. If a 
> function comes to that variable and finds a lock on it, # it will wait 
> until the lock is released.  And the variable happens to be a queue

Hi Tino,

One way to do this is to add a level of indirection.

##
class LockedVariable:
 def __init__(self, val):
 self.val = val
 self.internal_lock = RLock()

 def acquire(self):
 self.internal_lock.acquire()

 def release(self):
 self.internal_lock.release()

def with_lock(locked_variable, function):
 locked_variable.acquire()
 try:
 return function(locked_variable.val)
 finally:
 locked_variable.release()
##

The idea is that this allows us to pair up values with individual locks. 
There's nothing that restricts us to having one lock per program.


If you have some experience with treating functions as values, the last 
function, with_lock(), might be useful.  It's meant to be used as:

#
## Pseudocode
def function_using_some_locked_resource(locked_resource):
 def actual_work(val):
 ## ...
 with_lock(locked_variable, actual_work)
#

with_lock() here tries to capture the mutual-exclusion abstraction, and 
might make programs a little less error prone: we'll never forget to 
release the lock, because it handles both resource acquiring and 
releasing.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Object defined by initialization parameters

2006-04-24 Thread Danny Yoo


On Mon, 24 Apr 2006, Andre Engels wrote:

> Is it possible to define a class in such a way, that if twice an object 
> is made with the same initialization parameters, the same object is 
> returned in both cases?

Yes.  The idea is to have the "constructor" really be a function that 
delegates off to actual object instantiation only after it's comfortable 
with the situation.  That is, we can make a "factory" function.

For example:

##
class _Boolean:
 def __init__(self, value):
 self.value = value

def Boolean(b):
 if b:
 return _Boolean(True)
 else:
 return _Boolean(False)
##

The idea is that no one should directly call the underscored _Boolean(): 
they should go through Boolean(), which can do some additional things to 
make sure clients get the canonical objects.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Danny Yoo


On Mon, 24 Apr 2006, Etrade Griffiths wrote:

> just feeling my way into Python with a small app that reads data from 
> file, creates objects using that data, stores the objects in a list, 
> loops over the list doing comparison tests to filter out various 
> objects.  Here is a code snippet:
>
> class myObj:
>def __init__(self,a,b):
>self.a=a
>self.b=b
>
>def get_a(self):
>return self.a
>
>def get_b(self):
>return self.b

Hi Alun,

Looks ok so far.

Python specific tip: we can avoid writing getters and setters in Python. 
Python supports an alternative way to control how clients set and get 
attributes.  If you're interested, look for information on Python 
"properties".  So for now, I'd recommend simplifying this to:

##
class myObj:
def __init__(self,a,b):
self.a=a
self.b=b
##

until we get into a real need to set up explicit get/set methods.


> # Read data from file
>
> L1=[]
> nobj=0
>
> for line in input:
>L0=line.split()
>a=L0[1]
>b=L0[2]
>nobj=nobj+1
>
>an_obj=myObj(a,b)
>
>L1.append(an_obj)

There must be additional context here, in the sense that I don't know what 
'input' is.  I suspect this is a file of some sort.  So unfortunately, we 
won't be able to test the exact same situation that you have.


I'd recommend turning this into a function as well, just to make the 
commend superfluous:

##
def read_data_from_file(input):
 L1=[]
 nobj=0
 for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1
an_obj=myObj(a,b)
L1.append(an_obj)
 return L1, nobj
##

If we have this function, we can then test by doing:

#
L1, nobj = read_data_from_file(input)
#

and preserve the original behavior of our program.  (We may want to do 
some additional revision --- the nobj variable is also superfluous.)


> Trying to debug this using IDLE.  The calls x.get_a and x.get_b always 
> return zero so something is going wrong somewhere.  I think I'm either 
> not storing the objects correctly or retrieving them correctly but no 
> idea why!  All suggestions gratefully received!!!

I don't see anything horribly wrong with the code.  There are at least two 
possibilities when a problem comes up:

 * There's something wrong with the program (which might be the case,
   although I don't see it yet.)

 * The input to the program is weird.

I'll assume, for the moment, that the input may be weird.  *grin*


If we do have read_data_from_file() as function, we can test it by passing 
it hardcoded "files", and see that we get the myObj values we expect.

Here's one test to start you off:


import StringIO

def test1():
 sample_data = StringIO.StringIO("foo\tbar\tbaz\n")
 objs, nobjs = read_data_from_input(sample_data)
 assert (len(objs) == 1 == nobjs)
 first_object = objs[0]
 assert (first_object.a == "bar")
 assert (first_object.b == "baz")


(This uses the very useful StringIO module to disguise a string to make it 
look like a file.  See: 
http://www.python.org/doc/lib/module-StringIO.html)

Does this test case make sense to you?

If this test works out ok, then we've still made progress: we can at least 
know that our parser is working well.  That bolsters the possibility that 
the input we're getting from our other source is weird.


Good luck to you.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] looking to hire a tutor

2006-04-24 Thread Carroll, Barry
Hello, Meenakshi,

> -Original Message-
> Date: Fri, 21 Apr 2006 19:44:57 -0700 (PDT)
> From: [EMAIL PROTECTED]
> Subject: [Tutor] looking to hire a tutor
> To: tutor@python.org
> Message-ID:
>   <[EMAIL PROTECTED]>
> Content-Type: text/plain;charset=iso-8859-1
> 
> 
>   Hi,
> I apologize if this has been covered before.
> I am a postdoctoral research scientist learning Python programming.  I
> would like to hire a tutor who can spend 1-2 hours a week with me
going
> overand critiquing my programming.  I have looked for online Python
> programming classes (not free tutorials), which offer structure and
> feedback for a reasonable price.  To my surprise, I havent been very
> successful.
>Working with online free tutorials hasnt been an ideal approach,
partly
> because I dont get feedback and partly because they dont completely
> meet my requirements.
> 
>  How would I go about hiring a python tutor who:
> 
> Spends time critiquing my code and providing detailed feedback.
> Cares about good programming practices and is able to provide cogent
> explanations of programming principles.
> Can instruct me in the finer points of breaking a programming problem
down
> into constituent parts.
> Is well versed in Python.  It would be great (but not necessary) if
he/she
> were also familiar with data mining practices.
> 
>  I would be willing to pay 20-30$ an hour (or more depending on
instructor
> qualifications).
> 
>How do I go about doing this?  Any suggestions?
> 
>   Thanks
> Meenakshi 

I agree with the others that this list is an excellent place to learn
both Python and best programming practices.  However, the more personal,
one-on-one approach can be very useful.  

Have you checked the resources available there?  I'm thinking
particularly of the Computer Science department and the Student
Placement Service (or whatever they are called on your campus).  Most
placement services have a student employment service (web page, bulletin
board, etc) where students in need of part-time work can find job
listings.  Likewise, many computer science departments have a job board
or web page that does the same thing.  I'd be very surprised if UCLA
doesn't have something similar.

Good luck.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Locking a specific variable (fwd)

2006-04-24 Thread Danny Yoo


-- Forwarded message --
Date: Mon, 24 Apr 2006 07:32:04 -0400
From: Tino Dai <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] Locking a specific variable

Hey there Danny,

I'm not quite sure I get it, but ok.  *grin* I'll assume that fileQueue is
> an instance of the Queue class:
>
>  http://www.python.org/doc/lib/module-Queue.html
>
> If so: why not allow fileQueue to grow unbounded?
>
>
>> Presently, the only way that I can see to do this using Python is to
>> combine the two functions into one and lock and unlock the entire thing
>> . That doesn't seem efficient and/or elegant to me. Any pointers about
>> this?
>
> Do you know about the thread-locking primitives?  There are a few kinds
> provided by Python's threading module:
>
>  http://www.python.org/doc/lib/module-threading.html
>
> Are you already familiar with the concept of a RLock or a Lock?
>


Yup, I'm familiar with those. In all of the examples, I have seen, the
critical region happens in one specific area eg a part of a function with a
lock and release around it. My question is there a way to lock a specific
variable so that even though other functions are attempting to access it,
they will not until the first function has released it. Examples below

# This example shows the way I have seen it in python tutorials
def function1():
  blah blah
  function3()
  blah blah

def function2():
  blah blah
  function3()
  blah blah

def function3():
 acquire lock
 does some stuff
 release lock

t = Thread.thread()
t.start(function1())
t.start(function2())

# The way I would like to do it, so we have two different instances of the
same variable, and only # one function can access it at a time. If a
function comes to that variable and finds a lock on it, # it will wait until
the lock is released.  And the variable happens to be a queue
def function1():
  blah blah
  acquire lock of variable only so that only function1 can access this at
a given time
  increment some variable.
  release the function2 lock on this variable
  blah blah

def function2():
  blah blah
  acquire lock of variable only so that only function2 can access this at
a given time
  decrement some variable..
  release the function2 lock on this variable
  blah blah

t = Thread.thread()
t.start(function1())
t.start(function2())


Does that make more sense?


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


Re: [Tutor] How use relative path of Linux environment in Python (fwd)

2006-04-24 Thread Danny Yoo


-- Forwarded message --
Date: Mon, 24 Apr 2006 14:28:34 +0700
From: Keo Sophon <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] How use relative path of Linux environment in Python

On Monday 24 April 2006 14:24, you wrote:
> On Mon, 24 Apr 2006, Keo Sophon wrote:
>> Do you have any idea of how to use relative path of Linux environment in
>> Python. For example, if a program would like to create an oupfile from
>> these assignment: outputfile = "~/Desktop/" + workingfile, while "~" is
>> the short cut to the path of current user.
>
> This seems similar to a question that was asked and answered a few days
> ago:
>
>  http://mail.python.org/pipermail/tutor/2006-April/046613.html
>
> Are you trying to do something similar?

Yes, same. Just a small point different, he tried to read the file, i am
trying to write the file.

Phon

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


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Etrade Griffiths
Ed

the problem is that my original code did not have the closing brackets for 
the method calls get_a and get_b whereas the code snippet I posted 
did.  That's probably why your version works and mine failed.  Thanks for 
your help!

Alun

At 17:19 24/04/2006, Ed Singleton wrote:
>On 24/04/06, Etrade Griffiths <[EMAIL PROTECTED]> wrote:
> >  Hi
> >
> >  just feeling my way into Python with a  small app that reads data from
> > file, creates objects using that data, stores the objects in a list, loops
> > over the list doing comparison tests to filter out various 
> objects.  Here is
> > a code snippet:
> >
>[snip]
> >
> >  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> > return zero so something is going wrong somewhere.  I think I'm either not
> > storing the objects correctly or retrieving them correctly but no idea why!
> > All suggestions gratefully received!!!
>
>I added some test input to give the code below, and it works fine for
>me.  Can you give us some test input that fails for you?  Can you also
>show us your test() function as it may the code in there that is
>failing.
>
>Ed
>
>class myObj:
> def __init__(self,a,b):
> self.a=a
> self.b=b
>
> def get_a(self):
> return self.a
>
> def get_b(self):
> return self.b
>
>
>input = ["1 2 3", "4 5 6"]
>
>L1=[]
>nobj=0
>
>for line in input:
> L0=line.split()
> a=L0[1]
> b=L0[2]
> nobj=nobj+1
>
> an_obj=myObj(a,b)
>
> L1.append(an_obj)
>
># Filter data
>
>for i in range(1,nobj):
> for x in L1:# ... loop over all objects in list
> print "a -> ", x.get_a() # ... get value
>of a from current object
> print "b -> ", x.get_b()
>
>
>It returns:
>
>a ->  2
>b ->  3
>a ->  5
>b ->  6


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


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Ed Singleton
On 24/04/06, Etrade Griffiths <[EMAIL PROTECTED]> wrote:
>  Hi
>
>  just feeling my way into Python with a  small app that reads data from
> file, creates objects using that data, stores the objects in a list, loops
> over the list doing comparison tests to filter out various objects.  Here is
> a code snippet:
>
[snip]
>
>  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> return zero so something is going wrong somewhere.  I think I'm either not
> storing the objects correctly or retrieving them correctly but no idea why!
> All suggestions gratefully received!!!

I added some test input to give the code below, and it works fine for
me.  Can you give us some test input that fails for you?  Can you also
show us your test() function as it may the code in there that is
failing.

Ed

class myObj:
def __init__(self,a,b):
self.a=a
self.b=b

def get_a(self):
return self.a

def get_b(self):
return self.b


input = ["1 2 3", "4 5 6"]

L1=[]
nobj=0

for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1

an_obj=myObj(a,b)

L1.append(an_obj)

# Filter data

for i in range(1,nobj):
for x in L1:# ... loop over all objects in list
print "a -> ", x.get_a() # ... get value
of a from current object
print "b -> ", x.get_b()


It returns:

a ->  2
b ->  3
a ->  5
b ->  6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hash.update( argv[0] )

2006-04-24 Thread George Georgalis
On Sun, Apr 23, 2006 at 10:49:00PM -0700, Danny Yoo wrote:
>
>
>On Sun, 23 Apr 2006, George Georgalis wrote:
>
>>Hi! I've been struggling to find a way up seed hash.update() with
>>the sha1 (or similar) of the file that is the program running.
>>
>>this is not a security task but rather a means to generate
>>reasonably unique filenames based on various parameters including
>>changes to the program: name = hash.hexdigest()
>>
>>so new files are generated when the program or parameters are
>>changed; but cached files are used when identical results are
>>expected.
>>
>>help! I cannot figure out how to pass the program body as a seed
>>to hash.update().
>
>Hi George,
>
>I'm slightly confused.  Isn't this a matter of doing:
>
>###
>def prepare_md5(filename):
>m = md5.new()
>m.update(open(filename).read())  ## not so smart: do this
> ## progressively in real life!
>return m
>###

I'm pretty green as far as python is concerned, but that looks good.
However filename is unpredictable, as this is a website plugin module,
and the path could be anything.

 open(filename).read()

>Are you asking instead: how do I get the filename of the currently running 
>program?

yep, that's the main part of the problem I have

# Use a hash of the parameters to generate a cache filename.
hash = sha.new(texData)
hash.update( "%d %d" % (density, int(texMag)) )
hash.update( outputVersion )
name = hash.hexdigest()
imageFile = "%s/%s.%s" % (imagePath, name, 'png')

where outputVersion is a manual set variable in the program
(so I have to purge all the imageFile each time I adjust the
program.  maybe this is going to work, less progressive approach

# Use a hash of the parameters to generate a cache filename.
hash = sha.new(texData)
hash.update( "%d %d" % (density, int(texMag)) )
hash.update( open(argv[0]).read() )
name = hash.hexdigest()
imageFile = "%s/%s.%s" % (imagePath, name, 'png')

I cannot test till the evening because of $WORK; but is that a
good way to do it?

// George


-- 
George Georgalis, systems architect, administrator <
http://galis.org/ cell:646-331-2027 mailto:[EMAIL PROTECTED]

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


[Tutor] Object defined by initialization parameters

2006-04-24 Thread Andre Engels
Is it possible to define a class in such a way, that if twice an
object is made with the same initialization parameters, the same
object is returned in both cases?

More specifically, suppose I have the following program:

class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen

x = myObj("a")
y = myObj("a")
z = myObj("b")
x.touch()

After this, x._seen will return 1, but y._seen and z._seenwill return
0. I would like the definition of the myObj class to be such that
after these definitions x and y refer to the same object, but z to a
different one.

If there is not such possibility, does anyone have a better or more
elegant workaround than the one I am using, which is:

class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen

def obj(a):
try:
return objects[a]
except KeyError:
objects[a] = myObj(a)
return objects[a]

objects = {}
x = obj("a")
y = obj("a")
z = obj("b")
x.touch()



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Looping over lists of objects

2006-04-24 Thread Etrade Griffiths


Hi
just feeling my way into Python with a  small app that reads data
from file, creates objects using that data, stores the objects in a list,
loops over the list doing comparison tests to filter out various
objects.  Here is a code snippet:
class myObj:
    def __init__(self,a,b):
    self.a=a
    self.b=b
    def get_a(self):
    return self.a
    def get_b(self):
    return self.b

# Read data from file
L1=[]
nobj=0
for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1
an_obj=myObj(a,b)

L1.append(an_obj)
# Filter data
for i in range(1,nobj):
for x in
L1:#
... loop over all objects in list
a=x.get_a() #
... get value of a from current
object    
b=x.get_b()
   
if
test(a,b):
  
 print 'test succeeded'
else:
  
 print 'test 
failed'
Trying to debug this using IDLE.  The calls
x.get_a and
x.get_b always return zero so
something is going wrong somewhere.  I think I'm either not storing
the objects correctly or retrieving them correctly but no idea why! 
All suggestions gratefully received!!!
Thanks in advance
Alun Griffiths

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


Re: [Tutor] Invoking Excel Macro

2006-04-24 Thread arun
Hi Mike, 
   It doesn't  display any dialog box rather it gives a temporary name to the file.
Ex
 newsheet.xls as newsheet1.xls 
So i'm not able to save it. Is  there an alternative to invoke the  macro and save the file from my script itself .(saving it through macro wud be a better option : )  )
 
Thanx  and Regards,
arun 
On 4/21/06, Mike Hansen <[EMAIL PROTECTED]> wrote:


In the macro, you might try Application.DisplayAlerts = False  and reset it to True after you save.
I think it might be trying to display a dialog box before it saves. 
 
Mike



From: [EMAIL PROTECTED] [mailto:
[EMAIL PROTECTED]] On Behalf Of arunSent: Friday, April 21, 2006 1:44 AMTo: 
tutor@python.orgSubject: Re: [Tutor] Invoking Excel Macro 

I'm sorry , there is something realy wrong with 'Run-time error 1004':. I have fixed it now but still it throws an error while trying to save the workbook.
On 4/21/06, arun <[EMAIL PROTECTED]> wrote:
 


Hi, 
I tried invoking a macro from my python script and  It is  throwing  an error message that reads 'Run-time error 1004':
 
"This operation requires the merged cells to be identically sized"
 
My script looks like this 
 
from win32com.client import Dispatchxl = Dispatch('Excel.Application')xl.Workbooks.Add('E:\Templates\sample.xls')
xl.Run('Import_file')  # name of the macro
 
Also while (running the macro)opening the workbook it  names it as  "sample1.xls' ,and so 
It says there is no such file sample.xls
 
"
Filename =  Myexcel.xls
Workbooks("sample.xls").SaveAs Filename
"
 
Can somebody help me with this issue : (
 
 
Thanx

arun 
 
 
 -- arun 

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


Re: [Tutor] [Linux] open a file in any home "~" ?

2006-04-24 Thread kakada
learner404 wrote:
> It works great, thanks very much to the three of you for these
> light-speed answers ... I love this list !
>
> Wesley, I've just pre-order your new edition "Core Python programming"
> on amazon France, it looks great. :)
>
> Thanks  
I love this list too.

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


Re: [Tutor] How use relative path of Linux environment in Python

2006-04-24 Thread Danny Yoo


On Mon, 24 Apr 2006, Keo Sophon wrote:

> Do you have any idea of how to use relative path of Linux environment in 
> Python. For example, if a program would like to create an oupfile from 
> these assignment: outputfile = "~/Desktop/" + workingfile, while "~" is 
> the short cut to the path of current user.

This seems similar to a question that was asked and answered a few days 
ago:

 http://mail.python.org/pipermail/tutor/2006-April/046613.html

Are you trying to do something similar?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How use relative path of Linux environment in Python

2006-04-24 Thread Keo Sophon
Hi all,

Do you have any idea of how to use relative path of Linux environment in 
Python. For example, if a program would like to create an oupfile from these 
assignment: outputfile = "~/Desktop/" + workingfile, while "~" is the short 
cut to the path of current user.

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