Re: [Tutor] Omitting lines matching a list of strings from a file

2010-02-24 Thread Reed O'Brien



def main():
   infile = open("list.txt", "r")
   for line in infile:
   state = line[146:148]
   omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR',  
'RI', 'SD', 'VI', 'VT', 'WI']

   for n in omit_states:
   if state != n:
   print line
   infile.close()
main()


If state not in omit_states:
process_line(line)

~ro

--
Sent from a mobile device.

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


Re: [Tutor] IP-range

2009-05-25 Thread Reed O'Brien

On May 24, 2009, at 11:18 PM, Paras K. wrote:


Hello,

I came across your answer / assistance on the IP range.


I recommend looking at the ipaddr library:

http://svn.python.org/projects/python/trunk/Lib/ipaddr.py

There is some Sphinx documentation with the python 2.7 docs and some  
on the original google code page.


I am fairly new to the python world of programming. However, up to  
this point I have always been able to get my programs to work by  
reading the books or following the guides I find through google.com


Here is what I have to do:

I have to read a number of cvs files into 1 large file. (I have been  
able to get that done through a perl script). But after I get it  
into a large cvs file, I need to be able to look at each row and see  
if it falls within a specific IP ranges.


IP Ranges:

162.x.x.x
151.130.x.x
145.x.x.x

These are just some examples of the IP ranges.

The csv file has data like below:

63.145.40.32
Gnutella File Search
14
5/15/2009 0:48
151.40.133.25
Gnutella File Search
14
5/14/2009 16:21
145.133.19.147
BitTorrent Client Activity
13
5/14/2009 19:20

Here is my source code so far:

import sys
import win32api
import win32ui
import shutil
import string
import os
import os.path
import csv

#Global Variables
P2Pfiles = []


#still in the development process -- where to get the files from
#right now the location is C:\P2P
def getp2preportdestion():
win32ui.MessageBox('Welcome to P2P Reporting.\nThis script is  
designed to aid in the P2P reporting. \n\nThe locations of P2P  
Reports should be in C:\P2P \n\nWith no subdirectories.\n\n\n\n 
\nVersion 1.0 - \n\nPress "OK" to continue with this script.')

#p2pdrive=raw_input("Enter the drive letter:  ")
#p2pdir=raw_input("Enter the directory name:  ")
#p2preport = p2pdrive +':\\'+p2pdir+'/'
p2preport = 'C://P2P\\'
return p2preport





#Main Program

#Get location of directories
p2ploc = getp2preportdestion()

#Checking to make sure directory is there.
if os.path.exists(p2ploc):
if os.path.isfile(p2ploc +'/p2pmerge.csv'):
win32ui.MessageBox('Merge File exists..will continue with  
program')

else:
 win32ui.MessageBox('Merge File does not exists, script will  
exit. Please run the perl script first.')

 exit()
else:
   win32ui.MessageBox('The C:\P2P directory does not exists.\n 
\nPlease create and copy all the files there.\nThen re-run this  
script')

   exit()

reader = csv.reader(open('C://P2P/p2pmerge.csv', "rb"))
p2pwriter = csv.writer(open('C://P2P\P2PMerge4.csv', "wb"))
for row in reader:
p2pwriter.writerow([row])

win32ui.MessageBox('I am here')


Any assistance will be greatly appricated!!!

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


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


Re: [Tutor] iterating over a sequence question..

2007-06-17 Thread Reed O'Brien

On Jun 17, 2007, at 3:44 AM, John Fouhy wrote:

> On 17/06/07, Iyer <[EMAIL PROTECTED]> wrote:
>>
>> say, if I have a list l = [1,2,3,5]
>>
>> and another tuple t = ('r', 'g', 'b')
>>
>> Suppose I iterate over list l, and t at the same time, if I use  
>> the zip
>> function as in zip(l,t) , I will not be able to cover elements 3  
>> and 5 in
>> list l
>>
> l = [1,2,3,5]
> t = ('r', 'g', 'b')
> for i in zip(l,t):
>> ... print i
>> ...
>> (1, 'r')
>> (2, 'g')
>> (3, 'b')
>>
>> is there an elegant way in python to print all the elements in l,  
>> while
>> looping over list t, if len(t) != len(l) as to get the output:
>>
>> (1, 'r')
>>  (2, 'g')
>>  (3, 'b')
>> (5, 'r')
>
> Check out the itertools module.  I don't have the ability to test this
> right now, but try something like:
>
> import itertools
> lst = [1,2,3,5]
> t = ('r', 'g', 'b')
>
> itertools.izip(lst, itertools.cycle(t))
>
> -- 
> John.
>

+1 for John's solution

usage:
 >>> [x for x in itertools.izip(lst, itertools.cycle(t)]
 >>> [(1, 'r'), (2, 'g'), (3, 'b'), (5, 'r')]


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


Re: [Tutor] how can I compare a local directory or file with a remote one

2007-06-20 Thread Reed O'Brien

On Jun 20, 2007, at 2:03 PM, Richard Querin wrote:

> I'm interested in writing a quick script that would run a diff-type
> command that would compare a local directory to a remote one to
> identify the changes in the files within that directory.
>
> I was initially thinking that I would maybe use the linux diff command
> in conjunction with the wget command (or something similar) to create
> a local copy but that involves downloading files. Is there any way in
> python to do a similar thing but without having to download a copy of
> the remote files/directories?
>
> Any ideas?
>

At first blush it sounds to me like you want rsync, as has been  
pointed out.  If on of the systems is running an OS that doesn't come  
with rsync... I have used http://www.vdesmedt.com/~vds2212/rsync.html  
to achieve the same result.

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


Re: [Tutor] how can I compare a local directory or file with a remote one

2007-06-21 Thread Reed O'Brien
On Jun 21, 2007, at 9:06 AM, Lloyd Kvam wrote:

> On Wed, 2007-06-20 at 23:51 -0400, Reed O'Brien wrote:
>> On Jun 20, 2007, at 2:03 PM, Richard Querin wrote:
>>
>>> I'm interested in writing a quick script that would run a diff-type
>>> command that would compare a local directory to a remote one to
>>> identify the changes in the files within that directory.
>>>
>>> I was initially thinking that I would maybe use the linux diff  
>>> command
>>> in conjunction with the wget command (or something similar) to  
>>> create
>>> a local copy but that involves downloading files. Is there any  
>>> way in
>>> python to do a similar thing but without having to download a  
>>> copy of
>>> the remote files/directories?
>>>
>>> Any ideas?
>>>
>>
>> At first blush it sounds to me like you want rsync, as has been
>> pointed out.  If on of the systems is running an OS that doesn't come
>> with rsync... I have used http://www.vdesmedt.com/~vds2212/rsync.html
>> to achieve the same result.
>>
>
> I downloaded the file from the web site, but was disappointed to see
> that there appears to be no support for any network transport.  It
> simply operates on locally mounted directories.  I only did a cursory
> scan of the source code.  Did I miss something?
>
> Certainly the program provides useful example code for file  
> comparisons,
> but it does not appear to directly support any kind of remote
> processing.
>
> When I need to deal with Windows computers, I sorely feel the lack of
> ssh, rsync, and sshfs.
>

It has been a couple years since I have used it, but I am sure I did  
it across a network via SMB.  I no longer work there, so I  
unfortunately don't have access to what I did.

I remember it being over a network because the www server was  
separate from the backup server.  I may have done it on the Windows  
machine and had the remote N*X SMB mounted as a network drive. I  
think I also used putty on a Windows server to make an ssh tunnel to  
work over at another project.

To my great fortune I don't currently have to deal with windows at  
all (currently).

~r


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


Re: [Tutor] using shelve

2007-06-21 Thread Reed O'Brien


On Jun 21, 2007, at 9:59 PM, [EMAIL PROTECTED] wrote:

I created a shelf called 'myshelf' and put two objects in it, a  
string and a list. When I open the shelf I get:



d=shelve.open('/Users/development/Desktop/myshelf')
d.keys()

['dir1', 'dir2']

d
{'dir2': '/Users/development/Desktop/RSSReaderApp/RSS.db', 'dir1':  
['.DS_Store', '.localized', 'access the latest version', 'Python  
Quick Reference.webloc', 'rssdb', 'workspace']}


It seems that when you use shelve.open(), it actually brings the  
entire shelf dictionary into memory, accessible through d.


What if you had 100 objects in myshelf, or 1000 or 100,000?  
Wouldn't it get bogged down?


If so, what is it good for and how would you store a large number  
of objects? (Storing strings and lists in an sql database is  
probably the way to go for this simple example, but what if  you  
had more complex objects?)


Thanks
Chris V.





have a gander at:
http://codeidol.com/python/python3/Databases-and-Persistence/

As well as the shelve docs.

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


Re: [Tutor] using shelve

2007-06-22 Thread Reed O'Brien
On Jun 22, 2007, at 7:26 AM, Kent Johnson wrote:

> Reed O'Brien wrote:
>> have a gander at:
>> http://codeidol.com/python/python3/Databases-and-Persistence/
>
> That URL points to a (presumably) stolen copy of the book  
> Programming Python by Mark Lutz. If you like it I hope you will buy  
> a copy.
> http://www.oreilly.com/catalog/python3/index.html
>
> They even took the promotional text from O'Reilly's web site! Compare
> http://codeidol.com/python/ with the second paragraph from
> http://www.oreilly.com/catalog/python3/index.html#top
>
> Kent


Thanks for the heads up, Kent.  I didn't realize that was a copy of  
Lutz's book.  I sent notice to [EMAIL PROTECTED]
It did seem like an awfully rich comparison of python persistence  
options.

If they follow up with me I will follow up with the list.

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


Re: [Tutor] Bundle help!

2007-06-25 Thread Reed O'Brien


On Jun 25, 2007, at 9:56 PM, Sara Johnson wrote:

I'm to use the bundle method to append some information to a list.   
I have no idea how to do that!  I have Python for Dummies and I  
think I need Python for Complete Idiots because I am not seeing how  
to do this!!  I have basic C+ knowledge and about 6 programs to  
write (in one month's time!) and I know NOTHING!!  HELP!!!


Sara

8:00? 8:25? 8:40? Find a flick in no time
with theYahoo! Search movie showtime shortcut.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Sara:

Guessing:
http://numpy.scipy.org/
http://www.danbbs.dk/~kibria/software.html#qpnumpy
close?


But if it is as simple as just adding to a list:
In [2]: L = [1,2,3,4,5,6]

In [3]: L.append(['a','b', 'c'])

In [4]: L.append(7)

In [5]: L
Out[5]: [1, 2, 3, 4, 5, 6, ['a', 'b', 'c'], 7]

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


Re: [Tutor] Regular Expression help

2007-06-27 Thread Reed O'Brien

On Jun 27, 2007, at 10:24 AM, Mike Hansen wrote:

>
>
>> -Original Message-
>> From: [EMAIL PROTECTED]
>> [mailto:[EMAIL PROTECTED] On Behalf Of Gardner, Dean
>> Sent: Wednesday, June 27, 2007 3:59 AM
>> To: tutor@python.org
>> Subject: [Tutor] Regular Expression help
>>
>> Hi
>>
>> I have a text file that I would like to split up so that I
>> can use it in Excel to filter a certain field. However as it
>> is a flat text file I need to do some processing on it so
>> that Excel can correctly import it.
>>
>> File Example:
>> tag descVR  VM
>> (0012,0042) Clinical Trial Subject Reading ID LO 1
>> (0012,0050) Clinical Trial Time Point ID LO 1
>> (0012,0051) Clinical Trial Time Point Description ST 1
>> (0012,0060) Clinical Trial Coordinating Center Name LO 1
>> (0018,0010) Contrast/Bolus Agent LO 1
>> (0018,0012) Contrast/Bolus Agent Sequence SQ 1
>> (0018,0014) Contrast/Bolus Administration Route Sequence SQ 1
>> (0018,0015) Body Part Examined CS 1
>>
>> What I essentially want is to use python to process this file
>> to give me
>>
>>
>> (0012,0042); Clinical Trial Subject Reading ID; LO; 1
>> (0012,0050); Clinical Trial Time Point ID; LO; 1
>> (0012,0051); Clinical Trial Time Point Description; ST; 1
>> (0012,0060); Clinical Trial Coordinating Center Name; LO; 1
>> (0018,0010); Contrast/Bolus Agent; LO; 1
>> (0018,0012); Contrast/Bolus Agent Sequence; SQ ;1
>> (0018,0014); Contrast/Bolus Administration Route Sequence; SQ; 1
>> (0018,0015); Body Part Examined; CS; 1
>>
>> so that I can import to excel using a delimiter.
>>
>> This file is extremely long and all I essentially want to do
>> is to break it into it 'fields'
>>
>> Now I suspect that regular expressions are the way to go but
>> I have only basic experience of using these and I have no
>> idea what I should be doing.
>>
>> Can anyone help.
>>
>> Thanks
>>
>
> H... You might be able to do this without the need for regular
> expressions. You can split the row on spaces which will give you a  
> list.
> Then you can reconstruct the row inserting your delimiter as needed  
> and
> joining the rest with spaces again.
>
> In [63]: row = "(0012,0042) Clinical Trial Subject Reading ID LO 1"
>
> In [64]: row_items = row.split(' ')
>
> In [65]: row_items
> Out[65]: ['(0012,0042)', 'Clinical', 'Trial', 'Subject', 'Reading',
> 'ID', 'LO',
> '1']
>
> In [66]: tag = row_items.pop(0)
>
> In [67]: tag
> Out[67]: '(0012,0042)'
>
> In [68]: vm = row_items.pop()
>
> In [69]: vm
> Out[69]: '1'
>
> In [70]: vr = row_items.pop()
>
> In [71]: vr
> Out[71]: 'LO'
>
> In [72]: desc = ' '.join(row_items)
>
> In [73]: new_row = "%s; %s; %s; %s" %(tag, desc, vr, vm, )
>
> In [74]: new_row
> Out[74]: '(0012,0042); Clinical Trial Subject Reading ID; LO; 1'
>
> Someone might think of a better way with them thar fancy lambdas and
> list comprehensions thingys, but I think this will work.
>
>
I sent this to Dean this morning:

Dean,

I would do something like this (if your pattern is always the same.)

  foo =['(0012,0042) Clinical Trial Subject Reading ID LO 1 ',
  '(0012,0050) Clinical Trial Time Point ID LO 1 ',
  '(0012,0051) Clinical Trial Time Point Description ST 1 ',
  '(0012,0060) Clinical Trial Coordinating Center Name LO 1 ',
  '(0018,0010) Contrast/Bolus Agent LO 1 ',
  '(0018,0012) Contrast/Bolus Agent Sequence SQ 1 ',
  '(0018,0014) Contrast/Bolus Administration Route Sequence SQ 1 ',
  '(0018,0015) Body Part Examined CS 1',]

import csv
writer = csv.writer(open('/Users/reed/tmp/foo.csv', 'w'), delimiter=';')

for lin in foo:
 lin = lin.split()
 row = (lin[0], ' '.join(lin[1:-2]), lin[-2], lin[-1])
 writer.writerow(row)


more foo.csv
(0012,0042);Clinical Trial Subject Reading ID;LO;1
(0012,0050);Clinical Trial Time Point ID;LO;1
(0012,0051);Clinical Trial Time Point Description;ST;1
(0012,0060);Clinical Trial Coordinating Center Name;LO;1
(0018,0010);Contrast/Bolus Agent;LO;1
(0018,0012);Contrast/Bolus Agent Sequence;SQ;1
(0018,0014);Contrast/Bolus Administration Route Sequence;SQ;1
(0018,0015);Body Part Examined;CS;1


HTH,
~reed


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


Re: [Tutor] Fastest way to iterate through a file

2007-07-01 Thread Reed O'Brien


On Jul 1, 2007, at 7:13 PM, elis aeris wrote:


 might just end my quest for
optimized python source code.
ugh,

what does it mean ?



elias,

We have two MAJOR rules regarding optimization.  These rules really  
go beyond python, but this is a good place to learn them.


The two rules of optimization:

The first is:
1) DON'T DO IT!

The second is only for advanced programmers.
2) Don't do it, yet!


Until you have working code, there is nothing to optimize. You can  
spend months optimizing and refactoring a for loop only to find out  
that you are hung up on a network operation.  Write the program  
first. Then see if it needs tweaking. other wise you are simply  
rewriting this:


for None in None:
pass

~ro



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


Re: [Tutor] Power Shells [WAS:] optimization: faster than for

2007-07-01 Thread Reed O'Brien

On Jul 1, 2007, at 6:38 PM, ALAN GAULD wrote:

> Suddenly it seems like I have an embarassment of advanced
> shells to choose from. At risk of starting a religious war, who
> favours which and why?
>
>

Alan,

I have been using ipython for the last few months.  I am barely  
touching teh surface of what it is capable of.

there are of course silly shortcuts like so:
In [16]: def foo(x):
 print x
:
:

In [18]: def bar(x, y, z):
 print x, y, z
:
:

In [20]: ;foo 1 2 3
---> foo("1 2 3")
1 2 3

In [21]: ,bar 1 2 3
---> bar("1", "2", "3")
1 2 3

note the ; and , that auto quote for you.

The main reason I like it is that is leaves me real shell access and  
auto complete for filepaths and such.

I use it with the zope debugger, too.

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


Re: [Tutor] python image libray - source to Mac OS X

2007-10-29 Thread Reed O'Brien

On Oct 29, 2007, at 7:54 PM, elis aeris wrote:




http://www.pythonware.com/products/pil/#pil116


has anyone been able to compile this on Mac os x?




http://two.pairlist.net/pipermail/reportlab-users/2007-October/ 
006262.html


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


Re: [Tutor] Telnet to Router/Switch

2007-12-24 Thread Reed O'Brien

On Dec 24, 2007, at 1:19 PM, Shahjehan Hakim wrote:


Hi everyone..

I have to make Telnet session with Router/switch of Cisco. Anybody  
has idea how it can be done? from what i researched, i got most of  
the telnet session like client/servers. But what I have to do here  
is just to create a Telnet session which writes the password when  
its prompted and then write the commands and fetch the result which  
is returned by the session.


I would start with the telnetlib module:

http://www.python.org/doc/current/lib/module-telnetlib.html

It has a quick example too:

http://www.python.org/doc/current/lib/telnet-example.html___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Careful Dictionary Building

2007-12-29 Thread Reed O'Brien

On Dec 28, 2007, at 11:29 AM, doug shawhan wrote:


*sigh* Ignore folks. I had forgotten about .has_key().


.has_key() is deprecated in 2.6 and goes away in 3.0 IIRC

You should use

record in D

or

D.get(record)




On Dec 28, 2007 11:22 AM, doug shawhan <[EMAIL PROTECTED]> wrote:
I'm building a dictionary from a list with ~ 1M records.

Each record in the list is itself a list.
Each record in the list has a line number, (index 0) which I wish  
to use as a dictionary key.


The problem: It is possible for two different records in the list  
to share this line number. If they do, I want to append the record  
to the value in the dictionary.


The obvious (lazy) method of searching for doubled lines requires  
building and parsing a key list for every record. There must be a  
better way!


dict = {}
for record in list
if record[0] in dict.keys ():
dict[ record[0] ].append( record )
else:
dict[ record[0] ] = [record]

Once you get ~ 80,000 records it starts slowing down pretty badly  
(I would too ...).


Here's hoping there is a really fast, pythonic way of doing this!

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


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


Re: [Tutor] Spaces and tabs messing up code

2008-01-08 Thread Reed O'Brien
On Jan 8, 2008, at 7:49 PM, Bill Campbell wrote:

> On Tue, Jan 08, 2008, [EMAIL PROTECTED] wrote:
>>
>>   my friend uses vim

Small editors for small minds;)

>>
>>   and i use xemacs
>>
>>   so our shared python code is a mix of tabs and spaces and it is  
>> hard
>>   for him to edit it in vim
>>
>>   any idea on how to make it clean
>>
>>   convert it all to 4 spaces?
>
> Do that, and in his ~/.vimrc file, add a line ``set expandtab''

Tell him to use emacs.

>
> (Friends don't let friends use emacs :-).
>
> Bill
> --
> INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206)  
> 236-1676
>
> Giving money and power to government is like giving whiskey and car  
> keys to
> teenage boys -- P.J. O'Rourke
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] run in "deamon" mode?

2008-01-10 Thread Reed O'Brien
On Jan 10, 2008, at 12:41 AM, Allen Fowler wrote:

> Hello,
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>
> That is, I want to run the program via "python myfile.py" and have  
> it drop me back to the command line.  The program should continue  
> running until I kill it via it's PID, the machine shuts down, or  
> the program itself decides to shutdown.   It should _not_  die when  
> I simply log-out, etc.
>
> Is there a standard library module to help with this?

Something I have thrown into scripts to daemonize them. NOTE: this is  
probably not the `best` way.  but it works...

import os
import sys

def daemonize():
"""Become a daemon, seperate from the terminal and redirect IO"""
if os.fork(): os._exit(0)
os.setuid(1) # set user to  daemon
os.setsid()
sys.stdin  = sys.__stdin__  = open('/dev/null','r')
sys.stdout = sys.__stdout__ = open('/dev/null','w')
sys.stdout = sys.__stderr__ = sys.stdout


Then when you start your program in say main()

call daemonize()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Noob requesting help...

2008-02-18 Thread Reed O'Brien
On Feb 16, 2008, at 9:58 PM, bob gailer wrote:

> Marc Tompkins wrote:
>> John, Luke, Marc... can we get a Matthew to join this thread?
> You thinking of Matthew Dixon Coles?
>
> But then wouldn't Paul want to get into the Act?

For Pete's sake...

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


Re: [Tutor] python + http authentication (with cherrypy)

2008-07-07 Thread Reed O'Brien

On Jul 7, 2008, at 9:10 PM, James wrote:


Hi All,

I'm writing a web application in CherryPy. What a beautiful thing it
is to write Python code and get a simple yet powerful web output. :)

The web application needs to have some decent level of security and
authentication implemented.

The big issue here is that the user password is stored in a database
and algorithmically calculated as follows:
md5( md5( $password ) + salt ) )


The salt is also stored in the database (which I have full access to).
I can easily use the md5 library to compare what a user gives me and
see if that's the correct password (based on the salt and the stored
password in the database). I'm unsure, however, how to go about
implementing security into my web application.


I had to do some stuff with salted hashed passwords a few months back  
and noted some stuff here:

http://reedobrien.blogspot.com/2008/01/seeded-salted-sha-passwords.html

md5 hash length would be 16 instead of sha's 20 IIRC... but otherwise  
I hope it helps you.





CherryPy obviously has a 'session' library in it. But in the periods
of time I've researched writing web applications in the past
(primarily when dealing with PHP), there was always great debate in
how to write a "good" secure web application. (i.e., it becomes tricky
when determining what precisely you should be passing around in terms
of session variables).

Thoughts? Am I going about this the wrong way? It would be much easier
to use either digest or basic http authentication mechanisms, but I
don't think that this is possible because of the fact that the
password is double-hashed in the database (or am I wrong?).

Any help appreciated. :o)

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


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


Re: [Tutor] stack class

2008-07-11 Thread Reed O'Brien

On Jul 11, 2008, at 7:54 PM, Christopher Spears wrote:

For another Core Python Programming question, I created a stack  
class.  I then put the class into a script to test it:


I understand that this is an exercise; but I think it might be  
interesting for you to also look at collections.deque

http://docs.python.org/lib/deque-objects.html




#!/usr/bin/python

class Stack(list):
   def isempty(self):
   length = len(self)
   if length == 0:
return True
else:
return False

   def peek(self):
   length = len(self)
if length == 0:
return 0
else:
last_index = length - 1
   return self[last_index]

   def stackpop(self):
   length = len(self)
if length == 0:
print "Empty list!"
else:
last_index = length - 1
stackpop_val = self[last_index]
self = self[:last_index]
return stackpop_val

   def push(self, value):
   return self.append(value)

if __name__ == '__main__':
   x = True
   stack = Stack()
   print "Pick an option to modify stack: "
   while x == True:
print "1) Peek at the last value"
print "2) Pop off the last value"
print "3) Push a value on the stack"
print "4) Quit Program"
choice_string = raw_input("Make a choice: ")

   try:
   choice = int(choice_string)
   except ValueError:
   sys.exit("Not an integer!  Goodbye!")

   if choice == 1:
if stack.isempty():
print "Stack is empty"
else:
   peek_val = stack.peek()
print peek_val
   elif choice == 2:
if "pop" in dir(list):
   pop_val = stack.pop()
print pop_val
else:
pop_val = stack.stackpop()
print pop_val
   elif choice == 3:
push_val = raw_input("Push this value on stack: ")
   stack.push(push_val)
print stack
   elif choice == 4:
   print "Goodbye!"
x = False
   else:
x = False
   sys.exit("Wrong response Goodbye!")

According to the question, I should test if the pop() function is  
available.  If that function is not available, the stack should use  
a pop() method of my own design.  I think I solved the problem, but  
I am not sure how to test it because Python 2.4 is installed on my  
computer.




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


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


Re: [Tutor] array of different datatypes

2008-09-23 Thread Reed O'Brien

On Sep 22, 2008, at 11:50 PM, Steve Willoughby wrote:


Dinesh B Vadhia wrote:
Thanks Steve.  How do you sort on the second element of each list  
to get:

a' = [[42, 'fish'],
   [1, 'hello']
   [2, 'world']
   ]


something like this would do the trick:

a_prime = sorted(a, key=(lambda i: i[1]))

sorted(a) returns a new list consisting of the elements in a
but in sorted order.  the key= parameter says how to derive the
sort key from any given element; in this case, the elements
being sorted are themselves lists, and element #1 in the sub-list
(a.k.a. "row") is the key.


try itemgetter:

In [1]: a = [[42, 'fish'],
   ...:  [2, 'world'],
   ...:  [1, 'hello']]

In [2]: from operator import itemgetter
In [3]: sorted(a, key=itemgetter(1))

Out[3]: [[42, 'fish'], [1, 'hello'], [2, 'world']]







From: Steve Willoughby Sent: Monday, September 22, 2008 8:16 PM
To: Dinesh B Vadhia Cc: tutor@python.org Subject: Re: [Tutor] array  
of different datatypes

Dinesh B Vadhia wrote:
I have looked (honestly!) and cannot see an array structure to  
allow different datatypes per column.  I need a 2 column array  
with column 1 = an integer and column 2 = chars, and after  
populating the array, sort on column 2 with column 1 sorted  
relatively.

If by "array" you mean a regular Python list, the data type of
every single element may be different.  So it's just how lists
always work.
a = [[1, 'hello'],
 [2, 'world'],
 [42, 'fish'],
]

Thanks!

Dinesh





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


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


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


Re: [Tutor] some string operations

2008-10-04 Thread Reed O'Brien

On Oct 4, 2008, at 4:03 AM, David wrote:


Dear list,

one of the exercises in Zelle's book is:

given

import string
s1 = "spam"
s2 = "ni!"

show a Python expression that could construct the following result  
by performing string operations on s1 and s2:


"Spam Ni! Spam Ni! Spam Ni!".

I have two solutions:

a)
(string.capitalize(s1) + " " + string.capitalize( s2) + "  " ) * 3

b)
"%s %s " % (string.capitalize(s1), string.capitalize(s2)) * 3

Both seem to work, but they seem overly complex. Where could I  
improve?


Also, Python returns:

'Spam Ni! Spam Ni! Spam Ni! '

Which is not exactly "Spam Ni! Spam Ni! Spam Ni!" (note the final  
free space in my outcome). I am at a loss as to how to perfect my  
answer with regard to this issue.


>>>  s1, s2 = 'spam', 'ni!'
>>> ' '.join([s.capitalize() for s in (s1, s2)] * 3)
'Spam Ni! Spam Ni! Spam Ni!'

HTH,
~ro

smime.p7s
Description: S/MIME cryptographic signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] commands versus subprocess, I'm confused

2008-12-26 Thread Reed O'Brien
On Dec 26, 2008, at 8:57, "Emad Nawfal (عماد نوفل)" mail.com> wrote:





2008/12/26 Kent Johnson 
On Fri, Dec 26, 2008 at 8:09 AM, Emad Nawfal (عماد نوفل)
 wrote:
> suppose I have an external program that prints "testing the  
subprocess

> module"
> I know I can run it through the commands module like this:
>
 a = commands.getoutput("python3.0 hello.py")
 a
> 'testing the subprocess module'


> I cannot figure out how to do the same thing in the subprocess  
module. Can

> somebody please explain how to get the same behaviour from, say,
> subprocess.call

Sometthing like this, I think:

proc = subprocess.Popen('python3.0 hello.py',
  shell=True,
  stdout=subprocess.PIPE,
  )
stdout_value = proc.communicate()[0]

(Courtesy of http://blog.doughellmann.com/2007/07/pymotw-subprocess.html 
)


Kent
Thank you Kent.
It works, but isn't the commands module much simpler?  I don't know  
why it's no more available in Python3.0


Subprocess was designed to replace all the os.popen classes since 2.4.

Commands is a wrapper for os.popen.

Aside from that commands AFAIK is unix only. Therefore it is less  
portable.


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