[Tutor] lazy? vs not lazy? and yielding

2010-03-03 Thread John
Hi,

I just read a few pages of tutorial on list comprehenion and generator 
expression.  From what I gather the difference is "[ ]" and "( )" at the 
ends, better memory usage and the something the tutorial labeled as "lazy 
evaluation".  So a generator 'yields'.  But what is it yielding too?  

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


Re: [Tutor] python magazine

2010-03-26 Thread John
On Friday 26 March 2010 08:33:35 am Lowell Tackett wrote:
> >From the virtual desk of Lowell Tackett 
>
> --- On Fri, 3/26/10, Bala subramanian  wrote:
>
> From: Bala subramanian 
> Subject: [Tutor] python magazine
> To: tutor@python.org
> Date: Friday, March 26, 2010, 8:07 AM
>
> Friends,
> I am sorry if this query is not appropriate to this forum.
>
> Is there any online magazine dedicated to python especially its features
> and How-to's that i can subscribe for.
>
> Thanks,
> Bala
>
>
> -Inline Attachment Follows-
>
> http://twitter.com/pymag
>
> The Python Magazine people have now got a Twitter site--which includes a
> perhaps [telling] misspelling.

Last updated Jun 2009???
Johnf


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


Re: [Tutor] Help with choices for new database program

2010-07-03 Thread John
On Friday 02 July 2010 08:19:24 pm bob gailer wrote:
> On 7/2/2010 5:56 PM, Jeff Johnson wrote:
> > [snip]
> >
> > Visual FoxPro ... is very similar to Access
>
> I differ. Access and FoxPro are very different. Yes they both use
> tables, relationships, indexes and SQL. Yes they both have visual
> designers for forms and reports. Yes they both are programmable.
>
> But the differences are much more dramatic than the commonalities. I
> have developed in both. I find it painful to work in one while desiring
> a feature that exists only in the other.

Yes I agree (0ver 20 years with Fox/dBase) they are different.  I'd say Access 
provides several no thinking tools for the end user where VFP requires a 
little more effort.  But the concepts of both are very close.   The 
underlying code is also very different in that I find VFP 10 times easier 
when working with data.

That said, the question at hand is does Dabo make a good fit for the poster.  
I'd say without question the answer is yes.  Yes it is true that Dabo follows 
VFP more closely than Access.  But if the poster is moving from Access to a 
python solution does it matter?  The poster is making a change to a new 
language which is a major change.  At least Dabo keeps many of the concepts a 
Access user already understands. Therefore he/she will be more productive.

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


Re: [Tutor] newbie to gui programming

2010-07-06 Thread John
On Tuesday 06 July 2010 05:35:34 pm Nick Raptis wrote:
> Please excuse if I'm jumping on the topic. Haven't done any GUI work so
> this interests me too.
>
> wxPython always seemed a great choice as it works on all platforms, and
> uses GTK+ for linux.
> Well, what mainly bugs me about wxPython is that most of it's API names
> come from the wx C library, you almost can feel the C code underneath.
> I would really love a more pythonic wrapper around it.
>
> Really good news is that on this very list on another thread, someone
> suggested Dabo http://dabodev.com/
> It's a python library on top of wxPython and it's database-logic-GUI
> separation looks a lot like the MVP of django, which I'm familiar with.
>
> Of course, a bit not that easy to install if you're just starting out
> and there are no books for it. It's also database oriented, but I
> consider this a plus.
>
> I'd like to hear your views on whether you think it might be a good
> choice for a new python programmer, exactly for the above reasons.
> I think it might be worth the hurdles and pay off in the end.
>
> Nick

I really enjoy Dabo and I feel it is very easy to use and learn.  Best of all 
there plenty of support.

Johnf

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


Re: [Tutor] Writing Scripts.

2010-10-24 Thread John
Autumn,

Here's a basic script, if you save this in a file called hello.py and
type 'python hello.py' at the prompt, or as others are saying using
the python launcher, you should get some output. hth, john

SCRIPT (include lines below here):
#!/usr/bin/env python

import os

user  = os.environ.get('USER')

print "Hello %s!" % (user)


 NOW SOME COMMENTS 
the first line is somewhat 'unix or linux' dependent, but it tells
your 'shell' to call the file using python

the next line "import os" is a python import statement, telling python
to import the os module

the next line "user os.environ.get('USER')" is call a method (get)
from the environ class of the os module and returns the name of the
logged in user to the variable 'user'

the next line is doing a few things. First it is calling the built in
function 'print' to print a string "Hello %s!". However, the "%s" does
something fancy. This is string substitution, so by having the
variable 'user' after the second '%' sign, it replaces "%s" with that
variable. Don't worry, it will come fast! Have fun with it!!







On Wed, Oct 20, 2010 at 6:13 PM, Autumn Cutter  wrote:
> I just started learning Python last night and I'm a little stuck on how to 
> write a Python script.
> I'm using Python 2.5.0 on a Mac OS X 10.6.4. I've tried using programs like 
> Idle, Applescript and Textmate but I'm still unable to write a script and run 
> it successfully. I'm wondering if I'm using the write program or if I 
> understand correctly how to write and run scripts. Help! :(
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonpath

2010-11-01 Thread John
Chris,

I haven't worked on windows in ages, but I think you can set a
PYTHONPATH variable if you right click on My Computer and maybe the
advanced tab, there is a place to set ENVIRONMENT VARIABLES. Create a
new one called PYTHONPATH pointing to your directory.

-john

On Mon, Nov 1, 2010 at 10:58 PM, Chris King  wrote:
> On 11/1/2010 5:57 PM, Vince Spicer wrote:
>
> On Mon, Nov 1, 2010 at 3:54 PM, Chris King  wrote:
>>
>> On 11/1/2010 5:47 PM, Vince Spicer wrote:
>>
>> On Mon, Nov 1, 2010 at 3:41 PM, Chris King  wrote:
>>>
>>>  Dear Tutors,
>>>    When I try to import a module, how can I make it look in certain
>>> directories for them easily.
>>> Sincerely,
>>>    Chris
>>> ___
>>> Tutor maillist  -  tu...@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> Hello Chris
>> You can manage you path from within your script,
>> import sys
>> sys.path.append("/home/user/lib")
>>
>> Or in bash you can edit your  $PYTHONPATH env variable
>> echo $PYTHONPATH
>>
>> --
>> Vince Spicer
>>
>> --
>> Sent from Ubuntu
>>
>> So doing it in cmd windows will permanently change it?
>
>
> the first way with work for Window,  the second is for Linux or posix
> systems
> Sorry I can't help with PYTHONPATH on windows.
>
> --
> Vince Spicer
>
> --
> Sent from Ubuntu
>
> I want a permanent change.
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonpath

2010-11-01 Thread John
hehe. yeah, I had to go check my old PC that's collecting dust on how
to navigate the 'happy dungeon' of windows wizards...

I do prefer:

export PYTHONPATH=/my/custom/dir



On Mon, Nov 1, 2010 at 11:03 PM, Vince Spicer  wrote:
>
>
> On Mon, Nov 1, 2010 at 4:00 PM, Vince Spicer  wrote:
>>
>>
>> On Mon, Nov 1, 2010 at 3:58 PM, Chris King  wrote:
>>>
>>> On 11/1/2010 5:57 PM, Vince Spicer wrote:
>>>
>>> On Mon, Nov 1, 2010 at 3:54 PM, Chris King  wrote:

 On 11/1/2010 5:47 PM, Vince Spicer wrote:

 On Mon, Nov 1, 2010 at 3:41 PM, Chris King  wrote:
>
>  Dear Tutors,
>    When I try to import a module, how can I make it look in certain
> directories for them easily.
> Sincerely,
>    Chris
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 Hello Chris
 You can manage you path from within your script,
 import sys
 sys.path.append("/home/user/lib")

 Or in bash you can edit your  $PYTHONPATH env variable
 echo $PYTHONPATH

 --
 Vince Spicer

 --
 Sent from Ubuntu

 So doing it in cmd windows will permanently change it?
>>>
>>>
>>> the first way with work for Window,  the second is for Linux or posix
>>> systems
>>> Sorry I can't help with PYTHONPATH on windows.
>>>
>>> --
>>> Vince Spicer
>>>
>>> --
>>> Sent from Ubuntu
>>>
>>> I want a permanent change.
>>
>> There is probably a Windows alternative to env variables and PYTHONPATH,
>> Google may help.
>>
>> --
>> Vince Spicer
>> --
>> Sent from Ubuntu
>
>
> Sorry I don't know any developers that run Windows anymore, if you find the
> solution please post it back here.
> Thanks.
>
>
> --
> Vince Spicer
>
> --
> Sent from Ubuntu
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] mutable types

2010-11-02 Thread John
Hello, I thought the following should end with G[1] and G[0] returning
20. Why doesn't it?

In [69]: a = 10
In [70]: G = {}
In [71]: G[0] = [a]
In [72]: G[1] = G[0]
In [73]: a = 20
In [74]: G[1]
Out[74]: [10]
In [75]: G[0]
Out[75]: [10]

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


Re: [Tutor] Question from a newbie

2009-07-22 Thread John
On Tuesday 21 July 2009 11:12:23 am Deb wrote:
> My son suggested I play around with Python.  I was wondering if anybody has
> any real life applications?  It appears to be able to do quite a lot, but
> is anybody really doing it with Python?  I am very curious about this
> language. I used to be a Clipper programmer in another life (dBASE
> compiler), and got sick when I was just entering the OOP world via Visual
> Basic and had to quit I just recently got my brain back, thanks to medical
> science, and would like to learn all I can about what it out there these
> days.
>
> Thanks,

Then you'll love Dabo (www.dabodev.com) which is built on python, wxPython, 
and supports databases like Postgres, MsSQL, MySQL, Firebird, and SQLite.  
The thinking is very similar to Visual FoxPro.  Classes are close and the 
coding is close.  If you ever used any of the VFP (clipper) frameworks then 
it will be old hat.


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


[Tutor] python and java report writers

2009-08-17 Thread John
Hi,

I have been searching for a report writer to work with my python programs.  I 
did find reportlab. But most of the other report writers are java based.  I 
am confused by all the jargon associated with Java and have very little 
working knowledge of the environment.  So I'm hoping someone will help out.

I'd like to understand how python can integrate with Java in general and then 
how it would work with the Java report writers.  I have read a little about 
jPython but do not understand how to make that work with my python programs.  
It would appear to me it is a way to replace python.  I don't want to replace 
my python code.  I want to just call a java report writer.  Passing either 
the data or parameters to retrieve the data  and ask it to print a report.  I 
would think that would be straight forward.  But I see nothing about python 
and jasper for example.  Therefore, something is unusual in this case.  


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


Re: [Tutor] python and java report writers

2009-08-17 Thread John
On Monday 17 August 2009 01:08:15 pm Oxymoron wrote:
> (Posting to list!)
>
> On Tue, Aug 18, 2009 at 6:01 AM, John wrote:
> > First I love your handle.  And second, thanks for taking the time to
> > explain
> >
> :-)
> :
> > jython world.  But I was really looking for a simple way of calling a
> > report writer (like using a com object) to print a report.  At this point
> > in the project changing to jython is not going to be considered.  We are
> > using to many modules and I'm sure we will run into something.
>
> I wasn't suggesting changing everything to Jython - I actually meant
> something similar, i.e. write the reporting component in Jython (this
> really depends on where you get your data from I suppose, if it's all
> code generated may be more tricky, but for a DB-based thing, not so).
> You could then treat the jython/java mini-reporting-app as a blackbox.
> It's not COM perhaps, but plain IPC should do.
>
> > It looks like we are stuck with either reportlab or using something like
> > openoffice's uno.
>
> They may be a simpler solution if it amounts to the same thing.
>
> -- Kamal

I don't know enough about jython to understand what has to be done.  Let's say 
I can write the code to retrieve the data in cPython.  And I can write a 
module in jython that will accept the data passing it on to the report 
writer.  How can I call the jython program?  It can't be called from the 
cPython program - right?  So the jython runs stand alone - right?

IPC = Inter-process communication - right?  Does that mean I need to write 
some sort of server?

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


Re: [Tutor] python and java report writers

2009-08-17 Thread John
On Monday 17 August 2009 05:43:05 pm Kent Johnson wrote:
> Forwarding to the list with my reply.
>
> On Mon, Aug 17, 2009 at 4:04 PM, John  wrote:
> > Thanks for taking the time to write.  But I was really looking for a
> > simple way of calling a report writer (like using a com object) to print
> > a report. At this point in the project changing to jython is not going to
> > be considered.  We are using to many modules and I'm sure we will run
> > into something.
> >
> >
> >From a quick look at the docs for Jasper Reports I see that it can take
> > data
>
> from a CSV file. Perhaps you could make a Java / Jython app that generates
> your report from a file, then your Python program could write the CSV file
> and call the external program.
>
> Kent

Thanks folks I think I'll have to start playing with jython and see if I can 
get it to first create a report/ run a report.  Then I'll see if I can get it 
working with python.  

Again thanks to all.

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


[Tutor] real world decorators

2009-09-20 Thread John
Hi,

I think I understand what decorators are and how they work.  Maybe it's just 
me but I don't know where I'd use them in my real world programming.  I see 
how they work with profile or coverage but does anyone have real world uses.  

I mostly create wxPython apps and don't see where they might apply.

I know the tutors will enlighten me!

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


Re: [Tutor] real world decorators

2009-09-21 Thread John
On Sunday 20 September 2009 03:43:32 pm Eike Welk wrote:
> On Sunday 20 September 2009, John wrote:
> > Hi,
> >
> > I think I understand what decorators are and how they work.  Maybe
> > it's just me but I don't know where I'd use them in my real world
> > programming.  I see how they work with profile or coverage but does
> > anyone have real world uses.
>
> Frequently used are @classmethod and @staticmethod:
> http://docs.python.org/library/functions.html#classmethod
>
> An other interesting usage of decorators is Phillip J.
> Eby's 'simplegeneric' library, where decorated functions replace big
> if... elif... constructions:
> http://cheeseshop.python.org/pypi/simplegeneric/0.6
>
> But really decorators are just syntactical sugar. They are an elegant
> way to write a special case of a function call.
>
> Kind regards,
> Eike.

Thanks to all that responded on list and off.  You guys have provided much to 
read.  

Thanks

Johnf

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


Re: [Tutor] Porting PHP web app to Python GUI

2009-10-12 Thread John
On Monday 12 October 2009 05:17:16 am Dotan Cohen wrote:
> I have a simple PHP web application with a form, which enter the
> information entered into the form into a database. However, I will be
> several weeks without internet access so I now have two choices:
>
> 1) Run the script locally on my Kubuntu box
> 2) Port it to Python and make a real app out of it.
>
> I prefer the second route, but I want to know if this seems reasonable
> in Python:
> 1) GUI with several input areas which are analogous to the HTML
> Select, Input=Text, and Textarea fields.
> 2) insert the data collected into an sqlite database
> 3) Retrieve and display data from the database using predefined queries.
>
> I am familiar with the SQL language, some PHP and some C programing. I
> have never done GUI programming other than HTML. Does PyQt seem to
> have a reasonable learning curve for this application?
>
> Thanks!

Take a look at Dabo www.dabodev.com.  Dabo works with SQLite, MySQL, MsSQL, 
Firebird, and Postgres.  Use the ClassDesigner to create simple forms in a 
visual way.

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


[Tutor] cross platform authenticating

2009-10-20 Thread John
Hi,

Is there a general discussion (somewhere on the web) on how to

1. determine what authentication the platform requires
2. can #1 be determine dynamically 
3. If I know #1 will it be cross platform?

Googling reveals that there are many authenticating modules, LDAP, PAS, 
RADIUS, Active Directory, PAM, and something called pluggable authentication. 
But I don't see anything that tells me how to determine what the platform 
requires.  And what if there is no authentication required - like on a single 
computer.  Also if I am able to determine the authentication requirements 
will the modules then be cross platform - working on Linux, Mac, and Windows?

As you guys can see I'm just starting out in the authentication world.


Thanks in advance for any help,

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


Re: [Tutor] cross platform authenticating

2009-10-20 Thread John
On Tuesday 20 October 2009 12:41:28 pm Alan Gauld wrote:
> "John"  wrote
>
> > As you guys can see I'm just starting out in the authentication world.
>
> This is a list for beginners in Python not authentication.
> You would probably be better off posting on a security
> or authentication forum/list
>
> But you never know, lots of clever people here so you may get an answer.
>
> Alan G
>From a python beginner thanks.

Johnf

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


[Tutor] replacing a long list of if,elif

2009-10-23 Thread John
I'm using python 2.5

I have a long list of if, elif, else.  I always thought it was very NOT 
pythonic.  It's easy to read but not pretty.

for fldType in fieldList:
  if "int" in fldType:
  fld = "I"
  elif "char" in fldType :
  fld = "C"
  elif "bool" in fldType :
 fld = "B" .
  else:
 fld = '?'


I have considered:

  mydict = {'int': 'I', 'char':'C', 'bool':'B'}
  for fldType in fieldList:
try:
fld = mydict[fldType]
except:
fld = '?'

I also considered some sort of  lambda function as 

x = lambda fld: mydict[fldType] 

But could not determine how to account for the key exception. So I tried

x = lambda fldType: mydict[fldType] 
if fldType in mydict:
   x(fldType)
else:
fld = '?'


Any suggestions would be helpful  and would help me learn.

Johnf
   



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


Re: [Tutor] replacing a long list of if,elif

2009-10-23 Thread John
On Friday 23 October 2009 08:05:29 am John wrote:
> I'm using python 2.5
>
> I have a long list of if, elif, else.  I always thought it was very NOT
> pythonic.  It's easy to read but not pretty.
>
> for fldType in fieldList:
>   if "int" in fldType:
>   fld = "I"
>   elif "char" in fldType :
>   fld = "C"
>   elif "bool" in fldType :
>  fld = "B" .
>   else:
>  fld = '?'
>
>
> I have considered:
>
>   mydict = {'int': 'I', 'char':'C', 'bool':'B'}
>   for fldType in fieldList:
> try:
> fld = mydict[fldType]
> except:
> fld = '?'
>
> I also considered some sort of  lambda function as
>
> x = lambda fld: mydict[fldType]
>
> But could not determine how to account for the key exception. So I tried
>
> x = lambda fldType: mydict[fldType]
> if fldType in mydict:
>x(fldType)
> else:
> fld = '?'
>
>
> Any suggestions would be helpful  and would help me learn.
>
> Johnf

>John,

>Using a Dictionary is the best method to use here and you can use dict.get
>in order to bypass the KeyError

>EX:

>myDict.get(fldType, None)

>this will output the value from myDict if the key exists, if not it will
>
>return None 

Thanks this looks perfect - did not know dict.get()

Johnf


Vince


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


Re: [Tutor] How to load a dict into a dict subclass?

2009-10-27 Thread John
I use a 'SuperDict' all the time in my code. Not sure it's a good idea, but
I find it convenient. Also, I wouldn't mind comments on why/why not to use
something like this:

class SuperDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value

def set_with_dict(self,D):
""" set attributes with a dict """
for k in D.keys():
self.__setattr__(k,D[k])

Here's the original thread (NOTE: I have also been trying to use more
structured arrays as recommended by one poster):
http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-td23759398.html

On Tue, Oct 27, 2009 at 1:45 PM, Christian Witts wrote:

> Modulok wrote:
>
>> List,
>>
>> I'm new to the list, (somewhat new to python too). My code feels
>> hacky. I'd like to know if there is a more eloquent way (more below).
>> If not, a general thumbs up from more experienced programmers would be
>> great!
>>
>> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which
>> subclasses (i.e. is a derived class) of a dict. How do I eloquently
>> get foo into an instace of Bar? Example:
>>
>>
>> ### BEGIN CODE:
>> class Bar(dict):
>>   pass # Act like a dict for now.
>>
>> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return
>> value.
>> myvar = Bar()
>> # The hacky feeling part:
>> for k,v in foo.items(): myvar[k] = v
>>
>> ### END CODE
>>
>> Obviously I can put the dict into an instance variable, but then
>> methods like 'keys()' and such won't work. If that makes any sense...
>>
>> Thanks guys!
>> -Modulok-
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>
> You can use the built-in function for dictionaries called update.  So
>
> >>> class Bar(dict):
> >>> pass
>
>
> >>> foo = {'a':100, 'b':200, 'c': 300}
> >>> myvar = Bar()
> >>> myvar.update(foo)
> >>> myvar
> {'a': 100, 'c': 300, 'b': 200}
>
> --
> Kind Regards,
> Christian Witts
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to load a dict into a dict subclass?

2009-10-27 Thread John
On Tuesday 27 October 2009 06:25:13 am John wrote:
> I use a 'SuperDict' all the time in my code. Not sure it's a good idea, but
> I find it convenient. Also, I wouldn't mind comments on why/why not to use
> something like this:
>
> class SuperDict(dict):
> def __getattr__(self, attr):
> return self[attr]
> def __setattr__(self, attr, value):
> self[attr] = value
>
> def set_with_dict(self,D):
> """ set attributes with a dict """
> for k in D.keys():
> self.__setattr__(k,D[k])
>
> Here's the original thread (NOTE: I have also been trying to use more
> structured arrays as recommended by one poster):
> http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-th
>is-one-may-take-some-thought--%29-td23759398.html
>
> On Tue, Oct 27, 2009 at 1:45 PM, Christian Witts 
wrote:
> > Modulok wrote:
> >> List,
> >>
> >> I'm new to the list, (somewhat new to python too). My code feels
> >> hacky. I'd like to know if there is a more eloquent way (more below).
> >> If not, a general thumbs up from more experienced programmers would be
> >> great!
> >>
> >> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which
> >> subclasses (i.e. is a derived class) of a dict. How do I eloquently
> >> get foo into an instace of Bar? Example:
> >>
> >>
> >> ### BEGIN CODE:
> >> class Bar(dict):
> >>   pass # Act like a dict for now.
> >>
> >> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return
> >> value.
> >> myvar = Bar()
> >> # The hacky feeling part:
> >> for k,v in foo.items(): myvar[k] = v
> >>
> >> ### END CODE
> >>
> >> Obviously I can put the dict into an instance variable, but then
> >> methods like 'keys()' and such won't work. If that makes any sense...
> >>
> >> Thanks guys!
> >> -Modulok-
> >> ___
> >> Tutor maillist  -  Tutor@python.org
> >> To unsubscribe or change subscription options:
> >> http://mail.python.org/mailman/listinfo/tutor
> >
> > You can use the built-in function for dictionaries called update.  So
> >
> > >>> class Bar(dict):
> > >>> pass
> > >>>
> > >>>
> > >>> foo = {'a':100, 'b':200, 'c': 300}
> > >>> myvar = Bar()
> > >>> myvar.update(foo)
> > >>> myvar
> >
> > {'a': 100, 'c': 300, 'b': 200}
> >
> > --
> > Kind Regards,
> > Christian Witts


Hey guru's could one of you explain why such a subclass is needed.  How would 
it be used.  I'm not sure but does not the deepcopy() work as above?


Thanks
Johnf


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


[Tutor] how to access deep classes

2009-11-20 Thread John
Hi,
I'm not to sure I can explain myself.  But I need to ask because I do not 
understand how it works or what is possible.

class A (wx.Panel);
   def__init__(...)

class B(wx.PyPanel):

   def __init__(..):
 self.pages = A(...)

class C (B)
  def __init__(...)

I can't change the code in either class A or class B.  But I want to add a 
property to class A in class C.  Is that possible?

Something like

wxpanelFontSize = property(_getwxpanelFontSize, _setwxpanelFontSize, None, '')

Or is there another way to get the same thing done?

Johnf

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


Re: [Tutor] how to access deep classes

2009-11-20 Thread John
On Friday 20 November 2009 04:48:59 am Lie Ryan wrote:
> Is this what you want?
>
> class C(B):
>     �...@property
>      def wxpanelFontSize(self):
>          return self.pages.wxpanelFontSize
>     �...@wxpanelfontsize.setter
>      def wxpanelFontSize(self, value):
>          self.pages.wxpanelFontSize = value

Maybe? @property is called a decorator.  But from what I'm reading I don't see 
how it's different from what a normal property def is like:
wxpanelFontSize = property(_getwxpanelFontSize, _setwxpanelFontSize, None, '')

I'm trying to set the font size of a text control in a class that provides no 
way to set the font size.  But in the back of my head I think all wx text 
items have FontSize.  Maybe I'm thinking about this incorrectly.  I think 
your saying that from class C I can set the font size if I have access to the 
underlying wx text control.  

Johnf

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


Re: [Tutor] how to access deep classes

2009-11-20 Thread John
On Friday 20 November 2009 09:48:38 am Alan Gauld wrote:
> "John"  wrote
>
> > class A (wx.Panel);
> >   def__init__(...)
> >
> > class B(wx.PyPanel):
> >
> >   def __init__(..):
> > self.pages = A(...)
> >
> > class C (B)
> >  def __init__(...)
> >
> > I can't change the code in either class A or class B.  But I want to add
> > a
> > property to class A in class C.  Is that possible?
>
> You need to distinguish between classes and instances thereof.
>
> You can add attributes to instances of A, and you can access the
> instance because it is stored in self.pages of C. (You can actually add
> attributes and methods to the class too, after it is defined but I wouldn't
> recommend that since it gets  very confusing if you duplicate a name
> added to an instance elsewhere!)
>
> So you can, within C's methods do
>
> self.pages.foo = 66
>
> which adds a new foo attribute to the instance of A stored in pages.
> Just be careful you don't have any code anywhere that relies on the
> content of A instances (eg pickle/unpickle type things).
>
> > wxpanelFontSize = property(_getwxpanelFontSize, _setwxpanelFontSize,
> > None, '')
>
> Sorry, the connection to A is not clear.

Thanks - for your help.

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


[Tutor] win32com and ocx with properties

2009-12-09 Thread John
I realize that some may consider this an advance question.  But there are many 
here that are advance.  So I'm hoping some nice soul will help me.

I'm attempting to use a OCX designed to talk with QuickBooks.  I'm using 
win32com for the first time and have discovered an issue that I'm sure others 
have run into.  But researching google etc.  has not helped.

obj = win32com.client.Dispatch("InQB.Invoice.1")
#In the VB code 
#obj.ItemName(0) = 'string' 

#in python I'm trying 
obj.ItemName[0] = 'string'
#error is "Instancemethod object does not support item assignment"

I found and ran makepy.py and here is the code it created dealing with my obj.

# The method ItemName is actually a property, but must be used as a method
to correctly pass the arguments
def ItemName(self, ItemIndex=defaultNamedNotOptArg):
        """Line item property: Reference to the kind of item."""
        # Result is a Unicode object
        return self._oleobj_.InvokeTypes(19, LCID, 2, (8, 0), 
((3,1),),ItemIndex )

As I read the above code it can only return a string not assign anything. I'm 
not sure what "InvokeTypes" does.

So the question is how can I get around this issue?  I'm sure others need to 
set properties in com objects.

BTW does anyone know of a win32com forum or list?

Johnf

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


Re: [Tutor] win32com and ocx with properties

2009-12-09 Thread John
On Wednesday 09 December 2009 01:45:38 pm bob gailer wrote:
> John wrote:
> > I realize that some may consider this an advance question.  But there are
> > many here that are advance.  So I'm hoping some nice soul will help me.
> >
> > I'm attempting to use a OCX designed to talk with QuickBooks.  I'm using
> > win32com for the first time and have discovered an issue that I'm sure
> > others have run into.  But researching google etc.  has not helped.
> >
> > obj = win32com.client.Dispatch("InQB.Invoice.1")
> > #In the VB code
> > #obj.ItemName(0) = 'string'
> >
> > #in python I'm trying
> > obj.ItemName[0] = 'string'
>
> Try:
>
> obj.ItemName.Item[0] = 'string'
>
> In VB obj.ItemName(0) = 'string' Item is the "default" property.
> obj.ItemName.Item(0) = 'string' will also work in VB
>
> > #error is "Instancemethod object does not support item assignment"
> >
> > I found and ran makepy.py and here is the code it created dealing with my
> > obj.
> >
> > # The method ItemName is actually a property, but must be used as a
> > method to correctly pass the arguments
> > def ItemName(self, ItemIndex=defaultNamedNotOptArg):
> > """Line item property: Reference to the kind of item."""
> > # Result is a Unicode object
> > return self._oleobj_.InvokeTypes(19, LCID, 2, (8, 0),
> > ((3,1),),ItemIndex )
> >
> > As I read the above code it can only return a string not assign anything.
> > I'm not sure what "InvokeTypes" does.
> >
> > So the question is how can I get around this issue?  I'm sure others need
> > to set properties in com objects.
> >
> > BTW does anyone know of a win32com forum or list?
>
> There is python-wi...@python.org

Someone suggested I use:

obj.SetItemName(0,'test')

And it works (who knew) 

Thanks to all that replied,

Actually thanks to all you tutors...

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


Re: [Tutor] Entry-level open source opportunities

2009-12-15 Thread John
On Tuesday 15 December 2009 09:20:16 am bob gailer wrote:
> Kent Johnson wrote:
> > OpenHatch is a new web site that compiles entry-level opportunities
> > with open-source programming projects. Many of the projects are in
> > Python. If you are looking for a way to get involved with an open
> > source project, this could be a useful resource.
> > https://openhatch.org/search/
>
> I do not understand what I see on this site or how to use it. Are there
> any instructions?

Also the dates of the reports bug and issues are old.  On the second page the 
date is 2006?

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


[Tutor] pywinauto for OS X and Linux?

2007-05-18 Thread John
I have been playing with pywinauto http://pywinauto.pbwiki.com/ for a 
few hours. Pywinauto allows you to use python to automate the GUI of 
Windows using Python in very intuitive ways.  What are the closest 
analogs for this under OS X and Linux?

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


[Tutor] I'm clearly not getting an important pygtk concept

2007-05-25 Thread John
I created the following script to test my understanding of creating 
simple pygtk GUIs.

#!/usr/bin/python2.5

import gtk, urllib


def pinger_shotgun():
  """This function stores an object that pings Peter's writerscafe.org 
pages."""
  open_page = urllib.urlopen(web)

def plink(widget, web):
  print "I just pinged", web
  pinger_shotgun()

web = "http://www.mywebsite.com/";
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", gtk.main_quit)
ping_button = gtk.Button("ping me")
window.add(ping_button)
ping_button.connect("clicked", plink, web)
window.show_all()
gtk.main()

I am not sure what's wrong with the script as I've typed it above.  I 
expected this script to generate a button with the label "ping me". I 
expected that when I press this button that my webserver log would show 
that someone with the user-agent python-urllb just tried to access my site.

This is not happening unfortunately.  Sometimes pressing the button 
registers in my logs and sometimes it does not.  Pressing  the button 
twice in rapid succession may cause a hit to register if a single click 
did not.  Pressing the button 5 or 6 times will cause 4 or 5 hits.  What 
is it I am not understanding?


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


[Tutor] An interesting case... of east vs. west

2007-07-10 Thread John

I was trying to read in a tab delimited file i was given with lat and lon,
the thing is I needed decimal lat, and decimal long... well, anyway I think
you can see what my problem was:

for i in range(0,344)
  y=d[i][2].split('\xb0')
   x=d[i][3].split('\xb0')
   ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S")
   xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W")
   if re.search('\ZW','x[1]') xmin=-1*xmin
   if re.search('\ZS','y[1]') ymin=-1*ymin
   declat=int(ydeg)+(float(ymin)/60)
   declon=int(xdeg)+(float(xmin)/60)

The thing is, it isn't terribly robust (I'm not even positive it's working
correctly!!). For instance, as you might have guessed I was given Lat and
Lon in the following format:
STNA 45° 49' N 08° 38' E
STNB 46° 58' 19° 33' E
STNC 53°33'  -9°54'
STND 51°32' N 12°54' W

Some indicating north or some, and some not. This wasn't a concern, as I
knew they were all North. However, the West / East issue is another story.
Anyone have a more elegant solution?

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


Re: [Tutor] An interesting case... of east vs. west

2007-07-10 Thread John

Just a quick follow up.. it doesn't work :s

There are definitely some problems...  ideas are welcome!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] An interesting case... of east vs. west

2007-07-10 Thread John

Luke, Albert:

Thanks.. yes I'm thinking re is what I need... and using negative values for
west, and positive for east is our convention. The problem I have is that
not all the data was provided in that format, so I'm in the process of
converting...

There are a number of problems with my original post. For one, the
conversion to decimal fails if given a negative number (i.e. -9 30' in my
approach becomes 8.5 when it should be 9.5). So, to get around that I need
to use abs, and add some if cases to convert it back to negative..

Anyway, still working through this...


On 7/11/07, Albert Weiss <[EMAIL PROTECTED]> wrote:



John: One way to handle the situation of longitude is to make everything
west of the Greenwich meridan a negative value until -180 degrees and
everything east of Greenwich a positive value. HTH.
    Albert




  *John <[EMAIL PROTECTED]>*
Sent by: [EMAIL PROTECTED]

07/10/2007 04:22 PM
   To
tutor@python.org  cc
  Subject
[Tutor] An interesting case... of east vs. west




I was trying to read in a tab delimited file i was given with lat and lon,
the thing is I needed decimal lat, and decimal long... well, anyway I think
you can see what my problem was:

for i in range(0,344)
  y=d[i][2].split('\xb0')
   x=d[i][3].split('\xb0')
   ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S")
   xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W")
   if re.search('\ZW','x[1]') xmin=-1*xmin
   if re.search('\ZS','y[1]') ymin=-1*ymin
   declat=int(ydeg)+(float(ymin)/60)
   declon=int(xdeg)+(float(xmin)/60)

The thing is, it isn't terribly robust (I'm not even positive it's working
correctly!!). For instance, as you might have guessed I was given Lat and
Lon in the following format:
STNA 45° 49' N 08° 38' E
STNB 46° 58' 19° 33' E
STNC 53°33'  -9°54'
STND 51°32' N 12°54' W

Some indicating north or some, and some not. This wasn't a concern, as I
knew they were all North. However, the West / East issue is another story.
Anyone have a more elegant solution?

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





--
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] An interesting case... of east vs. west

2007-07-10 Thread John

A little closer, this seems to work, but it's not catching the 'W' or 'S'
cases to make it negative...

for i in range(0,20):
  y=d[i][2].split('\xb0')
  x=d[i][3].split('\xb0')
  ydeg,ymin=int(y[0].rstrip()),float(y[1].strip('\' N'))
  xdeg,xmin=int(x[0].rstrip()),float(x[1].rstrip("\' E").rstrip("\' W"))
  if re.search('\Z W','x[1]'): xdeg=-1*xdeg
  if re.search('\Z S','y[1]'): ydeg=-1*ydeg
  declat=abs(ydeg)+ymin/60
  declon=abs(xdeg)+xmin/60
  if ydeg < 0: declat=declat*-1
  if xdeg < 0: declon=declon*-1
  elv=int(d[i][4].strip('m'))
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] An interesting case... of east vs. west

2007-07-10 Thread John

I will work with this further, and report back once I find Alan's method...
but for now, this seems to work:

for i in range(0,20):
y=d[i][2].split('\xb0')
x=d[i][3].split('\xb0')
ydeg,ymin=int(y[0].rstrip()),float(y[1].strip('\' N'))
xdeg,xmin=int(x[0].rstrip()),float(x[1].rstrip("\' E").rstrip("\' W"))
if re.search("W",x[1]): xdeg=-1*xdeg
if re.search("S",y[1]): ydeg=-1*ydeg
declat=abs(ydeg)+ymin/60
declon=abs(xdeg)+xmin/60
if ydeg < 0: declat=declat*-1
if xdeg < 0: declon=declon*-1
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] green brackets?

2007-07-11 Thread John

This is how you put a newline or linebreak in a string: \n

-just adding that for someone's search later on, since 'newline' and
'linebreak' hadn't been mentioned yet ;)

(Should I be doing something else!?)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] binary data struct module

2007-09-03 Thread John
Hello,

I have an unformatted mixed type binary file I'm trying to read into Python.
So far, I've gotten as far as:

f2=file(infile,'rb')

Dfmt=['3i','13s','7i','2f','2i','2f','2i','i']  #format for binary reading
first bits

if f2:
print infile + ' has been opened'
#for ft in Dfmt:
#  print ft
a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt)
for ln in a: print ln

Which gives me:

/cygdrive/c/washakie/binfile has been opened
(21, 20060612, 0)
('Version 4.3',)
(21, 12, -86400, -86400, -900, 12, 24)
(-179.0, -90.0)
(360, 180)
(1.0, 1.0)
(24, 16)
(3,)

however, how can I now assign variables based on the 'generator object' a?
What exactly is this? When I try to do something like:

print a[0]
or
print a(0)

I get the error:
Traceback (most recent call last):
  File "readheader.py", line 20, in 
print a[0]
TypeError: 'generator' object is unsubscriptable

My question is, how can I now work with 'a' so that i can use the values?

Thanks!



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] more on reading binary... a better way?

2007-09-05 Thread John
Hello everyone,

Here's my solution for reading binary data (unformatted mixed types) and
packing it into a dictionary. It works, but somehow doesn't seem so
'pythonic'. Just seeking comments on how I might make it more efficient.
Thanks!

def readheader(filename):
 import struct
 
I={0:'rl',1:'ibdate',2:'ibtime',3:'version',4:'void1',5:'void2',6:'loutstep',7:'loutaver',8:'loutsample',9:'void3',10:'void4',11:'outlon0',12:'oulat0',13:'numxgrid',14:'numygrid',15:'dxout',16:'dyout',17:'void5',18:'void6',19:'numzgrid'}
 B={}
 f2=file(filename,'rb')
 #Define Header format
 
Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i']
#format for binary reading first bits
 if f2:
  print filename + ' has been opened'
  #create a dictionary from header file
  a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt]
  for i in range(len(a)):
   B[I[i]]=a[i][0]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] dynamic attribute assignment

2007-09-06 Thread John
I've just noticed that you can use the import statement to import variables,
such that a simple file such as vars.py:

# File with predefined variables
var1= 'some text'
var2= 2
var3=['a','b','c']

Would then, upon import, provide:

>>>vars.var1
'some text'
>>>vars.var2
2
>>>vars.var3
['a','b','c']

This is great, I had no idea! However, is there then a way to reassign or
update the values? For instance, can you say:

>>>vars.var1='some new text'

??

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


[Tutor] 2.5 to 2.4 problem with Int

2007-09-12 Thread John
I've written a program which calculates areas of grid cells distributed over
the globe. It works fine with Python 2.5, however, when I run it with
2.4(the Enthon edition) I get the following error:

OverflowError: long int too large to convert to int

It occurs on this line:

 for ix in range(nx): area[ix,iy]=gridarea

I have no idea which int it's referring to? The values of ix/nx will not
exceed 360, iy will not exceed 180. Any suggestions on what to change for
the backward compatability?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
The error occurs here:
area[ix,iy]=gridarea

The values of nx, ix, iy leading up to the error are:
360 0 0
360 1 0
360 2 0
360 3 0
360 4 0
360 ... ...
360 357 9
360 358 9
360 359 9
360 0 10
OverflowError: long int too large to convert to int

I guess then the problem occurs when iy goes from 9 to 10, but why?? It
wasn't a problem before and it's not a problem for ix???

Thanks!


On 9/13/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> John wrote:
> > I've written a program which calculates areas of grid cells distributed
> > over the globe. It works fine with Python 2.5, however, when I run it
> > with 2.4 (the Enthon edition) I get the following error:
> >
> > OverflowError: long int too large to convert to int
> >
> > It occurs on this line:
> >
> >  for ix in range(nx): area[ix,iy]=gridarea
> >
> > I have no idea which int it's referring to? The values of ix/nx will not
> > exceed 360, iy will not exceed 180. Any suggestions on what to change
> > for the backward compatability?
>
> Are you sure nx is not large? The argument to range() must be an int. I
> would split the line in two so you know which part of it is generating
> the error, then insert a print statement to give you some more data.
>
> Kent
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
In all it's glory: I'm just a bit embarrassed because I'm sure it's poor
coding:



def gridarea(H):
 """ returns an array of area corresponding to each nx,ny,nz
 %===
 %
 %---
 % input
 %   - H  : Header dict object with nx, ny, nz
 %
 % output
 %   - Numpy array area corresponding to nx,ny,nz
 %---
 %
 %---
 % last changes: ww, 2007
 %===
 """
 import math
 import numpy as N

 pih=math.pi/180.
 r_earth=6.371e6
 cosfunc = lambda y : math.cos(y*pih)*r_earth
 nz=H['nz']
 nx=H['nx']
 ny=H['ny']
 outlat0=H['outlat0']
 dyout=H['dyout']
 dxout=H['dxout']
 area=N.zeros((nx,ny)) #creates numpy array

 for iy in range(ny):
  ylata=outlat0+(float(iy)+0.5)*dyout
  ylatp=ylata+0.5*dyout
  ylatm=ylata-0.5*dyout
  if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih
  else:
   cosfact=cosfunc(ylata)
   cosfactp=cosfunc(ylatp)
   cosfactm=cosfunc(ylatm)
   if cosfactp", line 1, in ?
  File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ?
H,fail=readheader(pathname,1,0)
  File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in readheader
H['area'] = gridarea(H)
  File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea
area[ix,iy]=gridarea
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.5 to 2.4 problem with Int

2007-09-13 Thread John
for the record:
nx=360
ny=180
nz=1


On 9/13/07, John <[EMAIL PROTECTED]> wrote:
>
>
> In all it's glory: I'm just a bit embarrassed because I'm sure it's poor
> coding:
>
>
>
> def gridarea(H):
>  """ returns an array of area corresponding to each nx,ny,nz
>  %===
>  %
>  %---
>  % input
>  %   - H  : Header dict object with nx, ny, nz
>  %
>  % output
>  %   - Numpy array area corresponding to nx,ny,nz
>  %---
>  %
>  %---
>  % last changes: ww, 2007
>  %===
>  """
>  import math
>  import numpy as N
>
>  pih=math.pi/180.
>  r_earth=6.371e6
>  cosfunc = lambda y : math.cos(y*pih)*r_earth
>  nz=H['nz']
>  nx=H['nx']
>  ny=H['ny']
>  outlat0=H['outlat0']
>  dyout=H['dyout']
>  dxout=H['dxout']
>  area=N.zeros((nx,ny)) #creates numpy array
>
>  for iy in range(ny):
>   ylata=outlat0+(float(iy)+0.5)*dyout
>   ylatp=ylata+0.5*dyout
>   ylatm=ylata-0.5*dyout
>   if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih
>   else:
>cosfact=cosfunc(ylata)
>cosfactp=cosfunc(ylatp)
>cosfactm=cosfunc(ylatm)
>if cosfactp (r_earth**2-cosfactm**2)
>else: 
> hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2)
>
>
>   gridarea=2.*math.pi*r_earth*hzone*dxout/360.
>   for ix in range(nx):
>print nx, ix, iy
>area[ix,iy]=gridarea
>
>  return area #returns numpy array of area
>
>
>
> Here's the traceback:
>
> ...
>
> 360 357 9
> 360 358 9
> 360 359 9
> 360 0 10
> OverflowError: long int too large to convert to int
> Traceback:
>   File "", line 1, in ?
>   File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ?
> H,fail=readheader(pathname,1,0)
>   File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in
> readheader
> H['area'] = gridarea(H)
>   File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea
> area[ix,iy]=gridarea
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] summing arrays, along a dimension

2007-09-14 Thread John
>>> d
array([[0, 0, 1],
   [1, 2, 3],
   [2, 2, 4],
   [3, 6, 8]])
>>> e=reshape((d[:,-2]+d[:,-1]),(4,1))
>>> e
array([[ 1],
   [ 5],
   [ 6],
   [14]])

is there a better way to accomplish this?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] referencing vars()

2007-09-15 Thread John
#Set up writer
import csv
vardict=vars()
for var in vardict:
if var=='allcum' or var=='alldhdt':
outfile=in_path+'/'+dataset+'_'+str(var)+'.csv'
writer = csv.writer(open(outfile, "wb"))
writer.writerows(var)

I'm trying to do the above, but of course get an error because vardict is
only referencing vars(), thus changes size... also, I tried
vardict=[vars()], but this fails as well??

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


Re: [Tutor] referencing vars()

2007-09-17 Thread John
Kent,

Thanks this is exactly the solution I am looking for...  so simple.


On 9/15/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> John wrote:
> > #Set up writer
> > import csv
> > vardict=vars()
> > for var in vardict:
> > if var=='allcum' or var=='alldhdt':
> > outfile=in_path+'/'+dataset+'_'+str(var)+'.csv'
> > writer = csv.writer(open(outfile, "wb"))
> > writer.writerows(var)
> >
> > I'm trying to do the above, but of course get an error because vardict
> > is only referencing vars(), thus changes size... also, I tried
> > vardict=[vars()], but this fails as well??
>
> I'm not too clear what you are trying to do here. Do you want the values
> of the variables allcum and alldhdt?
>
> vars() gives you a dict whose keys are varible names and values are,
> well, the values. I think you are trying to write the contents of allcum
> to a file with allcum in the name?
>
> You could do it with vars like this:
>
> for var in ['allcum', 'alldhdt']:
> outfile=in_path+'/'+dataset+'_'+var+'.csv'
> writer = csv.writer(open(outfile, "wb"))
> writer.writerows(vars()[var])
>
> or you could iterate a list of name, value tuples directly:
>
> for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]:
> outfile=in_path+'/'+dataset+'_'+name+'.csv'
> writer = csv.writer(open(outfile, "wb"))
> writer.writerows(value)
>
> I think I prefer the second, even with the duplication of names; it
> feels more explicit to me.
>
> Another alternative would be to accumulate the values in a dict with
> keys 'allcum' and 'alldhdt'. Then you would look up in that dict instead
> of in vars().
>
> HTH,
> Kent
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] URLLIB / GLOB

2007-10-22 Thread John
Hello,

I would like to write a program which looks in a web directory for, say
*.gif files. Then processes those files in some manner. What I need is
something like glob which will return a directory listing of all the files
matching the search pattern (or just a simply a certain extension).

Is there a way to do this with urllib? Any other suggestions?

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


[Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
I have a file sitelocations:

STN_id[1]=AAA
STNlat[1]=58.80
STNlon[1]=17.40
STNelv[1]=20
STN_id[2]=BBB
STNlat[2]=42.45
STNlon[2]=25.58
STNelv[2]=2925

which in shell scripts I can simple 'source'. In Python I have to:
sitesFile=file('sitelocations','r')
sites=sitesFile.readlines()
i=0;
for l in sites:
if i==0:
STN_id.append(l.split('=')[1].strip('\n')); i+=1;
elif i==1:
STNlat.append(l.split('=')[1].strip('\n')); i+=1;
elif i==2:
STNlon.append(l.split('=')[1].strip('\n')); i+=1;
else:
STNelv.append(l.split('=')[1].strip('\n')); i=0;

Is there a better way??

Thanks!




-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
Thanks! This is helpful.. I like the RE approach as it's conceivable to
write a function...

On 10/27/07, Aditya Lal <[EMAIL PROTECTED]> wrote:
>
> You can source the file in python provided that you make it python
> friendly:-
>
> STN_id[1]='AAA' instead of STN_id[1]=AAA
> ...
>
>
> ---
> import re
> # Read the file
> fd = open('sitelocations')
> lines = fd.readlines()
> fd.close()
>
>
> # Make it python friendly: put all values in 'single quotes'
> cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> lines])
>
>
> # Create variables as list of appropriate size with default values
> (assuming 0)
> max = 5
> STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max
>
>
> # Execute the command and all your variables are populated ...
> exec(cmd)
>
>
> ---
> Not sure if this is a better way :) But atleast it will make the file
> sitelocations order invariant - implies you can interchange the lines
> without breaking the logic.
>
>
> Caveat - list in python starts at 0 index so STN_id[1] is not the first
> element but the second element. But you can filter unwanted items from the
> list if you want as in -
> [ x for x in STN_id if x != 0 ]
>
>
> HTH
> Aditya
>
>  On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> >  I have a file sitelocations:
> >
> > STN_id[1]=AAA
> > STNlat[1]=58.80
> > STNlon[1]=17.40
> > STNelv[1]=20
> > STN_id[2]=BBB
> > STNlat[2]=42.45
> > STNlon[2]=25.58
> > STNelv[2]=2925
> >
> > which in shell scripts I can simple 'source'. In Python I have to:
> > sitesFile=file('sitelocations','r')
> > sites=sitesFile.readlines()
> > i=0;
> > for l in sites:
> > if i==0:
> > STN_id.append(l.split('=')[1].strip('\n')); i+=1;
> > elif i==1:
> > STNlat.append(l.split('=')[1].strip('\n')); i+=1;
> > elif i==2:
> > STNlon.append(l.split('=')[1].strip('\n')); i+=1;
> > else:
> > STNelv.append(l.split('=')[1].strip('\n')); i=0;
> >
> > Is there a better way??
> >
> > Thanks!
> >
> >
> >
> >
> > --
> > Configuration
> > ``
> > Plone 2.5.3-final,
> > CMF-1.6.4,
> > Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> > Five 1.4.1,
> > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> > 4.1.1-51)],
> > PIL 1.1.6
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>
> > /listinfo/tutor <http://mail.python.org/mailman/listinfo/tutor>
> >
> >
>
>
> --
> Aditya
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
Ok, so trying to convert it to a function:

def source(ifile, *args):
""" takes a file object and a list of variables as input.
assumes, source file has variables in format:
VAR[i]=variable """

import re
# Read the file
lines = fd.readlines()
fd.close()

# Make it python friendly: put all values in 'single quotes'
cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
lines])

# Create variables as list of appropriate size with default
IM STUCK HERE... HOW DO I DYNAMICALLY CONVERT THE LIST OF VARIABLE NAMES TO
VARIABLES OF TYPE LIST

# Execute the command and all your variables are populated ...
exec(cmd)


Thanks,





> Thanks! This is helpful.. I like the RE approach as it's conceivable to
> write a function...
>
> On 10/27/07, Aditya Lal <[EMAIL PROTECTED]> wrote:
> >
> > You can source the file in python provided that you make it python
> > friendly:-
> >
> > STN_id[1]='AAA' instead of STN_id[1]=AAA
> > ...
> >
> >
> > ---
> > import re
> > # Read the file
> > fd = open('sitelocations')
> > lines = fd.readlines()
> > fd.close()
> >
> >
> > # Make it python friendly: put all values in 'single quotes'
> > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> > lines])
> >
> >
> > # Create variables as list of appropriate size with default values
> > (assuming 0)
> > max = 5
> > STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max
> >
> >
> > # Execute the command and all your variables are populated ...
> > exec(cmd)
> >
> >
> > ---
> > Not sure if this is a better way :) But atleast it will make the file
> > sitelocations order invariant - implies you can interchange the lines
> > without breaking the logic.
> >
> >
> > Caveat - list in python starts at 0 index so STN_id[1] is not the first
> > element but the second element. But you can filter unwanted items from the
> > list if you want as in -
> > [ x for x in STN_id if x != 0 ]
> >
> >
> > HTH
> > Aditya
> >
> >  On 10/27/07, John < [EMAIL PROTECTED]> wrote:
> >
> > >  I have a file sitelocations:
> > >
> > > STN_id[1]=AAA
> > > STNlat[1]=58.80
> > > STNlon[1]=17.40
> > > STNelv[1]=20
> > > STN_id[2]=BBB
> > > STNlat[2]=42.45
> > > STNlon[2]=25.58
> > > STNelv[2]=2925
> > >
> > > which in shell scripts I can simple 'source'. In Python I have to:
> > > sitesFile=file('sitelocations','r')
> > > sites=sitesFile.readlines()
> > > i=0;
> > > for l in sites:
> > > if i==0:
> > > STN_id.append(l.split('=')[1].strip('\n')); i+=1;
> > > elif i==1:
> > > STNlat.append(l.split('=')[1].strip('\n')); i+=1;
> > > elif i==2:
> > > STNlon.append(l.split('=')[1].strip('\n')); i+=1;
> > > else:
> > > STNelv.append(l.split('=')[1].strip('\n')); i=0;
> > >
> > > Is there a better way??
> > >
> > > Thanks!
> > >
> > >
> > >
> > >
> > > --
> > > Configuration
> > > ``
> > > Plone 2.5.3-final,
> > > CMF-1.6.4,
> > > Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> > > Five 1.4.1,
> > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> > > 4.1.1-51)],
> > > PIL 1.1.6
> > >
> > > ___
> > > Tutor maillist  -   Tutor@python.org
> > > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
> > >
> > >
> >
> >
> > --
> > Aditya
> >
>
>
>
> --
> Configuration
> ``
> Plone 2.5.3-final,
> CMF-1.6.4 ,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> 4.1.1-51)],
> PIL 1.1.6
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
The problem is the infies are also being used in a shell scripted
environment, they are frequently updated and cannot be changed.

So ideadly I could just define a function which sourced the file, assuming
the variable names passed in the *args list. So, yes, I know the names, they
just haven't been set in the program. I would like the source program to
then define them. My re is not so great, but I'm assuming the statement
here:

cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines])

assumes the pattern VAR[i]=variable , and then makes it Python friendly.

So it would look like:

my_source(fid,['STN_id','STNlat','STNlon','STNelv'])

then in the program, before exec(cmd) the *args list has to be converted
into empy lists, preparing it for the cmd. Does that make sense??

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


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
Here's where I am:


def source(filename, vList):
 """ takes a file object and a list of variables as input """
 import re
 # Read the file
 fid=open(filename,'r')
 lines = fid.readlines()
 fid.close()
 #how many variables
 ns=len(lines)/len(vList)
 #predefine the varibles
 for v in vList:
  exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))

 # Make it python friendly: put all values in 'single quotes'
 cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines])
 exec(cmd)
 for v in vList:
  exec( '%s=%s[1:]' % (v,v))

source('infile.py',['files','nfiles','nreleases'])

print files
print nreleases
print nfiles



But oddly, my output is:

[0, 'ASP_200603', 'ASP_200604', 'ASP_200605']
[0, '248', '240', '248']
[0, '3', '3', '3']



So, I am not properly getting rid of the list[0], is it something with the
'global' nature of the vairables... it looks like it's only changing
locallly in my source function.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
Note, i need the ns+1 because the 'source files are not zero indexed.

On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> Here's where I am:
>
>
> def source(filename, vList):
>  """ takes a file object and a list of variables as input """
>  import re
>  # Read the file
>  fid=open(filename,'r')
>  lines = fid.readlines()
>  fid.close()
>  #how many variables
>  ns=len(lines)/len(vList)
>  #predefine the varibles
>  for v in vList:
>   exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
>
>  # Make it python friendly: put all values in 'single quotes'
>  cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> lines])
>  exec(cmd)
>  for v in vList:
>   exec( '%s=%s[1:]' % (v,v))
>
> source('infile.py',['files','nfiles','nreleases'])
>
> print files
> print nreleases
> print nfiles
>
>
>
> But oddly, my output is:
>
> [0, 'ASP_200603', 'ASP_200604', 'ASP_200605']
> [0, '248', '240', '248']
> [0, '3', '3', '3']
>
>
>
> So, I am not properly getting rid of the list[0], is it something with the
> 'global' nature of the vairables... it looks like it's only changing
> locallly in my source function.
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread John
Thanks,

it's strange, it works within a script defined at the top, but if I try to
import it from a module it fails:

NameError: name 'files' is not defined



On 10/27/07, Aditya Lal <[EMAIL PROTECTED]> wrote:
>
>
>
> On 10/27/07, John <[EMAIL PROTECTED]> wrote:
> >
> > Note, i need the ns+1 because the 'source files are not zero indexed.
> >
> > On 10/27/07, John <[EMAIL PROTECTED] > wrote:
> > >
> > > Here's where I am:
> > >
> > >
> > > def source(filename, vList):
> > >  """ takes a file object and a list of variables as input """
> > >  import re
> > >  # Read the file
> > >  fid=open(filename,'r')
> > >  lines = fid.readlines()
> > >  fid.close()
> > >  #how many variables
> > >  ns=len(lines)/len(vList)
> > >  #predefine the varibles
> > >  for v in vList:
> > >   exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
> > >
> > >  # Make it python friendly: put all values in 'single quotes'
> > >  cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> > > lines])
> > >  exec(cmd)
> > >  for v in vList:
> > >   exec( '%s=%s[1:]' % (v,v))
> > >
> > > source('infile.py',['files','nfiles','nreleases'])
> > >
> > > print files
> > > print nreleases
> > > print nfiles
> > >
> > >
> > >
> > > But oddly, my output is:
> > >
> > > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605']
> > > [0, '248', '240', '248']
> > > [0, '3', '3', '3']
> > >
> > >
> > >
> > > So, I am not properly getting rid of the list[0], is it something with
> > > the 'global' nature of the vairables... it looks like it's only changing
> > > locallly in my source function.
> > >
> >
> >
> >
> > --
> > Configuration
> > ``
> > Plone 2.5.3-final,
> > CMF-1.6.4,
> > Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> > Five 1.4.1,
> > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> > 4.1.1-51)],
> > PIL 1.1.6
> >
>
> I think you need to define the variable global again otherwise it will
> re-assign the object in local space.
>
> exec( "global %s ; %s = %s[1:]" % (v,v,v) )
>
> --
> Aditya
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system call

2007-10-27 Thread John
I have the exact same situation, but system doesn't seem to wait. Here is my
pseudo code:

for i in attempts:  #attempts holds strings of shellscripts
cmd="%s which runs many different shell scripts and takes about an
hour" % (i)
os.system(cmd)
#debugging
print "Finished with %s" % (i)
raw_input("More debugging, shouldn't see this until shell scripts
are finished!")


But it prints the print statement and waits for raw_input instantly... Any
thoughts?



On 10/27/07, Eric Walker <[EMAIL PROTECTED]> wrote:
>
> disregard this one. I found the answer. I was using  spawn instead of
> os.system.
>
> Thanks.
>
> - Original Message 
> From: Eric Walker <[EMAIL PROTECTED]>
> To: tutor@python.org
> Sent: Saturday, October 27, 2007 9:55:05 AM
> Subject: [Tutor] system call
>
> Hello,
> I am trying to run a timing script but I need the python program to stop
> and wait for the executable to finish. Does anyone have any examples of
> doing this?
>
> Thanks
> Python Newbie
>
> __
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
>
> __
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system call

2007-10-28 Thread John
Here is my actual code (a section of a long script):

if os.path.isdir(ad) and aRun.split('_')[0]==STN_id[i] and in (aRun.split
('_')[1]):
   make_pages=os.path.join(BASEDIR,STN_id[i],SUBDIR[1],'make_pages')
   sedstr1="""cat %s | sed -e 's/ASYSmin=[0-9][0-9]*/ASYSmin=%s/g' > jnk"""
% (make_webpages,nf+1)
   sedstr2="""cat jnk | sed -e 's/ASYSmax=[0-9][0-9]*/ASYSmax=%s/g' > %s"""
% (nf+1,make_pages)
   cmd="""%s > %s """ % (make_pages,STN_id[i]+'.mw.out')
   print """ Now running make_pages for: %s """ % (files[nf])
   os.system(sedstr1)
   os.system(sedstr2)
   fail= os.system(cmd)
   print(cmd)
   if fail: print """For %s there was an error""" % (files[i])
   os.wait()
   print """Finished for %s """ % (files[i])
   raw_input('Continue?')

make_pages is  a shell script which usually is run with nohup and takes
anywhere from 1-24 hours to run, depending on ASYSmin, ASYSmax. If there the
same (which they are here) then it should take around one hour.

Perphaps I need to change the os.wait somehow? Or structure the
os.systemcall for cmd a little differently???

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


Re: [Tutor] 'source' in python or preloading variables

2007-10-28 Thread John
But won't if fail since the variabls in the file are not quoted?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] killing bash, sshd... dangerous?

2007-10-28 Thread John
Hello, I've written a little script with the intention of killing all of my
bash, sshd sessions... is this dangerous? How could I make it work so that
it didn't kill the session it was run from (as it is I suppose I have to run
it with nohup):


#!/usr/bin/env python
import os

cmd="ps -u myuser | grep 'bash' > .ps"
os.system(cmd)

pid=[]
fid=open('.ps','r')
for line in fid:
pid.append(line.split(' ')[0])

for i in pid:
cmd="""kill -9 %s""" % (i)
os.system(cmd)


cmd="ps -u myuser | grep 'sshd' > .ps"
os.system(cmd)

pid=[]
fid=open('.ps','r')
for line in fid:
pid.append(line.split(' ')[0])

for i in pid:
cmd="""kill -9 %s""" % (i)
os.system(cmd)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] killing bash, sshd... dangerous?

2007-10-28 Thread John
No, mostly just playing around with scripting and I have a problem
sometimes with cygwin where logging out from bash session, the xterm hangs,
so this seems to fix it... but it's not really the best solution... needs
some mods, I'm sure.


On 10/28/07, Tom Tucker <[EMAIL PROTECTED]> wrote:
>
> Instead of reading in an outputfile (.ps), try reading from command
> output.  The correct terminology escapes me (for file in
> os.popen(cmd).readlines():).
>
> Are you looking for a auto logout method? For example if no activity
> after X minutes kill the shell.  Bash and a few other shells have this
> functionality already.
>
>
>
>
>
> On 10/28/07, John <[EMAIL PROTECTED]> wrote:
> > Hello, I've written a little script with the intention of killing all of
> my
> > bash, sshd sessions... is this dangerous? How could I make it work so
> that
> > it didn't kill the session it was run from (as it is I suppose I have to
> run
> > it with nohup):
> >
> >
> >
> > #!/usr/bin/env python
> > import os
> >
> > cmd="ps -u myuser | grep 'bash' > .ps"
> > os.system(cmd)
> >
> > pid=[]
> > fid=open('.ps','r')
> > for line in fid:
> > pid.append(line.split(' ')[0])
> >
> > for i in pid:
> > cmd="""kill -9 %s""" % (i)
> > os.system(cmd)
> >
> >
> > cmd="ps -u myuser | grep 'sshd' > .ps"
> > os.system(cmd)
> >
> > pid=[]
> > fid=open('.ps','r')
> > for line in fid:
> > pid.append(line.split(' ')[0])
> >
> > for i in pid:
> > cmd="""kill -9 %s""" % (i)
> > os.system(cmd)
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] calculation with arrays: shape mismatch

2007-10-29 Thread John
Does anyone have an idea why I can't do this?

 for k in range(nr):
  contribution=N.zeros(shape(H['area']))
  contribution=[contribution+grid[:,:,z:,k,0]/A for z in
range(len(H['outheight']))]
  zplot[:,:,k]=zplot[:,:,k]+contribution;


And on the interactive line:
>>> shape(contribution)
(360, 180)
>>> shape(grid[:,:,0,0,0])
(360, 180)
>>>


But I get the error:
ValueError: shape mismatch: objects cannot be broadcast to a single shape

 for the highlighted line.

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


Re: [Tutor] calculation with arrays: shape mismatch

2007-10-29 Thread John
Sorry, here's the output from the command line

>>>run Day_footprint.py
trying...
header has been opened
succes!
Reading grid 2006051100 at: Mon Oct 29 16:57:57 2007
processing: 2006051100


Traceback (most recent call last):
  File "Day_footprint.py", line 48, in ?
contribution=[contribution+grid[:,:,z:,k,0]/A for z in
range(len(H['outheigh
t']))]
ValueError: shape mismatch: objects cannot be broadcast to a single shape

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


Re: [Tutor] calculation with arrays: shape mismatch

2007-10-29 Thread John
Well,

To be honest, part of the problem is that I work in about four different
Python environments!! I've had a hard time getting the scipy suite to work
fully on windows, and for number crunching it's just easier to run in linux.
This here was just a cut from running a script I wrote at the DOS prompt...
but that is not my usual flavor.

Anyway, the problem was in fact a shape mismatch. Ha! Imagine that ;)

Thanks for the feedback. The issue was in the dividing by A, I had to pull
that out separately and things worked.

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


[Tutor] Automating operations... os module, mysql operations, more...

2007-11-01 Thread John
I should begin by explaining I am not a sysadmin, I'm merely one trying to
use the right tool for the right job, and for my job I believe Python to be
that tool. Here is an outline of what I wish to accomplish, pointers to
modules, tools of interest, etc. would be greatly appreciated... Below each
number I propose the modules I've found, but please let me know if there are
better ones.. or others I should be aware of. Also, any good resources
regarding #2?? Thanks in advance!!

1) Maintain a mysql database which contains information, as well as
'control' variables, pointers to directories, etc.  for various shell
scripts / fortran code.
->pyMySQL

2) Query various servers to see if there is 'idyl' time/resources... send a
job to the server if it's available...


 3) Use python to check the file system for existing files (glob?) , decide
which 'jobs' need to be run, etc.
->os, sys, glob

4) Use python as glue between the db and the shell /fortran routines. For
this I picture python querying the db, 'writing' new CONTROL files, and
using subprocess to run the scripts / fortran.
->sys, os, subprocess

5) Update the db with information regarding the status of the various
scripts / fortran.
->pyMySQL

6) Have a portion of the information available to a plone site for dynamic
html generation.
->ZMySQLDBConn
->Z SQL Methods



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Automating operations... os module, mysql operations, more...

2007-11-01 Thread John
>
>
>
>
> > 2) Query various servers to see if there is 'idyl' time/resources...
> > send a job to the server if it's available...
> >
>
> This and 3 can be helped out with ipython
>
>
>
> >  3) Use python to check the file system for existing files (glob?) ,
> > decide which 'jobs' need to be run, etc.
> > ->os, sys, glob
> >
>
I'm not sure I follow this? ipython is a command line interpreter, no? How
ill that help me 'automate' tasks...

>
> > 4) Use python as glue between the db and the shell /fortran routines.
> > For this I picture python querying the db, 'writing' new CONTROL files, and
> > using subprocess to run the scripts / fortran.
> > ->sys, os, subprocess
> >
>
> I'd imagine SWIG may make it so you can actually call it if you make your
> fortran compiler spit out a C compatible library. I know that one of the
> Fortran95 compilers does this.
>

Seems this would require a bit more than is required... just running the
shell scripts, which run the fortran is all I'm desiring to accomplish today
;)


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


[Tutor] subprocess stdout nohup question

2007-11-02 Thread John
When I run a python script with nohup, my print statements are not being
written to nohup.out, why is that? Should nohup.out capture all stdout
statements?

-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with setting path

2007-11-02 Thread John
How did you install Python? I've found that the Enthought distribution to be
the simplest and quickest way to get up and running while having good
functionality (i.e. scipy up and running).

Active state releases a good version as well... and thus, welcome, to what
in my humble opinion (a newbie as well) is the hell of Python... that is,
there is a seemingly endless number of possible ways to configure the
installations. But that's the hell, the rest is grreat! So it's a sugar
coated hell once you get up and running ;)

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


Re: [Tutor] Help with setting path

2007-11-03 Thread John
Good point, I think that goes for learning a programming language in general
;)  Find one that works, and master it...

I'm starting to put together the picture of what a Python installation is,
but I have to admit, when you work on multiple machines regularly, it is a
bit challenging. Especially when you're starting out...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Some question about OO practice

2007-11-04 Thread John
I've now written my first set of Classes to do some fairly specific
processing for work I do. I have a few questions.

First, in looking through what I've done, I basically just incorporated all
my previous scripts into classes... they are still highly specific to my
application, though I did try to make them somewhat 'reusable' or general.
It is difficult though, as portions required hardcoding. For that I used the
__init__ method to define a bunch of 'hardcoded' variables, that could then
be set if they were passed on initiation.

I guess, I'm writing because I'm wondering now what people think about
writing classes versus just using scripts for things that are so specific.
It's hard for me to give an example, or show what I'm doing, but I would
appreciate thoughts on that matter.

One thing I am struggling with is how to assign *args and **kwargs if they
are passed, and how to ignore them if they are not... right now I do this:

def myfunc(self, *args,**kwargs):
   a=self.a
   b=self.b
   kwa=self.kwa
   kwb=self.kwb
   try:
a=args[0]; b=args[1]
kwa=kwargs['a']
 kwb=kwargs['b']
   except: pass


Where self.X is defined in the __init__ of the class. Is that correct?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'source' in python or preloading variables

2007-11-04 Thread John
Does anyone know why the script below works fine (in regards to the 'source
function') but when I try to uncomment the line from mymod import source and
use it that way without defining the function in the script, I get an error
that N_id does not exist. It must have something to do with namespace and
global variables I don't understand...


#!/usr/bin/env python

from PyF import *
#from mymod import source
vList=['N_id','Nlat','Nlon','Nelv']
## FUNCTION #
def source(filename, vList):
""" Reads a filename, collects variabls in file, and returns
variables.
Usage: source(filename, vList) where vList is a list of variables.

"""
import re
# Read the file
fid=open(filename,'r')
lines = fid.readlines()
fid.close()
#how many variables
ns=len(lines)/len(vList)
#predefine the varibles
for v in vList:
exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))

# Make it python friendly: put all values in 'single quotes'
cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
lines])
exec(cmd)
for v in vList:
exec( "global %s ; %s = %s[1:]" % (v,v,v) )


source('sites_ALL',vList)

for s in N_id:
fw=stnWeb(s)
fw.mkStnBase()
fw.mkWebBase()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Some question about OO practice

2007-11-04 Thread John
Thanks,

One last question (okay, one MORE question ;) ) when you call a
method/function with optionaly *args **kwargs, I'm finding I need to make
the statement like;

def myFunc(self, *args,**kwargs):
  do something


In ord to pass the kwargs:
myFunc(**kwargs) # where kwargs is a dictionary

or for args:
myFunc(a,b,c, etc.)

It is correct that you need to use the '**' in the 'calling' statement?




On Nov 4, 2007 2:31 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> John wrote:
> > I've now written my first set of Classes to do some fairly specific
> > processing for work I do. I have a few questions.
> >
> > First, in looking through what I've done, I basically just incorporated
> > all my previous scripts into classes... they are still highly specific
> > to my application, though I did try to make them somewhat 'reusable' or
> > general. It is difficult though, as portions required hardcoding. For
> > that I used the __init__ method to define a bunch of 'hardcoded'
> > variables, that could then be set if they were passed on initiation.
>
> You didn't show your original script or enough context for me to judge
> if this was a useful change. A program that uses classes rather than
> simple scripts is not necessarily 'better' than one that doesn't.
> Classes are a tool that is helpful in some circumstances but not all. In
> other words don't add classes to your programs just because it seems
> like a good idea. Some good reasons for using classes are here:
> http://personalpages.tds.net/~kent37/stories/00014.html
>
> > I guess, I'm writing because I'm wondering now what people think about
> > writing classes versus just using scripts for things that are so
> > specific. It's hard for me to give an example, or show what I'm doing,
> > but I would appreciate thoughts on that matter.
>
> It's ok for classes to be specific.
>
> > One thing I am struggling with is how to assign *args and **kwargs if
> > they are passed, and how to ignore them if they are not... right now I
> > do this:
> >
> > def myfunc(self, *args,**kwargs):
> >a=self.a
> >b=self.b
> >kwa=self.kwa
> >kwb=self.kwb
> >try:
> > a=args[0]; b=args[1]
> > kwa=kwargs['a']
> > kwb=kwargs['b']
> >except: pass
> >
> >
> > Where self.X is defined in the __init__ of the class. Is that correct?
>
> No, this will not assign from kwargs if args is not given. How about this:
> def myfunc(self, *args,**kwargs):
>try:
> a=args[0]; b=args[1]
>except TypeError:
> a=self.a
> b=self.b
>try:
> kwa=kwargs['a']
> kwb=kwargs['b']
>except TypeError:
>  kwa=self.kwa
> kwb=self.kwb
>
> Kent
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading and writing with csv then appending some data to a specific line

2007-11-04 Thread John
Remember to seek to the end of the file before you start writing. See:
http://mail.python.org/pipermail/python-list/2000-August/048839.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess help, nohup

2007-11-13 Thread John
Hello,

I've written a script which conducts several subprocess calls and then
ultimately calls a shell script which runs even more programs... my script
is using subprocess to execute a few sed calls, and then execute the script.
I'm getting strange behavior:

Here's a snippet of my script (any general comments are also welcome):

   if RUNS[k][3]==1: #model run complete, run is a DICT
compWebPages=self.getCompletedWeb() #returns a DICT, which
RUNS[k][0] COULD be a key
if RUNS[k][0] not in compWebPages.keys():
 runFile='make_'+RUNS[k][0]
 cmd = """sed -e 's/RUNmin=[0-9][0-9]*/RUNmin=%s/g' %s  > jnk""" %
(k,'make_wwwpages');
 subprocess.call(cmd,shell=True)
 cmd = """cat jnk | sed -e 's/RUNmax=[0-9][0-9]*/RUNmax=%s/g' > %s""" %
(k,runFile);
 subprocess.call(cmd,shell=True); subprocess.call('rm jnk',shell=True);
 os.chmod(runFile,0744)
 cmd="""./%s""" % (runFile)
 print "Starting %s" % (runFile)
 #subprocess.call(cmd,shell=True)
 q=raw_input('continue?');
 print "Done with: %s" % (RUNS[k][0])
 cmd="""rm %s""" % (runFile); subprocess.call(cmd,shell=True)


You'll notice, the last subprocess call is commented out. Right now I'm just
getting to that point to make sure everything is working. So, it seems to
work, but I'm not sure how to get it to work if I change the command to
nohup. I still want python to wait for it to return, in fact, I would like
to set the python job running in the background as well... so what I'm
looking at doing is:

% nohup myControl.py
   ---> which will make several subprocess.call(s) including some that
should be 'nohupped' as well...

Suggestions on the syntax of how to do this?

Thanks!






-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] MySQLdb install issue

2008-01-15 Thread John
Hello,

Does anyone know how to install MySQLdb into a python installation when the
machine you are working on does not have MySQL installed? I.E. the MySQL
installation is on a different server, but the site.cfg file for the MySQLdb
installation asks for the location of the mysql_config:


"
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
#mysql_config = /usr/local/bin/mysql_config

"

Thanks!

-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] what tools will i need to start my project ?

2006-03-19 Thread John
i'm new to programming and decided to go with python as my first language.  
my goal is to create an excel macros that will grab information from an  
html file and import it into my worksheet. I figure i should first start  
apart from excel then work on making it work with it (if it is even  
possible). is excel macros exclusively vb or is it possible to get excel  
to work with other languages... or maybe openoffice spreadsheet? either  
one, doesn't matter to me. the result will be a listing of all my movies  
complete with information from imdb.com. i already have something that  
does this in vb but i didn't write it and i'd like to create my own.

i read about find() and how it returns the index of the 1st character of  
what you searched for. from what i can read from the vb code i have, what  
i have to do is search for a start and end string and grab the string in  
between. This works because there is certain formatting/code that stays  
constant in the html files. so for example, if the title of a movie lies  
somewhere between  every time, i would need to  
grab the text between those start and finish points. Am i making any  
sense? So basically, i am asking what, in addtion to find(), do i need to  
read up about. I think the vb equiv is InStr() and something else..

i posted this on the python-forum and recieved only 1 response. I learned  
how to read from an html using file(). I'm also looking for a searchable  
directory of python tool usage. for example if i type file() it will give  
me an explanation of what it does and how to use it.

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


Re: [Tutor] help with slice

2008-04-02 Thread John
Thanks all for the posts,

I guess I'm thinking in 'matrices' and in a matlab syntax. So I was trying
to get the third element of a list of lists, or lists in a dictionay in
syntax like matlab (yes, I should be using numpy or scipy).

Anyway, Alan's final suggestion (and everyone else's) has helped me better
understand list syntax.

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


[Tutor] normalize an array

2010-11-26 Thread John
I know this is a simple problem, but I want to do it the most
efficient way (that is vectorized...)

import numpy as np

a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4]))
b = np.sum(a,axis=1)

for i,elem in enumerate(a):
a[i,:] = elem/b[i]



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


Re: [Tutor] normalize an array

2010-11-27 Thread John
Thank you both! Broadcasting is a concept I hadn't yet read about, but
knew was important for efficient python programming... thanks for the
link!


On Sat, Nov 27, 2010 at 6:44 PM, Eike Welk  wrote:
> Hello John!
>
> On Friday 26.11.2010 23:23:51 Peter Otten wrote:
>> John wrote:
>> > I know this is a simple problem, but I want to do it the most
>> > efficient way (that is vectorized...)
>> >
>> > import numpy as np
>> >
>> > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4]))
>> > b = np.sum(a,axis=1)
>> >
>> > for i,elem in enumerate(a):
>> >     a[i,:] = elem/b[i]
>> >
>> > suggestions?
>>
>> I'm not a numpy expert, but:
>>
>> (a.transpose()/np.sum(a, axis=1)).transpose()
>
> The underlying feature of Peter's solution is called broadcasting. For a
> detailed explanation look at:
> http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
>
>
> Eike.
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] modified dictionary class

2010-12-06 Thread John
Hello all,

I have been using this class extensively in my modules / scripts. It
provides the ability to .reference dictionary values. I find it handy,
but am afraid it may come back to haunt me at some point. Is there
anything wrong with using this?


class Structure(dict):
""" A 'fancy' dictionary. It provides 'MatLab' structure-like
referencing. Could also just define a generic class.
Caution: This may be deprecated in a future release.
"""
def __getattr__(self, attr):
# Fake a __getstate__ method that resturns None
if attr == "__getstate__":
return lambda: None
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value

def set_with_dict(self,D):
""" set attributes with a dict """
for k in D.keys():
self.__setattr__(k,D[k])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modified dictionary class

2010-12-06 Thread John
Hugo,

Thank you for the response, it's very helpful. I posted a question
earlier to this list (or possibly numpy) about how to create a 'matlab
like structure'. This was early in my learning of Python, and yes, the
intention was to have something that was similar to a matlab
structure... now, I've been using Python much more, and I realize that
this may be in fact 'un-Pythonic'. The problem is, I've used it
extensively throughout my existing modules, and I have become somewhat
comfortable with it...

I guess an alternative would be to simply define a generic class, no?

class Structure(object):
pass

Then, you could easily say:

S = Structure()
S.this = ['my slice of cheese']

and perhaps I would be being more 'pythonic'?? This I could quite
easily do, as, where I have used this class, I almost never actually
use the 'dictionary' like referencing...

--john



On Mon, Dec 6, 2010 at 3:37 PM, Hugo Arts  wrote:
> On Mon, Dec 6, 2010 at 2:47 PM, Alan Gauld  wrote:
>> Oops, too quick. I neant to add:
>>
>> But this line seems to return a value so the return values of this function
>> seem to be incompatible which is not a good design pattern.
>
> I agree it's not the clearest way to do this, but not because of
> incompatible return values. Attribute and Method access have the same
> syntax on objects, and __getattr__ is only called if the attribute
> isn't found "in the usual places," so it won't hide other methods. In
> other words:
>
>>>> a = Structure()
>>>> a["spam"] = 5
>>>> a.__getstate__()
> None
>>>> a.spam
> 5
>
> Doesn't look that strange to me, interface-wise. Attribute access
> sometimes returns a function and sometimes not. The comment
> specifically states it's faking a method, so it's pretty clear.
>
> I do have a few other gripes though:
>
> * why not just define __getstate__ in the class? why return a new
> lambda every time when you can just write "def __getstate__(self):
> return None"  and be done with it? This also simplifies getattr.
>
> * it's now impossible to have keys that collide with a method name:
> dict, items, keys, clear, popitem, et cetera. You can set them without
> error, but when you try to get them you'll get the old method, which
> might cause hard-to-find bugs
>
> * it's not much of an advantage over regular dicts, really. You limit
> yourself to string keys, you make it very unclear that you're using a
> dict, it's not as efficient, and really just unpythonic in general.
> Why do this at all? To make python more Matlab-like?
>
> Hugo
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] calling a method within a function

2010-12-07 Thread John
Hello,

I have a strange problem with a piece of code I've written. It's a bit
overly complicated to make an example with, but the gist is below. But
in the example below, it works. However, in my example, when I call
the method from within the function, it returns something other than
what I expect. If I call the method outside the function, it behaves
properly???



class DataHolder():
def __init__(self):
self.x = np.arange(100)
def f(self,wl):
f = np.sin(self.x) ** wl
return f


def function(DH,wl=20):
f = DH.f(wl)
plt.plot(DH.x,f)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] calling a method within a function

2010-12-08 Thread John
I understand... but don't blame me if it hurts your head ;)

The class is here:
http://python.pastebin.com/gPpep50Y

The function is here:
http://python.pastebin.com/faK0vZ8U

The issue is with the 'reflectance' method of the FlightData class
(line 76). You can see in the class definition I now just add
reflectance to self, but before I was trying to return it, and in the
function (line 38-40) I was calling the method to get the array.

On Ipython it worked fine to call the method and get a refl array. The
array worked as expected (ie. refl.max(), refl.min() returned floats).
But when I passed the same FlightData object to the function and
called it inside it would not work. It would still return a
numpy.ma.core.MaskedArray, but the max and min methods on the array
returned empty values, which caused my function to crash.




On Wed, Dec 8, 2010 at 2:18 AM, Alan Gauld  wrote:
>
> "John"  wrote
>
>> I have a strange problem with a piece of code I've written. It's a bit
>> overly complicated to make an example with, but the gist is below. But
>> in the example below, it works. However, in my example, when I call
>> the method from within the function, it returns something other than
>> what I expect.
>
> Care to give us a clue?
>
> What did you expect?
> What did you get?
> What does the real code look like?
>
> Its a bit hard to diagnose your problem based on a bit of code that
> works and a loose description of your dissapointment with another
> bit of code that may or may not work - depending on what you
> expected!
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Odd behavior with eval, list comps, and name lookup

2011-02-18 Thread John
I noticed some odd behavior relating to eval(). First, a baseline case for
behavior:

>>> def test():
... x = 5
... return [a for a in range(10) if a == x]
...
>>> test()
[5]

So far so good. Now let's try eval:

>>> c = compile('[a for a in range(10) if a == x]', '', 'single')
>>> eval(c, globals(), {'x': 5})
Traceback (most recent call last):
File "", line 1, in 
File "", line 1, in 
File "", line 1, in 
NameError: global name 'x' is not defined

Looks like 'x' is searched for only among the globals, bypassing the locals.
The same behavior is seen between exec and eval, with and without compile,
and between 3.1.3 and 3.2rc2. Given simpler code without a list comp, the
locals are used just fine:

>>> c = compile('a=5; a==x', '', 'single')
>>> eval(c, {}, {'x': 5})
True

Could anyone help me understand these scoping rules? Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with a class

2011-08-24 Thread John
Hello, I have a class that has an attribute that is a dict which I
fill with more dicts. I've created a function to return those
dictionaries if a key is provide, otherwise, it returns the 'default'
dictionary.

I have the following methods (see below), it seems the update_options
method is fine, but I'm not sure about the override_options method...
and for that matter, I'm not sure this is the best approach overall...
any comments, critiques?

Thank you,
john

class Runner(object):
""" Initiate with an optional dictionary of settings.

Defaults are set in the options dictionary, which can be overridden.

"""
# Simplest default:
default_options = {
  'file' : '../data/input.dat',
  'wavelength' : '310.0 310.0'
  }


def __init__(self, **kwargs):

if 'options' not in kwargs:
self.options = copy(self.default_options)
self.run_queue = {}

def _get_from_queue(self, queue_key):
""" internal method to set options """

if queue_key:
if queue_key not in self.run_queue:
raise ValueError('queue_key: {0} not in
queue'.format(queue_key))
else:
return self.run_queue[queue_key]
else:
return self.options


def update_options(self, options, queue_key=None):
""" update the options dictionary using a dict """
assert isinstance(options, dict), "update options requires a dict"
old_options = self._get_from_queue(queue_key)
old_options.update(options)


def overide_options(self, options, queue_key=None):
""" completely overide the options dict """

assert isinstance(options, dict), "override options requires a dict"
old_options = self._get_from_queue(queue_key)
old_options = options

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


Re: [Tutor] help with a class

2011-08-24 Thread John
Thank you. I've corrected the KeyError, and changed the function to:

def overide_options(self, options, run_id=None):
""" completely overide the options dict """

assert isinstance(options, dict), "override options requires a dict"
if run_id in self.run_queue:
self.run_queue[run_id] = options
else:
self.options = options
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] understanding **kwargs syntax

2011-08-25 Thread John
Just a quick question,

is it wrong to use the *args and **kwargs ( the latter in particular)
when DEFINING a function?

def fest(**kwargs):
""" a function test """
keys = sorted(kwargs.keys())

print("You provided {0} keywords::\n".format(len(keys)))
for kw in keys:
print("{0} => {1}".format(kw, kwargs[kw]))

Are there some good examples of when this would be a good idea to implement?

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


Re: [Tutor] help with a class

2011-08-25 Thread John
Thanks for the feedback. I wasn't aware about the assert usage not
being intended for production code.

On Wed, Aug 24, 2011 at 11:37 PM, Alan Gauld  wrote:
> On 24/08/11 21:03, Prasad, Ramit wrote:
>>
>> I was under the impression that asserts are more for testing
>
>> than for production code
>
> That's true.
>
>> def overide_options(self, options, run_id=None):
>>
>>         if not isinstance(options, dict):
>>                 raise TypeError("override options requires a dict")
>
> This is good if you want to keep the check in for production.
> But using an assert here while testing then removing it from production
> would be a valid use too. The typecheck is not required for the function to
> work if you are confident of the data being passed in. assert checks the
> data while you are gaining that confidence.
>
> So either approach is valid.
> It all depends on how variable your input data is going to be.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with 'organization'

2011-08-25 Thread John
Hello, I am writing a module that will have two classes ('runners') I
am calling them, as they will ultimately use subprocess to run a
command line program, so they are basically option parsers, etc...

As I wrote the second 'runner', I realized many of the methods are
going to be the same as the first, so I would actually like to create
a third class that has the methods which are mutual between the two.
The problem are the 'self' calls

I know a code example might help, so I try to show it here (my code
I'm afraid is too complex and ugly at the moment). You can see the it
fails because MyTools doesn't have 'this' attribute...

class MyTools:
def f(self, this):
print(this)

def foo(self):
this = self.this
print(this)

class MyProcess:
def __init__(self):
self.tools = MyTools()

self.this = 'My Process, this'

self.tools.f(self.this)

self.tools.foo()

if __name__ == "__main__":
mp = MyProcess()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding the differences between two lists

2011-08-25 Thread John
Not entirely sure, but I think it is as simple as:

scanResults = open('scanResults.txt', 'r').readlines()
verifiedList = open('verifiedList.txt', 'r').readlines()

Now both are lists. I assume each mac address is on it's own line?

-john


On Thu, Aug 25, 2011 at 8:56 PM, Justin Wendl  wrote:
> Hello,
>
> Bare with me, as I am new to Python and a beginner programmer.
> I am trying to compare two lists (not of the same length), and create a new
> list of items that are -not- found in both lists.
>
> Scenario: I have a list of MAC addresses that are known and good, and am
> comparing it to a list of MACs found in a scan.  I want to weed out the
> those which are unknown.  I am using IDLE (Python 2.7) on Windows, and all
> files are in the same directory.
>
> Code:
>
> scanResults = open('scanResults.txt', 'r')
> verifiedList = open('verifiedList.txt', 'r')
> badMacs = []
>
> for mac in scanResults:
>   if mac not in verifiedList:
>     print mac
>     badMacs.append(mac)
>   else:
>     break
>
>
> When I print 'badMacs', the results come up empty:
> []
>
>
> Any help would be greatly appreciated!
>
> Regards,
> Justin
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with 'organization'

2011-08-25 Thread John
Ha! Inheritance!

On Thu, Aug 25, 2011 at 7:51 PM, John  wrote:
> Hello, I am writing a module that will have two classes ('runners') I
> am calling them, as they will ultimately use subprocess to run a
> command line program, so they are basically option parsers, etc...
>
> As I wrote the second 'runner', I realized many of the methods are
> going to be the same as the first, so I would actually like to create
> a third class that has the methods which are mutual between the two.
> The problem are the 'self' calls
>
> I know a code example might help, so I try to show it here (my code
> I'm afraid is too complex and ugly at the moment). You can see the it
> fails because MyTools doesn't have 'this' attribute...
>
> class MyTools:
>    def f(self, this):
>        print(this)
>
>    def foo(self):
>        this = self.this
>        print(this)
>
> class MyProcess:
>    def __init__(self):
>        self.tools = MyTools()
>
>        self.this = 'My Process, this'
>
>        self.tools.f(self.this)
>
>        self.tools.foo()
>
> if __name__ == "__main__":
>    mp = MyProcess()
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] understanding **kwargs syntax

2011-09-08 Thread John
Following up on this...

Why does pylint seem to think it is a bad idea?

Description ResourcePathLocationType
ID:W0142 plot_ts_array_split_x: Used * or **
magic   tsplot.py   /research.plot  line 299PyLint Problem

Thanks,
john


On Thu, Aug 25, 2011 at 10:44 AM, Alan Gauld  wrote:
> On 25/08/11 09:27, John wrote:
>>
>> Just a quick question,
>>
>> is it wrong to use the *args and **kwargs ( the latter in particular)
>> when DEFINING a function?
>
> No, in fact it's essential if you don't know in advance what arguments are
> going to be passed to the function. This is very common if you are wrapping
> another function that itself takes variable arguments.
>
>> def fest(**kwargs):
>>     """ a function test """
>>     keys = sorted(kwargs.keys())
>>
>>     print("You provided {0} keywords::\n".format(len(keys)))
>>     for kw in keys:
>>         print("{0} =>  {1}".format(kw, kwargs[kw]))
>>
>> Are there some good examples of when this would be a good idea to
>> implement?
>
> GUI frameworks like Tkinter often take variable numbers of configuration
> values. If you want to wrap that with a
> function of your own you can do something like(pseudocode):
>
> def myfunc(**kwargs):
>   if some interesting arg exists
>        do something with it
>   return wrappedFunc(kwargs)
>
> There are plenty other cases, try grepping the standard library code
> for lines with def and **kwargs for some examples...
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Doctest error!

2011-11-17 Thread John


Hi all,
When i run a doctest on this piece of code (shown at bottom) i get this error 
message [from the doctest]:



Trying:
rot13('5 The Parade')
Expecting:
'5 Gur Cnenqr'
**
File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13
Failed example:
rot13('5 The Parade')
Expected:
'5 Gur Cnenqr'
Got:
'B-aur-]n\x7fnqr'
Trying:
rot13('5 Gur Cnenqr')
Expecting:
'5 The Parade'
**
File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13
Failed example:
rot13('5 Gur Cnenqr')
Expected:
'5 The Parade'
Got:
'B-T\x82\x7f-P{r{~\x7f'



An one have any idea why? (I'm guessing its to do with the numbers)


code:

def rot13(s):

"""
>>>   type(rot13("bob"))

>>>   len(rot13("foobar"))
6
>>>   rot13("abc")
'nop'
>>>   rot13("XYZ")
'KLM'
>>>   rot13('5 The Parade')
'5 Gur Cnenqr'
>>>   rot13('5 Gur Cnenqr')
'5 The Parade'
"""
result = '' # initialize output to empty
for char in s:  # iterate over string
if int:
char_low = s.lower()
if char_low<= 'm':
dist = 13
else:
dist = -13
char = chr(ord(char) + dist)
result+=char
return result


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


[Tutor] IndexError: list index out of range

2011-11-21 Thread John


Hi all,

I have wriiten the following code:
[Segment]


 def survivor(names, step):

index = step - 1
next = names
while len(next)>  1:
next.remove (next[index])



However when ever i run it i get this error message:

Traceback (most recent call last):
  File "", line 1, in
survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
"Felicity", "Greg", "Harriet"], 4)
  File "", line 5, in survivor
next.remove (next[index])
IndexError: list index out of range

Any ideas about whats causing this error?

Big thanks,

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


[Tutor] Python code trouble!

2011-11-21 Thread John

Hi all,

I have attempted to create a programme which removes every Nth person 
from the list until there is only one name remaining. N is inputted by 
the user.


Here is the code:

def survivor(names, step):
next = names
while len(next) > 1:
 index = step - 1
 next.remove (next[index])
index = index + step - 1
while index > len(next):
index = index - len(next)
if index == len(next):
index = 0
return names[0]



To me is appears to be correct, however when i test it i get the 
following message:




>>> survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", 
"Felicity", "Greg", "Harriet"], 4)
['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg', 
'Harriet'] 3

['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig'] 3

Traceback (most recent call last):
  File "", line 1, in 
survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", 
"Felicity", "Greg", "Harriet"], 4)

  File "", line 6, in survivor
next.remove (next[index])
IndexError: list index out of range


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


[Tutor] python 2.7.1

2012-09-06 Thread john
print "hello world" #this is just something to say





>>> /Users/jonathan/Documents/hello.py 
  File "", line 1
/Users/jonathan/Documents/hello.py 
^
SyntaxError: invalid syntax

what am i doing wrong?

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


Re: [Tutor] about the gui development

2015-06-13 Thread john

Interesting question - what will be the end platform.

If you really want a python solution:
Tablets. phones, desktops - Kivy (very promising)
Tablets. phones, desktops - PyQt
Desktops - wxPython, tk, Dabo (python 2.7 at the moment)

All the other GUI frameworks either have a very small following or are 
dying (my opinion of course).


If you are not concerned with what language is used:
Consider all the web frameworks.
Several of the web frameworks work on the desktops, and are browser 
friendly.  Atom/electron (not sure about the name)

but in general web frameworks (no matter which one) is all about browsers.

Johnf

On 06/13/2015 10:15 AM, Laura Creighton wrote:

The final thing to consider is, do you really want to do gui programming
at all, or would you be happier developing something that runs in a browser?
If that has appeal, well, you guessed it, we have lots of browser
frameworks, as well.


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


Re: [Tutor] Python excel filter

2015-10-26 Thread john

take a look at python-excel

xlwt is what I use. BTW there are others Johnf



On 10/26/2015 05:21 AM, Lucas Mascia wrote:

Hello,

I would like some guidance in a way to filter data from an excel sheet
(.xlsx)

I will be exporting an extensive table from a website with 400x20 infos. In
this sheet, I need to apply 3 or 4 filters and collect the amount of info
it shows then. Eg.:

1 - Export .xlsx from website
2 - Run python to filter
2.1 - Filter by client A
2.2 - Filter by task A
2.3 - Filter by Person A
3 - Repeat filter for different clients, tasks and persons
4 - Collect the amount each person does inside each client.


Please Help guide my through a starting poing

Thank you,

Lucas R. Mascia

 | VIEW MY | 

"It is not the strongest of the species that survives, nor the most
intelligent that survives. It is the one that is most adaptable to change."
  - Darwin.
___
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] Best tool for programming interactive games in Python

2016-03-30 Thread john

On 03/30/2016 04:27 AM, wolfrage8...@gmail.com wrote:

I have a few students who are interested in creating interactive games in
Python. We have learned how to use tkinter but we are looking for
something more robust. I tried using pygame 

I recommend Kivy; because then it is easy to take the app from
computer to Phone; which opens the world of touch devices!
Though not specifically made for games it works very well for my
purposes which are a game.


I believe Kivy requires pygame so he would get the same error.

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


Re: [Tutor] UPDATE, pyhthon+postgre

2016-06-01 Thread john

cursor1.execute("""UPDATE employee SET
name=%s,
add=%s,
add1=%s,
city=%s,
state_county=%s,
country=%s,
basic=%s,
WHERE group_code = %s""" %
(name,add,add1,city,state_county,country,basic,grpCode))

It appears that you are not required to provide any time or date since you 
created a default.  Of course that assumes you want today and now.

If that assumption is wrong then lookup "datetime".  To make life a little easier lookup 
the module "dateutil".  You would use either of those modules to convert your python 
input to the correct output for postgres (actually for any sql database).

Hint:  if the field requires a string you should place quotes around the 
placeholder as in '%s'.

Johnf




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


Re: [Tutor] GUI development with Python 3.4.1

2014-09-18 Thread john

On 09/18/2014 06:07 AM, Juan Christian wrote:
On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian 
mailto:juan0christ...@gmail.com>> wrote:


I need to develop a GUI for my Python pogram, I already read the
GuiProgramming page (https://wiki.python.org/moin/GuiProgramming).
For me, the best so far was 'gui2py'.

The problem is that I need a simple "C#/Java-ish" GUI builder,
that is easy and simple, coding all the GUI by hand is boring, I
prefer to focus on the logic, on the actual program code, than
coding the GUI.

Anyone here already used 'gui2py'
(https://github.com/reingart/gui2py)? Any other good alternatives?


Anyone?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Dabo has a designer (currently moving to support wxPython 3.x). That 
said, the link you first provided suggested there was a designer for 
gui2py?


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


[Tutor] sub-modules and python3

2017-05-31 Thread john

Hi folks,

In the past I used a simple "import filename" for sub-modules in python 
2.  With python 3 I have run into errors reported (file not found) using 
python 2 import statements.  But I'm not asking how to correct the 
import as I am able to change the way I write the import as a work 
around - but I'm importing all the files at once.  What I want to know 
is what is the best practice for my situation.


Is there a simple way using python 3  to emulate python 2 imports?

Is there a standard python 3 import tool for sub-modules (files)?

Is it acceptable to add/change the os path to allow my app to find the 
modules/files?


Any help or thoughts on the matter is welcome.


Johnf


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


[Tutor] maximum value in a Numeric array

2004-12-10 Thread Ertl, John
All,

I am trying to get the maximum value in a 2-D array.  I can use max but it
returns the 1-D array that the max value is in and I then I need to do max
again on that array to get the single max value.

There has to be a more straightforward way...I have just not found it.

>>> b = array([[1,2],[3,4]])
>>> max(b)
array([3, 4])
>>> c = max(b)
>>> max(c)
4
>>>

I could also flatten the array to 1 D first then do max but the array I am
going to be working with is fairly large.

Thanks 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   7   8   9   10   >