Re: list comprehension question

2009-05-01 Thread Shane Geiger
from goopy.functional import flatten  # 
http://sourceforge.net/projects/goog-goopy/

b = [(1,2), (3,4), (5,6)]
print flatten(b)



#from goopy.functional import flatten  # 
http://sourceforge.net/projects/goog-goopy/


def flatten(seq):
 """
 Returns a list of the contents of seq with sublists and tuples "exploded".
 The resulting list does not contain any sequences, and all inner sequences
 are exploded.  For example:

 >>> flatten([7,(6,[5,4],3),2,1])
 [7,6,5,4,3,2,1]
 """
 lst = []
 for el in seq:
   if type(el) == list or type(el) is tuple:
 lst.extend(flatten(el))
   else:
 lst.append(el)
 return lst



Chris Rebert wrote:

On Thu, Apr 30, 2009 at 5:56 PM, Ross  wrote:
  

If I have a list of tuples a = [(1,2), (3,4), (5,6)], and I want to
return a new list of each individual element in these tuples, I can do
it with a nested for loop but when I try to do it using the list
comprehension b = [j for j in i for i in a], my output is b =
[5,5,5,6,6,6] instead of the correct b = [1,2,3,4,5,6]. What am I
doing wrong?



Your comprehension is the identity comprehension (i.e. it effectively
just copies the list as-is).
What you're trying to do is difficult if not impossible to do as a
comprehension.

Here's another approach:
b = list(itertools.chain.from_iterable(a))

And without using a library function:
b = []
for pair in a:
for item in pair:
b.append(item)

Cheers,
Chris
  



--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create Standalone PYC File

2009-03-04 Thread Shane Geiger

py2exe (Windows) and py2app (Mac) are probably what you are looking for.



Rohan Hole wrote:
I have .py file which uses some third party modules like egg files, 
like simplejson and python-twitter ,
 
- start of file  -
 
import ConfigParser

import getopt
import os
import sys
import twitter
 
 
when i compile this py file using compile module , i get .pyc file . 
Now my question is , if i run .pyc file on another computer containing 
only python installed , will it run ? or do i need to install 3rd 
party lib again on that computer ? Anyone know how to make program lib 
independent , something called embedded into one file only ?
 
thank you in anticipation .
 
Rohan.



--
http://mail.python.org/mailman/listinfo/python-list
  



--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: OTish: convince the team to drop VBScript

2009-02-28 Thread Shane Geiger



The company does use Python on rare occasions. It all comes down to
the prejudices and habits of one of the programmers. His only argument
I can't counter -because I don't see the problem- is that "Python
modules cause problems for updates to customer's installations".



This is purely an argument from ignorance, a logical fallacy. 

Python is one of the more flexible, cleanly designed tools you could 
have at your disposal--it is certainly more powerful, flexible and 
elegant than VBScript.  If he has any doubts about how things can be 
designed with Python, show him that py2web (a web server/development 
environment) requires no installation, can run on a USB memory stick, 
can work with multiple operating systems, and can run on a cell phone 
(see youtube demo). 





Next time you talk to him, when he say that again, interrupt him, and
say: "[citation needed]" (don't forget the parentheses).

I don't really see any reason why "python modules would cause problem
for updating customer's installations", and I can't find anything on
Google that mentioned any problem. However, I do know that upgrading
python modules is easier than upgrading most other language's
libraries[citation needed].
--
http://mail.python.org/mailman/listinfo/python-list

  



--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: Email Program

2009-02-28 Thread Shane Geiger

J wrote:

Is it possible to make a GUI email program in Python that stores
emails, composes, ect? Also, could I create my own programming
language in Python? What are Pythons limits, or is this just a waste
of my time to learn it.
  


Python is "Turing complete," which means it is a general-purpose 
programming language.  Generally speaking, this means you can do 
anything with it that you can do with any other programming language.  
Being a higher-level language, Python is often chosen over other 
languages because it is faster to do many things in Python.


You could also create another programming language with Python.  In 
fact, another general-purpose programming language (C) was used to 
create Python.


Python makes many things easy.  For many tasks, Python saves you a lot 
of time.  It is a good general-purpose tool to know how to use well.  It 
is a good beginner's language, as it makes many of the annoying things 
about programs non-issues.




--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: Capture Keystrokes from a USB Wireless Keyboard.

2009-02-27 Thread Shane Geiger

Here's one option:

http://pykeylogger.sourceforge.net/wiki/index.php/PyKeylogger:FAQ




Support Desk wrote:

Does anybody know of a way to capture keystrokes form a wireless USB
keyboard using python?

--
http://mail.python.org/mailman/listinfo/python-list

  



--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: Flattening lists

2009-02-05 Thread Shane Geiger

These functions come from goopy:


def flatten1(seq):
 """
 Return a list with the contents of SEQ with sub-lists and tuples 
"exploded".

 This is only done one-level deep.
 """

 lst = []
 for x in seq:
   if type(x) is list or type(x) is tuple:
 for val in x:
   lst.append(val)
   else:
 lst.append(x)
 return lst

def flatten(seq):
 """
 Returns a list of the contents of seq with sublists and tuples "exploded".
 The resulting list does not contain any sequences, and all inner sequences
 are exploded.  For example:

 >>> flatten([7,(6,[5,4],3),2,1])
 [7,6,5,4,3,2,1]
 """
 lst = []
 for el in seq:
   if type(el) == list or type(el) is tuple:
 lst.extend(flatten(el))
   else:
 lst.append(el)
 return lst




Brian Allen Vanderburg II wrote:

mrk...@gmail.com wrote:

Hello everybody,

Any better solution than this?

def flatten(x):
res = []
for el in x:
if isinstance(el,list):
res.extend(flatten(el))
else:
res.append(el)
return res

a = [1, 2, 3, [4, 5, 6], [[7, 8], [9, 10]]]
print flatten(a)


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Regards,
mk

--
http://mail.python.org/mailman/listinfo/python-list


I think it may be just a 'little' more efficient to do this:

def flatten(x, res=None):
   if res is None:
  res = []

   for el in x:
  if isinstance(el, (tuple, list)):
 flatten(el, res)
  else:
 res.append(el)

   return res

Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list




--
Shane Geiger, IT Director
Council For Economic Education / www.councilforeconed.org
sgei...@councilforeconed.org  / 402-438-8958

Teaching Opportunity

--
http://mail.python.org/mailman/listinfo/python-list


Re: Text parsing via regex

2008-12-08 Thread Shane Geiger

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061


def wrap(text, width):
   """
   A word-wrap function that preserves existing line breaks
   and most spaces in the text. Expects that existing line
   breaks are posix newlines (\n).
   """
   return reduce(lambda line, word, width=width: '%s%s%s' %
 (line,
  ' \n'[(len(line)-line.rfind('\n')-1
+ len(word.split('\n',1)[0]
 ) >= width)],
  word),
 text.split(' ')
)

# 2 very long lines separated by a blank line
msg = """Arthur:  "The Lady of the Lake, her arm clad in the purest \
shimmering samite, held aloft Excalibur from the bosom of the water, \
signifying by Divine Providence that I, Arthur, was to carry \
Excalibur. That is why I am your king!"

Dennis:  "Listen. Strange women lying in ponds distributing swords is \
no basis for a system of government. Supreme executive power derives \
from a mandate from the masses, not from some farcical aquatic \
ceremony!\""""

# example: make it fit in 40 columns
print(wrap(msg,40))

# result is below
"""
Arthur:  "The Lady of the Lake, her arm
"""


Robocop wrote:

I'm having a little text parsing problem that i think would be really
quick to troubleshoot for someone more versed in python and Regexes.
I need to write a simple script that parses some arbitrarily long
string every 50 characters, and does not parse text in the middle of
words (but ultimately every parsed string should be 50 characters, so
adding in white spaces is necessary).  So i immediately came up with
something along the lines of:

string = "a bunch of nonsense that could be really long, or really
short depending on the situation"
r = re.compile(r".{50}")
m = r.match(string)

then i started to realize that i didn't know how to do exactly what i
wanted.  At this point i wanted to find a way to simply use something
like:

parsed_1, parsed_2,...parsed_n = m.groups()

However i'm having several problems.  I know that playskool regular
expression i wrote above will only parse every 50 characters, and will
blindly cut words in half if the parsed string doesn't end with a
whitespace.  I'm relatively new to regexes and i don't know how to
have it take that into account, or even what type of logic i would
need to fill in the extra whitespaces to make the string the proper
length when avoiding cutting words up.  So that's problem #1.  Problem
#2 is that because the string is of arbitrary length, i never know how
many parsed strings i'll have, and thus do not immediately know how
many variables need to be created to accompany them.  It's easy enough
with each pass of the function to find how many i will have by doing:
mag = len(string)
upper_lim = mag/50 + 1
But i'm not sure how to declare and set them to my parsed strings.
Now problem #1 isn't as pressing, i can technically get away with
cutting up the words, i'd just prefer not to.  The most pressing
problem right now is #2.  Any help, or suggestions would be great,
anything to get me thinking differently is helpful.
--
http://mail.python.org/mailman/listinfo/python-list

  



--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

--
http://mail.python.org/mailman/listinfo/python-list


Re: generating a liste of characters

2008-12-03 Thread Shane Geiger

import string
alphabet=list(string.letters[0:26])
print alphabet



Yves Dorfsman wrote:

Is there any built in way to generate a list of characters, something
along the line of range('a'-'z') ?

Right now I am using:

  chars  = [ chr(l)  for l in range(0x30, 0x3a) ] # 0 - 9
  chars += [ chr(l)  for l in range(0x41, 0x5b) ] # A - Z
  chars += [ chr(l)  for l in range(0x61, 0x7b) ] # a - z

Is there a better, more straight forward way of doing that ?



Thanks.



Yves.
http://www.sollers.ca/blog/2008/swappiness
http://www.sollers.ca/blog/2008/swappiness/.fr

--
http://mail.python.org/mailman/listinfo/python-list

  



--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

--
http://mail.python.org/mailman/listinfo/python-list


Re: hw to program on python

2008-04-15 Thread Shane Geiger
ashish,

While you are waiting for Diez to arrive, you should check out this Web 
site:  http://www.google.com.  It has some interesting content.  Perhaps 
you can find information there that will help you to ask a better question.

Here is another page you should look at:  
http://www.catb.org/~esr/faqs/smart-questions.html

All joking aside, this hasn't been an easily answered question.  The 
creator of Python, Guido, was asking a similar question not so long 
ago:  http://www.artima.com/weblogs/viewpost.jsp?thread=146149

The latest and greatest from Guido's company is Google App Engine, which 
you might want to learn about.

http://www.techcrunch.com/2008/04/07/google-jumps-head-first-into-web-services-with-google-app-engine/
http://code.google.com/appengine/
http://www.computerworld.com.au/index.php/id;1913502382;fp;4;fpid;611908207
http://googleblog.blogspot.com/2008/04/developers-start-your-engines.html
http://googleappengine.blogspot.com/2008/04/introducing-google-app-engine-our-new.html

Shane



Diez B. Roggisch wrote:
> ashish wrote:
>
>   
>> hi ,
>> python experts i want some help from u people just mail me how to
>> write scripts for web applications (like form coding for login page,
>> etc).
>>
>>
>> i m waiting for ur reply by
>> 
>
> While you are waiting, would a nice back-rub & and a good portion of powder
> sugar gently blown up your behind be in order? I'd plain love to drop by &
> give that to you, to make the dreaded waiting for the amassing expert
> advice a bit more comfortable!
>
> Diez
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a tuple to a list

2008-04-08 Thread Shane Geiger
from goopy.functional import *

tupla = ((1,2), (3,4), (5,6))

print flatten(tupla)




Gabriel Ibanez wrote:
> Hi all ..
>
> I'm trying to using the map function to convert a tuple to a list, without 
> success.
>
> I would like to have a lonely line that performs the same as loop of the 
> next script:
>
> ---
> # Conveting tuple -> list
>
> tupla = ((1,2), (3,4), (5,6))
>
> print tupla
>
> lista = []
> for a in tupla:
> for b in a:
> lista.append(b)
> print lista
> -------
>
> Any idea ?
>
> Thanks ...
>
> # Gabriel
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking processes running under Windows

2008-03-27 Thread Shane Geiger
One way: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339


Another way:  wmi

# List all running processes
# http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes


import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
  print process.ProcessId, process.Name


# List all running notepad processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process (name="notepad.exe"):
  print process.ProcessId, process.Name


# Create and then destroy a new notepad process

import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create
(CommandLine="notepad.exe")
for process in c.Win32_Process (ProcessId=process_id):
  print process.ProcessId, process.Name

result = process.Terminate ()






João Rodrigues wrote:
> Hello all! I'm trying to write a script that needs to check which
> processes are running under Windows (XP Pro, Home, whatever). The
> method I'm using is:
>
> >>> process_list = os.popen('TASKLIST').read()
>
> However, XP Home doesn't have the tasklist.exe tool so, this is kind
> of useless in that OS. Do you have any other methods I can use for this?
>
> Thanks!


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thousand Seperator

2008-03-14 Thread Shane Geiger
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/python/lib/decimal-recipes.html
 



Eddie Corns wrote:
> [EMAIL PROTECTED] writes:
>
>   
>> I'm trying to find some code that will turn:
>> 
>
>   
>> 100 -> 100
>> 1000 -> 1,000
>> 100 -> 1,000,000
>> -1000 -> -1,000
>> 
>
>   
>> I know that can be done using a regular expression. In Perl I would do
>> something like:
>> 
>
>   
>> sub thousand {
>>$number = reverse $_[0];
>>$number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g;
>>return scalar reverse $number;
>> }
>> 
>
>   
>> But I cannot find how to do this in Python.
>> 
>
> Look at the locale module.  If you're producing the numbers yourself then they
> get printed in that format otherwise you can convert them to numbers first.
>
> Eddie
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Monitoring SSHd and web servers?

2008-03-14 Thread Shane Geiger
I would recommend using a tried-and-true solution for making sure your
uptime of various services is maximized (if that's what your goal is).

Running a local "daemon-monitoring daemon" is one option--monit does a
good job.  Checking services over the network, as nagios does well, is
another solution.



Jonathan Gardner wrote:
> On Mar 13, 11:32 pm, Gilles Ganault <[EMAIL PROTECTED]> wrote:
>   
>> I'd like to monitor connections to a remote SSH and web server. Does
>> someone have some code handy that would try to connect every 5mn, and
>> print an error if the script can't connect?
>> 
>
> from time import sleep
> while True:
>   # Try to connect. May want to spawn a subprocess running a simple
> shell script
>   # Handle success / failure appropriately
>   sleep 5*60 # Sleep for 5 minutes
>
> What you monitor is up to you. At a basic level, you can see if the
> server is accepting connections. At a higher level, see if you can get
> a page or see if you can login as a specific person. At a higher
> level, you may want to check what is on the page or what happens when
> you log in. It's all up to you.
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Combinations

2008-03-12 Thread Shane Geiger
Michael Wieher wrote:
>
>
> 2008/3/12, Gerdus van Zyl <[EMAIL PROTECTED]
> <mailto:[EMAIL PROTECTED]>>:
>
> I have a list that looks like this:
> [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
>
> how can I get all the combinations thereof that looks like as follows:
> 3,9,5,4,2
> 3,1,5,4,2
> 3,9,5,4,5
> 3,1,5,4,5
> etc.
>
> Thank You,
> Gerdus
>
> --
>
>
> list =  [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
> newList = []
> for l in list:
>newList.extend(l)
>
> #newList = [3,9,1,5,4,2,5,8]
> list=[]
> for l in newList:
> if l not in list:
>  list.append(l)
>
> #now list is [3,9,1,5,4,2,8]
>
> list.sort()
>
> #now your list is in sorted order
>
> Then, you can just write a series of for loops to spin off your data
> however you like. 
>
>


def gen(lists):
out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']'
comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
return eval('[ ' + out + comp + ' ]')

a,b,c = [1,2,3],[4,5,6],[7,8,9]

print gen([a, b, c])





-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to factor using Python?

2008-03-11 Thread Shane Geiger
def fact(x):
if x == 1: return 1  # don't forget this
else: return x * fact(x - 1)

print fact(5)


> Factorial algorithm is a very simple and common algorithm, and it's
> one of the most basic of all recursive algorithm
> def fact(x):
> return x * fact(x - 1)
>
> That recursive function is very close to the basic definition of
> factorials, that is
> x! = x * (x - 1)!
>
> If however, you expected x to be a real (float) value, you'd better
> consider the gamma function as Mark Dickinson pointed out. Wikipedia
> is a good start to create your gamma function:
> http://en.wikipedia.org/wiki/Factorial
> http://en.wikipedia.org/wiki/Gamma_function
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: image matching algorithms

2008-03-10 Thread Shane Geiger
Daniel Fetchinson wrote:
>>> There are a number of free tools for image matching but it's not very
>>> easy to decipher the actual algorithm from the code that includes db
>>> management, GUI, etc, etc. I have my own image database and GUI so all
>>> I need is the actual algorithm preferably in pseudo code and not in
>>> the form of a research paper (from which I also found a lot but since
>>> I'm not that much interested in the actual science of image
>>> recognition this seems like an over kill).
>>>   
>> I'd recommend SIFT. There's quite a bit of information on SIFT. In most
>> cases, they don't cover the background science too much, but are still
>> heavy on the math. Pseudo code is hard to come by since it will take
>> many lines of pseudo code just to express one concise mathematical
>> equation. There are however many links to implementations in various
>> languages on the Wikipedia page.
>>
>> http://en.wikipedia.org/wiki/Scale-invariant_feature_transform
>>
>> I have had good experiences with SIFT for feature extraction from images
>> (I have used it for panorama stitching and robot mapping). It's
>> insensitive to scale and rotation. Note that it is a patented algorithm
>> and this may (or may not) pose a problem for you.
>> 
>
> Thanks for the info! SIFT really looks like a heavy weight solution,
> but do you think the whole  concept can be simplified if all I needed
> was: given a photo, find similar ones? I mean SIFT first detects
> objects on the image and find similarities, but I don't need the
> detection part at all, all I care about is similarity for the whole
> photo. I surely don't understand the big picture fully but just have
> the general feeling that SIFT and other expert tools are an overkill
> for me and a simplified version would be just as good with a much more
> easily comprehensible core algorithm.
>
> Or am I being too optimistic and there is no way out of going into the 
> details?
>   


Using the histogram of the picture may be good enough for your
application.  Here's something I put together for comparing images (for
purposes of detecting motion) taken by the built-in web cam in my
Macbook Pro.  This might be good enough if you play with the threshold.


"""
I'm writing a simple little app for doing motion detection with data
output from wacaw, a package for MacOSX.  You could easily modify this
script to get data output from some other source.

cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png
picture-${i} && sleep 3 ; done; open *.png
cd /Applications; open picture-*

"""

# cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png
picture-${i} && sleep 3 ; done; open *.png


# SOURCE:
http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/

import os
from time import sleep
import tempfile

import Image

# Sun Mar 18 16:40:51 CDT 2007
def diff_image(img1, img2, pix_threshold=50, img_threshold=4):
"""Compare 2 images to detect possible motion
You might want to choose the img_threshold amount based on the
conditions.
"""
img1 = Image.open(img1)
img2 = Image.open(img2)
if not img1 or not img2: return False
img1 = img1.getdata()
img2 = img2.getdata()
pixel_count = len(img1)
pixdiff = 0
for i in range(pixel_count):
#if abs(sum(img1[i]) - sum(img2[i])) > pix_threshold:
diffval = abs(sum(img1[i]) - sum(img2[i]))
#print "Pixel diffval:",diffval
if diffval > pix_threshold:
pixdiff += 1
diffperc = pixdiff / (pixel_count/100.0)
print "Photo diff percentage:",diffperc
if diffperc > img_threshold:
# motion detected
return True
else:
return False

photos = []  # consider automatically serializing this data

import commands


"""
def analyze_thresholds(list_of_photos):
last = list_of_photos[0]
for photo in list_of_photos[1:]:
diff_image(last, photo)
last = photo
"""



def detect():
number = 0
while True:
number += 1
sleep(3)
current = 'photo-'+str(number)
#tmp = tempfile.mktemp()
print commands.getoutput('/Applications/wacaw --png ' + current
)  # ' + tmp +'.png')

# Here's the actual name of the file wacaw created:
current = '/Applications/'+current+'.png'
photos.append( current )
if len(photos) < 2:  # pad the list for the first time
photos.append( current )

if diff_image(photos[-1],photos[-2], pix_threshold=50,
img_threshold=5):
print "motion detected"
else:
print "motion NOT detected"



detect()

#import glob
#analyze_thresholds(glob.glob('/Applications/photo-*')

 




-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-04 Thread Shane Geiger

>  if a == 0:
> do_task_0()
>  elif a == 1:
> do_task_1()
>  elif a == 2:
> do_task_2()
>  else:
> do_default_task()

The if-elif-else structure that calls functions (like that above) can be
avoided with the code below:


def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'
def do_default_task(): print 'do_default_task'

do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }

a = 1

# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()

# example of testing all functions in the dict as well as the default
function
for a in do_task.keys() + [8]:  # 8 is a non-existent key in the do_task
dict
print "a is ",a,"and it gives this output:",
if a in do_task.keys(): do_task[a]()
else: do_default_task()





Carl Banks wrote:
> On Mar 4, 10:55 am, "BJörn Lindqvist" <[EMAIL PROTECTED]> wrote:
>   
>> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
>> 
>>>  > for ...:
>>>  > ...
>>>  > exhausted:
>>>  > ...
>>>  > broken:
>>>  > ...
>>>   
>>>  > The meaning is explicit. While "else" seems to mean little there.
>>>  > So I may like something similar for Python 3.x (or the removal of the
>>>  > "else").
>>>   
>>>  I would not be opposed to this on its own merits, but there is a
>>>  rationale behind the name "else".  If you consider a for loop to be a
>>>  rolled-up if...elif...else statement (situations where this is
>>>  reasonable tend to be the same ones were else would be useful), then
>>>  the "else" clause would remain unchanged on the for loop.
>>>   
>>>  For instance, if you have a (trivial) if...elif...else like this:
>>>   
>>>  if a == 0:
>>> do_task_0()
>>>  elif a == 1:
>>> do_task_1()
>>>  elif a == 2:
>>> do_task_2()
>>>  else:
>>> do_default_task()
>>>   
>>>  You could roll it up into a for...else statement like this:
>>>   
>>>  for i in range(3):
>>> if a == i:
>>> do_task[a]()
>>>  else:
>>> do_default_task()
>>>   
>> You forgot the break statement. The else suite will always be executed
>> in this loop. Kind of proves bearophiles point, for-else is really
>> tricky.
>> 
>
> Ah ha, but that would have been a mistake with or without the else
> clause
>
>
> Carl Banks
>   

This approach works well for me:



def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'

def do_default_task(): print 'do_default_task'

do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }

a = 1 

# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()


# example of testing
for i in range(len(do_task.keys)):
 if a in do_task.keys(): do_task[a]()
 else: do_default_task()



-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib & gnupg

2008-02-20 Thread Shane Geiger
To the best of my knowledge, GNUPG acts upon the body of the message. 
If you think about it you should realize that the header of the message
cannot be encrypted, as it will be handled by mail servers that have no
knowledge of GNUPG or your encryption keys.  I am further emboldened to
make this assertion because the encryption takes place before the
message is sent--that is, before the headers are completely formed.



Brot wrote:
> Hello,
>
> at the moment my program sends mail with smtplib. Is there a chance to
> sign and/or encode/cipher this mails with GnuPG?
> If yes, does anyone have some sample code?
>
> Regards
>   Bernd
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to use .NET DLL from Python

2008-02-06 Thread Shane Geiger
The following links *may* put you on the right path:


Calling DLL functions from Python (
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847 ), a
fairly complete description with some helper class code. Another example
( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/181063 ) of
using the calldll module to do this.

calldll module: http://www.nightmare.com/software.html


http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847






Huayang Xia wrote:
> Hello All,
>
> I have several .NET DLL (I have no source code for them), is there
> anyway to use them from python instead of from C#.
>
> Thanks,
> Huayang
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

2008-01-30 Thread Shane Geiger
The answer is here: 
http://www.google.com/search?q=gene+expression+programming+python



Tim Chase wrote:
>> I do not understand why no one has answered the following question:
>>
>> Has anybody worked with Gene Expression Programming   
>> 
>
> Well, my father's name is Gene, and he's expressed software wants
> that I've implemented in Python...so yes, I guess I've done some
> Gene Expression Programming...
>
> ;-P
>
> -tkc
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there some Python function that searches "sys.path" for a module?

2008-01-14 Thread Shane Geiger
If I understand you correctly, you want this:

module.__file__




John Nagle wrote:
>Python's own loader searches "sys.path" for module names, but is there
> some function that makes that search functionality accessible to
> Python programs?  I need the absolute pathname of a module, with the
> search being done exactly the same way "import" does it.  The loader for
> "egg" files has this functionality, but I'd like to find out if there's
> a standard way to do this before looking into that source code.
>
>Also, it seems that the environment variable "PYTHONPATH" applies to
> "import", but not to the starting module named on the Python command
> line.  Is that correct?  Thanks.
>
>   John Nagle
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recieving emails in python

2008-01-13 Thread Shane Geiger
[EMAIL PROTECTED] wrote:
> I m trying to create something simple a mailing list similar to yahoo
> groups
> I m stumbling at the part where the python recieves messages via say
> [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>
>
> how to make python recieve emails and process it
> after that it is straight forward processing in python inserting in db etc

Can you use POP to access Yahoo groups?

If so, this script will get you started:

#!/usr/bin/python
"""
Redirect the output to a file to capture the contents of the mailbox.
"""
host = 'foo.com'
account = 'jennyjenny'
password = '8675309'

import getpass, poplib
M = poplib.POP3(host)
#M.user(getpass.getuser())
#M.pass_(getpass.getpass())
M.user(account)
M.pass_(password)
numMessages = len(M.list()[1])
for i in range(numMessages):
for j in M.retr(i+1)[1]:
print j



-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does **kw mean?

2008-01-11 Thread Shane Geiger
Does this help?

def foobar(first_name,last_name, *args, **kwargs):
print first_name
print last_name
print "Tuple:",args
print "Dict:",kwargs

x = "has"
y = "demonstrated"
foobar('Shane','Geiger', x, y, adjective='useful', thing='PYTHON trick
known as extended call syntax', adverb='wonderfully')




[EMAIL PROTECTED] wrote:
> I've been reading the following example, and couldn't figure out, what
> **kw mean. (It's an empty dictionary, but what's the semantics):
>
>
> def wrap(method):
> def wrapped(self, *args, **kw):
> print "begin"
> method(self, *args, **kw)
> print "end"
> return wrapped
>
>
> class Test(object):
>     def method(self, name):
> print "method(%r)" % name
>
> t = Test()
> t.method("pure")
> Test.method = wrap(Test.method)
> t.method("wrapped")
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting n items at a time from a generator

2008-01-10 Thread Shane Geiger

Paul Rubin wrote:
> Tim Roberts <[EMAIL PROTECTED]> writes:
>   
>> I have to say that I have found this to be a surprisingly common need as
>> well.  Would this be an appropriate construct to add to itertools?
>> 
>
> I'm in favor.
>   


I am ecstatic about the idea of getting n items at a time from a
generator!  This would eliminate the use of less elegant functions to do
this sort of thing which I would do even more frequently if it were
easier. 

Is it possible that this syntax for generator expressions could be adopted?

>>> sentence = 'this is a senTence WiTH'
>>> generator = (word.capitalize() for word in sentence.split())
>>> print generator.next(3,'PadValue')
('This','Is','A')
>>> print generator.next(3,'PadValue')
('Sentence','With','PadValue')
>>> generator.next(3,'PadValue')
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
>>>


While on the topic of generators:

Something else I have longed for is assignment within a while loop.  (I
realize this might be more controversial and might have been avoided on
purpose, but I wasn't around for that discussion.)


>>> sentence = 'this is a senTence WiTH'
>>> generator = (word.capitalize() for word in sentence.split())
>>> while a,b,c = generator.next(3,'PadValue'):
... print a,b,c
...
This Is A
Sentence With PadValue
>>>




-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: linecache and glob

2008-01-03 Thread Shane Geiger
import linecache
import glob

# reading from one file
print linecache.getline('notes/python.txt',4)
'http://www.python.org/doc/current/lib/\n'

# reading from many files
for filename in glob.glob('/etc/*'):
print linecache.getline(filename,4)




jo3c wrote:
> hi everyone happy new year!
> im a newbie to python
> i have a question
> by using linecache and glob
> how do i read a specific line from a file in a batch and then insert
> it into database?
>
> because it doesn't work! i can't use glob wildcard with linecache
>
>   
>>>> import linecache
>>>> linecache.getline(glob.glob('/etc/*', 4)
>>>>     
>
> doens't work
>
> is there any better methods??? thank you very much in advance
>
> jo3c
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


SVGDraw is where?

2008-01-01 Thread Shane Geiger
Does someone know where SVGDraw has gone?  It used to be here: 
http://www2.sfk.nl/svg/

Googling hasn't helped me locate it.  :-\

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to connect to a remote machine using python........

2007-12-30 Thread Shane Geiger
ontent-type", 'text/html')
self.end_headers()
f = StringIO()
f.write("A test %s\n" % self.path)
f.seek(0)
return f

def getMenu(self):
keys = self.cmds.keys()
keys.sort()
msg = []
for k in keys:
msg.append('%s => %s' %(k, k,
self.cmds[k]))
msg.append('')
return "\n".join(msg)

def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)

def main(HandlerClass = MyHTTPRequestHandler,
 ServerClass = BaseHTTPServer.HTTPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
main()



vinoj davis wrote:
> hi all,
>   i am new to python, can anyone tell me how can i connect to
> a remote machine using python and execute commands.
>
> Thanking you..
>
> Regards,
>
>  ---ViNOJ DAViS---
>
>
> 
> Chat on a cool, new interface. No download required. Click here.
> <http://in.rd.yahoo.com/tagline_webmessenger_10/*http://in.messenger.yahoo.com/webmessengerpromo.php>



-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Shane Geiger
Yes, I knew this.  Good call, it was just a bad copy and paste example
of lines that showed up close together in a file.  My apologies.

>> import tempfile
>> tmp = tempfile.mktemp()
>>
>> import os
>> os.remove(tmp)
>> 
>
> Not only does that not answer the Original Poster's question, but I don't 
> think it does what you seem to think it does.
>
>
>   
>>>> tmp = tempfile.mktemp()
>>>> tmp
>>>> 
> '/tmp/tmpZkS0Gj'
>   
>>>> type(tmp)
>>>> 
> 
>   
>>>> import os
>>>> os.remove(tmp)
>>>> 
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 2] No such file or directory: '/tmp/tmpZkS0Gj'
>
>
>
>
> You might like to read help(tempfile.mktemp).
>
> (By the way... the whole point of using tempfile is to avoid needing to 
> delete the file by hand afterwards.)
>
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Shane Geiger
import tempfile
tmp = tempfile.mktemp()

import os
os.remove(tmp)



[EMAIL PROTECTED] wrote:
> Wondering if someone would help me to better understand tempfile. I
> attempt to create a tempfile, write to it, read it, but it is not
> behaving as I expect. Any tips?
>
>   
>>>> x = tempfile.TemporaryFile()
>>>> print x
>>>> 
> ', mode 'w+b' at 0xab364968>
>   
>>>> print x.read()
>>>> 
>
>   
>>>> print len(x.read())
>>>> 
> 0
>   
>>>> x.write("1234")
>>>> print len(x.read())
>>>> 
> 0
>   
>>>> x.flush()
>>>> print len(x.read())
>>>> 
> 0
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic DNS with a python script

2007-12-27 Thread Shane Geiger
 the
names "sgeiger.mine.nu" and for "myothername.mine.nu":

[EMAIL PROTECTED]:/root$ sudo /usr/sbin/ipcheck.py --makedat -l -r
checkip.dyndns.org:8245 shanerg asdfasdf
sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu
ipcheck.py: There is already an ipcheck.dat file existing.
ipcheck.py: Remove this file first before running --makedat
[EMAIL PROTECTED]:/root$ sudo mv ipcheck.dat ipcheck.dat-old
[EMAIL PROTECTED]:/root$ sudo /usr/sbin/ipcheck.py --makedat -l -r
checkip.dyndns.org:8245 shanerg asdfasdf
sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu
ipcheck.py: ip1 looking up sgeiger.mine.nu
ipcheck.py: result: 'sgeiger.mine.nu'[]['139.55.233.228']
ipcheck.py: ip2 looking up sgeigerbot.mine.nu
ipcheck.py: result: 'sgeigerbot.mine.nu'[]['139.55.233.228']
ipcheck.py: ip2 looking up myothername.mine.nu
ipcheck.py: result: 'myothername.mine.nu'[]['139.55.233.228']
[EMAIL PROTECTED]:/root$


[EMAIL PROTECTED]:/nu/mine/myothername$ sudo crontab -l
15 10 * * * /usr/sbin/ipcheck.py -l -r checkip.dyndns.org:8245
shanerg asdfasdf sgeiger.mine.nu,sgeigerbot.mine.nu,myothername.mine.nu
--acctfile /root/ipcheck.dat
[EMAIL PROTECTED]:/nu/mine/myothername$







-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting n items at a time from a generator

2007-12-27 Thread Shane Geiger
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958

from itertools import *
def group(lst, n):
"""group([0,3,4,10,2,3], 2) => iterator

Group an iterable into an n-tuples iterable. Incomplete tuples
are padded with Nones e.g.

>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
iters = tee(lst, n)
iters = [iters[0]] + [chain(iter, repeat(None))
 for iter in iters[1:]]
return izip(
 *[islice(iter, i, None, n) for i, iter
  in enumerate(iters)])

import string
for grp in list(group(string.letters,25)):
   print grp

"""
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y')
('z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X')
('Y', 'Z', None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None, None, None,
None)

"""




Kugutsumen wrote:
> On Dec 27, 7:24 pm, Terry Jones <[EMAIL PROTECTED]> wrote:
>   
>>>>>>> "Kugutsumen" == Kugutsumen  <[EMAIL PROTECTED]> writes:
>>>>>>>   
>> Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>>
>> 
>>>> On Dec 27, 11:34 am, Kugutsumen <[EMAIL PROTECTED]> wrote:
>>>> 
>>>>> I am relatively new the python language and I am afraid to be missing
>>>>> some clever construct or built-in way equivalent to my 'chunk'
>>>>> generator below.
>>>>>   
>> Kugutsumen> Thanks, I am going to take a look at itertools.  I prefer the
>> Kugutsumen> list version since I need to buffer that chunk in memory at
>> Kugutsumen> this point.
>>
>> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>>
>> def chop(iterable, length=2):
>> return izip(*(iter(iterable),) * length)
>>
>> Terry
>> 
>
>   
>> [snip code]
>>
>> Try this instead:
>>
>> import itertools
>>
>> def chunk(iterator, size):
>> # I prefer the argument order to be the reverse of yours.
>> while True:
>> chunk = list(itertools.islice(iterator, size))
>> if chunk: yield chunk
>> else: break
>>
>> 
>
> Steven, I really like your version since I've managed to understand it
> in one pass.
> Paul's version works but is too obscure to read for me :)
>
> Thanks a lot again.
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem untaring python2.5

2007-12-20 Thread Shane Geiger
You might want to try an all-python implementation for sanity testing. 

I haven't tested this snippet much.  I am not sure it handles nested
files all that well. 



import tarfile
tar = tarfile.open("TarTest.tar.gz2", "r:gz") #  other options:
"r:bz2", and ??
file_list = tar.getnames()

import os
os.mkdir('new_dir')
# write the files out to new files
for fname in tar.getnames():
# extract/decompress the data of each file
data = tar.extractfile(fname).read()
# optionally change the filename
new_file = "new_dir/" + fname
print "File %s written!" % new_file
# write the decompressed data to a file
fout = open(new_file, "w")
fout.write(data)
fout.close()

# done, close the tar file ...
tar.close()



> On Dec 19, 12:16 pm, [EMAIL PROTECTED] wrote:
>   
>> Hello,
>>
>> It is not possible to give sharp hints without more relevant
>> information like:
>> - What is your platform?
>> - Which version of python?
>> - What is the version of: $tar--version (GNUtar, other proprietarytar, 
>> according to my personal experience, AIXtarmay fail)
>> - Is your disk full or do you have the correct permissions with your
>> current user?
>>
>> ++
>>
>> Sam
>> 
>
> Hi Sam ,
> I am using windows server 2003, python2.5.1 and version 1.16 of tar
>
> and as per disk full issues i dont think that my systems hard disk is
> full
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate pdf file from an html page??

2007-12-16 Thread Shane Geiger
Just some thoughts to get you started:

You may not get any responses because you weren't specific enough about
what you want to do.  Since you are asking about doing this via Python,
it seems you want to automate something which can be done from a menu
option in various Web browsers (use the print feature and print to
PDF).  You could, of course, download the files (as with the
command-line Web client, wget) and then convert html to PDF using
various tools.  Of course, this gives you a different result--of
course--because you would be using a different HTML rendering engine. 
So you have to ask yourself:  Is your goal to have a page that looks
exactly like it looks in Firefox? or in IE? or Safari?  Or are you only
concerned that you have the words of the document?


> Hi everyone, I am trying to generate a PDF printable format file from
> an html page. Is there a way to do this using   python. If yes then
> which library and functions are required and if no then reasons why it
> cant be done.
>
> Thank you All
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding overlapping times...

2007-12-13 Thread Shane Geiger
You should give a more real data set (maybe 20 various pairs so that all
scenarios can be seen) and the output you want.



Breal wrote:
> I have a list that looks like the following
> [(10, 100010), (15, 17), (19, 100015)]
>
> I would like to be able to determine which of these overlap each
> other.  So, in this case, tuple 1 overlaps with tuples 2 and 3.  Tuple
> 2 overlaps with 1.  Tuple 3 overlaps with tuple 1.
>
> In my scenario I would have hundreds, if not thousands of these
> ranges.  Any nice pythonic way to do this?
>
> Thanks.
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is anyone happy with csv module?

2007-12-12 Thread Shane Geiger
Neil Cerutti wrote:
> On 2007-12-12, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>   
>> John Machin <[EMAIL PROTECTED]> wrote:
>> 
>>> For that purpose, CSV files are the utter pox and then some.
>>> Consider using xlrd and xlwt (nee pyexcelerator) to read
>>> (resp. write) XLS files directly.
>>>   
>> FWIW, CSV is a much more generic format for spreadsheets than
>> XLS. For example, I deal almost exclusively in CSV files for
>> simialr situations as the OP because I also work with software
>> that can't (or in some cases "can't easily") deal with XLS
>> files.  CSV files can be read in by basically anything.
>> 
>
> When I have a choice, I use simple tab-delimited text files.  The
> usually irrelevent limitation is the inability to embed tabs or
> newlines in fields. The relevant advantage is the simplicity.
>   

That is very unnecessary.  You can have your tabs and not eat them, too:



#!/usr/bin/python
"""
EXAMPLE USAGE OF PYTHON'S CSV.DICTREADER FOR PEOPLE NEW TO PYTHON AND/OR
CSV.DICTREADER

Python - Batteries Included(tm)

This file will demonstrate that when you use the python CSV module, you
don't have to remove the newline characters, as between "acorp_ Ac" and
"orp Foundation" and other parts of the data below.

It also demonstrates python's csv.DictReader, which allows you to read a
CSV record into a dictionary.

This will also demonstrate the use of lists ([]s) and dicts ({}s).

If this doesn't whet your appetite for getting ahold of a powertool
instead of sed for managing CSV data, I don't know what will.

"""

  FIRST: CREATE A TEMPORARY CSV FILE FOR DEMONSTRATION PURPOSES
mycsvdata = """
"Category","0","acorp_ Ac
orp Foundation","","","Acorp Co","(480) 905-1906","877-462-5267 toll
free","800-367-2228","800-367-2228","[EMAIL PROTECTED]
g","7895 East Drive","Scottsdale","AZ","85260-6916","","","","","","Pres
Fred & Linda ","0","0","1","3","4","1"

"Category","0","acorp_ Bob and Margaret Schwartz","","","","317-321-6030
her","317-352-0844","","","","321 North Butler Ave.","In
dianapolis","IN","46219","","","","","","Refrigeration
man","0","1","2","3","4","0"

"Category","0","acorp_ Elschlager,
Bob","","","","","702-248-4556","","","[EMAIL PROTECTED]","7950 W.
Flamingo Rd. #2032","Las Vega
s","NV","89117","","","","","","guy I met","0","1","2","3","4","1"

"""

##  NOTE:  IF YOU HAVE A RECORD SEPARATOR WITHIN QUOTES, IT WILL NOT BE
TREATED LIKE A RECORD SEPARATOR!
##   Beef|"P|otatos"|Dinner Roll|Ice Cream


import os, sys
def writefile(filename, filedata, perms=750):
f = open(filename, "w")
f.write(filedata)
os.system("chmod "+str(perms)+" "+filename)
f.close()

file2write = 'mycsvdata.txt'
writefile(file2write,mycsvdata)

# Check that the file exists
if not os.path.exists(file2write):
print "ERROR: unable to write file:", file2write," Exiting now!"
sys.exit()

#   ...so everything down to this point merely creates the
# temporary CSV file for the code to test (below).



  SECOND:  READ IN THE CSV FILE TO CREATE A LIST OF PYTHON
DICTIONARIES, WHERE EACH
#  DICTIONARY CONTAINS THE DATA FROM ONE ROW.  THE KEYS OF THE
DICTIONARY WILL BE THE FIELD NAMES
#  AND THE VALUES OF THE DICTIONARY WILL BE THE VALUES CONTAINED WITHIN
THE CSV FILE'S ROW.

import csv

### NOTE: Modify this list to match the fields of the CSV file.
header_flds =
['cat','num','name','blank1','blank2','company','phone1','phone2', \
      
'phone3','phone4','email','addr1','city','state','zip','blank3', \
  
'blank4','blank5','blank6','blank7','title','misc1','misc2','misc3', \
   'mics4','misc5','misc6']

file2open = 'mycsvdata.txt'

reader = csv.DictReader(open(file2open), [], delimiter=",")
data = []
while True:
try:
# Read next "header" line (if there isn't one then exit the loop)
reader.fieldnames = header_flds
rdr = reader.next()
data.append(rdr)
except StopIteration: break


def splitjoin(x):
""" This removes any nasty \n that might exist in a field
(of course, if you want that in the field, don't use this)
"""
return ''.join((x).split('\n'))


  THIRD: ITERATE OVER THE LIST OF DICTS (IN WHICH EACH DICT IS A
ROW/RECORD FROM THE CSV FILE)

# example of accessing all the dictionaries once they are in the list
'data':
import string
for rec in data:   # for each CVS record
itmz = rec.items()  # get the items from the dictionary
print "- = " * 20
for key,val in itmz:
print key.upper()+":  \t\t",splitjoin(val)
# Note: splitjoin() allows a record to contain fields
with newline characters






-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loading an exe icon into a pixmap/bitmap

2007-12-11 Thread Shane Geiger
Are you looking for these kinds of tools?


In Debian:
icoutils - Extract MS Windows icons and cursors

I don't recall where I saw this:
FileJuicer - Extract images from Powerpoint, PDF, HTML, and CAB files


[EMAIL PROTECTED] wrote:
> I've been searching for a way to load an icon from an executable into
> something that I can eventually display either through pygame or
> pygtk. I've tried the stuff found at
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/d7f61f270cce368/3ff38c1ced504e43?lnk=gst&q=win32+icon#3ff38c1ced504e43
> but the tests just output all black (not surprising, as that guy
> couldn't get it to work either). I've mucked around with taht code and
> the ExtractIcon stuff from pywin32, but still am stuck. I've seen some
> reference to a wxpython ways to do it, but I'm trying to not have to
> convert over to that. Any help is appreciated. Thanks
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding dir of main .py file

2007-12-11 Thread Shane Geiger
Some usage of __file__ will always get what you want in various situations:

print __file__

print modulename.__file__

print os.getcwd() + "/" + __file__   





Rick Dooling wrote:
> On Dec 11, 10:08 am, "ron.longo" <[EMAIL PROTECTED]> wrote:
>   
>> Is there any way that I can find the path of the main .py file of my
>> application?
>>
>> For example, I have an application with some resources which are in a
>> subdirectory:
>>
>>  myPythonApp.py
>>  /resources
>>  image1
>>  image2
>>  etc.
>> 
>
> I just put the reference in my module. Don't hard code an absolute
> path, use the environment tools.
>
> app_path = os.getenv('HOME') + "/your_sub_dir"
>
> resources_path = os.getenv('HOME') + "/your_sub_dir/resources"
>
> If there's another way, someone else will jump in.
>
> rd
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculate an age

2007-12-08 Thread Shane Geiger
What is so obvious about dealing with months that vary in length and the
leap-year issue?  Nothing.  If you were born on a day that does not
exist every year (Feb 29th), how old are you on Feb 28th? or Mar 1 of
non-leap years?  If you were born on Feb 29th, then you would be one
month old on March 29th, but would you be one year, one month and one
day old on March 29th of the next year? or would you merely be one year
and one month old?  I believe this is exactly why datetime merely states
deltas in days, not months or years. 


Marc 'BlackJack' Rintsch wrote:
> On Fri, 07 Dec 2007 23:37:23 -0800, Pierre Quentel wrote:
>
>   
>> On Dec 7, 7:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>>
>> 
>>> How many days in a year? 365.25 (J2000 epoch), 365.2422 [as I
>>> recall](B1900 epoch), 365.0 (non-leap year), 366 (leap year)? Gregorian
>>> or Julian calendar -- and depending upon one's country, the Gregorian
>>> reform may take place at different years.
>>>
>>> Simple months of (year/12) days, or calendrical mishmash (30 days
>>> hath September, April, June, and November...) again with leap year
>>> exceptions?
>>>
>>>   
>> I don't see where the ambiguity is. Isn't it obvious what we mean by
>> "I am X years, Y months and Z days" ?
>> 
>
> That's obvious but given either the present date or the birth date along
> with that information it's not so clear what the other date may be. 
> Unless you give the info about the used calender systems and the points in
> time (according to which calender system!?) when to use which system.
>
> If you are just asking those questions for people living now (and are
> not called Connor McLeod ;-) and the gregorian calender it's easy but
> providing functions in the standard library for arbitrary date calculation
> involving years is not so easy.
>
> Ciao,
>   Marc 'BlackJack' Rintsch
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [NEWB] Dictionary instantiation?

2007-12-07 Thread Shane Geiger
)
# Note: splitjoin() allows a record to contain fields
with newline characters




Matt_D wrote:
> Hello there, this is my first post to the list. Only been working with
> Python for a few days. Basically a complete newbie to programming.
>
> I'm working with csv module as an exercise to parse out a spreadsheet
> I use for work.(I am an editor for a military journalism unit) Not
> trying to do anything useful, just trying to manipulate the data.
> Anyway, here's the code I've got so far:
>
> import csv
> import string
> import os
>
> #Open the appropriate .csv file
> csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))
>
> #Create blank dictionary to hold {[author]:[no. of stories]} data
> story_per_author = {}
>
> def author_to_dict(): #Function to add each author to the dictionary
> once to get initial entry for that author
> for row in csv_file:
> author_count = row[-1]
> story_per_author[author_count] = 1
>
> #Fetch author names
> def rem_blank_authors(): #Function to remove entries with '' in the
> AUTHOR field of the .csv
> csv_list = list(csv_file) #Convert the open file to list format
> for e-z mode editing
> for row in csv_list:
>     author_name = row[-1]
> if author_name == '': #Find entries where no author is listed
> csv_list.remove(row) #Remove those entries from the list
>
> def assign_author_to_title(): #Assign an author to every title
> author_of_title = {}
> for row in csv_file:
> title = row[3]
> author = row[-1]
> author_of_title[title] = author
>
>
> assign_author_to_title()
> print author_of_title
>
> --
>
> Ok, the last two lines are kind of my "test the last function" test.
> Now when I run these two lines I get the error:
>
> Traceback (most recent call last):
>   File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
> \scriptutils.py", line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "D:\Python25\csv_read.py", line 33, in 
> print author_of_title
> NameError: name 'author_of_title' is not defined
>
> I am guessing that the author_of_title dict does not exist outside of
> the function in which it is created? The concept of instantiation is
> sort of foreign to me so I'm having some trouble predicting when it
> happens.
>
> If I call the assign_author_to_title function later, am I going to be
> able to work with the author_of_title dictionary? Or is it best if I
> create author_of_title outside of my function definitions?
>
> Clearly I'm just stepping through my thought process right now,
> creating functions as I see a need for them. I'm sure the code is
> sloppy and terrible but please be gentle!
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: which configparse?

2007-12-06 Thread Shane Geiger
Best, is naturally, a somewhat subjective evaluation.  That being said,
configparser is well regarded.  I have also seen these two options that
you might want to check out:

http://wiki.woodpecker.org.cn/moin/Dict4Ini
http://www.voidspace.org.uk/python/configobj.html


> I have all my options setup with optparse.  Now, I'd like to be able to
> parse an ini file to set defaults (that could be overridden by command line
> switches).
>
> I'd like to make minimal change to my working optparse setup (there are lots
> of options - I don't want to duplicate all the cmdline parsing with ini
> file parsing code)
>
> I've looked at configparse, cfgparse, iniparse.
>
> configparse looks like what I want, but it seems last commit was >2years
> ago.
>
> What is the best choice?
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Standalone USB Web Server and Python Interpeter

2007-12-05 Thread Shane Geiger

mcl wrote:
> I would like to have a USB pen drive, which can execute python scripts
> including CGI versions, which I can take to any Windows PC and run
> without having to install anything on the PC.
>
> My days of hacking are past so I am looking for something very simple.
>
> I would envisage a batch file which would ask if the USB web server
> needed to be started or just python scripts and it would return the IP
> address of the server or even some local host name such as 'bobserver'
> which I could give it.
>
> I need v2.3 python.
>
> Is this possible
>
> Thanks
>
> Richard
>   


To the best of my knowledge you should be squared away if you have
Movable Python and the script below.  Let me know whether it works for
you.  (You might have to adjust the path somewhat.)


Movable Python:  http://www.voidspace.org.uk/python/movpy/



#!/usr/bin/python

"""
The CGIHTTPServer module
This is a simple HTTP server that can call external scripts through the
common gateway interface
(CGI).
Example: Using the CGIHTTPServer module
# File:cgihttpserver-example-1.py

If you are reading this, you have all the source code necessary to run
your own Web server.
Run this with Python.

Note:  This script allows symlinks to places outside the document root.

"""
try:
from mywebserver_config import *
except:
print "No mywebserver_config module found.  Using defaults."
pass

import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/cgi"]


def writefile(f, data, perms=750): open(f, 'w').write(data) and
os.chmod(f, perms)
def readfile(f): return open(f, 'r').read()

html_template = """


  temp



Temporary Server
This is a temporary server.  Do not expect to have access to this
indefinitely.  This is likely running on my laptop.


"""


index2_html = """


  



CGI scripts
cgi/test.py


"""

example_cgi = """#!/usr/bin/python

# Required header that tells the browser how to render the text.
print "Content-Type: text/html\\n\\n"

# Print a simple message to the display window.
print "Hello, World!\\n"

print "What follows are some files in the CGI directory:"
import commands
output = commands.getoutput('ls -1 cgi/').splitlines()
for item in output:
print ""
print item,
print ""
print ""


"""

def readip():
"""returns your external IP address by querying dyndns.org
"""
import re, urllib
f = urllib.urlopen('http://checkip.dyndns.org')
s = f.read()
m = re.search('([\d]*\.[\d]*\.[\d]*\.[\d]*)', s)
return m.group(0)

print "http://"+readip()+":8000/"

import urllib
import os


originaldir = os.getcwd()

# For safety, changing the document root
import tempfile, os
DOCUMENT_ROOT = tempfile.mkdtemp()
print "DOCUMENT_ROOT: " + DOCUMENT_ROOT
os.chdir(DOCUMENT_ROOT)
writefile(DOCUMENT_ROOT+"/README.html",html_template)

#print readfile(originaldir+'/'+__file__)
writefile(DOCUMENT_ROOT+"/"+os.path.basename(os.getcwd()+'/'+__file__),readfile(originaldir
+'/'+__file__))  # write a copy of this file


# create a cgi directory
os.mkdir(DOCUMENT_ROOT+'/cgi')
writefile(DOCUMENT_ROOT+"/cgi/test.py",example_cgi)
os.chmod(DOCUMENT_ROOT+"/cgi/test.py",755)
### not sure why the previous line doesn't work, but this next
(os-dependent) line does work (on some OSes):
os.system('chmod 755 ' + DOCUMENT_ROOT+"/cgi/test.py")



### INDEX2.HTML
writefile(DOCUMENT_ROOT+"/index2.html",index2_html)
os.system('chmod 755 ' + DOCUMENT_ROOT+"/index2.html")



try:
os.remove('/tmp/web')  # this path is OS-dependent
os.symlink(DOCUMENT_ROOT, '/tmp/web')
print "Created symlink /tmp/web"
except:
pass



import os
os.symlink( "/Users/shanegeiger/Desktop", DOCUMENT_ROOT+'/Desktop' )
os.symlink( "cgi/test.py", DOCUMENT_ROOT+'/test.py' )


PORT = 8000
#httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
#httpd = BaseHTTPServer.HTTPServer(("10.37.129.2", PORT), Handler)
httpd = BaseHTTPServer.HTTPServer(("0.0.0.0", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tool for translating Matlab to Python?

2007-12-04 Thread Shane Geiger
I would like such a tool, too.  Could someone with an interest in MatLab
help me figure out how to express this in Python?  :-) 
http://caprolibra.com/B10g/images/OptI_column_effect1/index.html



Rolf, you may not have seen this recently on this list:

http://www.geocities.com/ptmcg/python/using_matlab_from_python.html
Calling Matlab from Python


Rolf Wester wrote:
> Hi,
>
> is there a tool to automatically translate Matlab source to Python/numpy 
> code?
>
> Regards
>
> Rolf
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Die, thread! Die! (Was Re: "Python" is not a good name)

2007-12-04 Thread Shane Geiger
Die, thread! Die!



grflanagan wrote:
> On Dec 4, 11:53 am, [EMAIL PROTECTED] wrote:
>   
>> On Dec 4, 11:36 am, MarkE <[EMAIL PROTECTED]> wrote:
>>
>> 
>>> Ithon
>>>   
>> Pie - Fun
>> 
>
> Pie-a-thon?
>
> http://montypython.tribe.net/thread/fd519910-25e3-4102-b898-8815d6ece32a
>
> http://www.flickr.com/photos/kirstywombat/1862165664/
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


audiodev problem

2007-12-02 Thread Shane Geiger
"""
I just used the following Google search to look for some random .aiff
files which I could use to test the code I once found for the audiodev
module.  Unfortunately, the writeframes() call gives me the traceback
below.  Does anyone know what the problem is?  (I would, quite frankly
rather know how to play mp3 or ogg files, but I was wondering whether
there's a problem here that needs to be fixed.)


http://www.google.com/search?q=intitle%3A%22index.of%22+%22parent+directory%22+%22size%22+%22last+modified%22+%22description%22+%5Bsnd%5D+%28aiff%29+-inurl%3A%28jsp%7Cphp%7Chtml%7Caspx%7Chtm%7Ccf%7Cshtml%7Clyrics-realm%7Cmp3-collection%29+-site%3A.info++&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a


player.writeframes(data)  #  this line is causing this problem with
every .aiff file I try:


Traceback (most recent call last):
  File "/tmp/foo.py", line 39, in 
player.writeframes(data)  #  this line is causing this problem with
every .aiff file I try:
  File
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/Audio_mac.py",
line 67, in writeframes
nframes)
  File
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/struct.py",
line 63, in pack
return o.pack(*args)
struct.error: byte format requires -128 <= number <= 127


-

THE AUDIODEV MODULE

[contents]

(Unix only) This module provides sound playing support for Sun and SGI
computers.
Example: Using the audiodev module

# File: audiodev-example-1.py
"""
import audiodev
import aifc

# THIS IS THE ERROR I GET:  struct.error: byte format requires -128 <=
number <= 127

#sound = aifc.open("/Users/shanegeiger/bring.aiff", "r")
#sound = aifc.open("/Users/shanegeiger/gates01.aif", "r")
sound = aifc.open("/Users/shanegeiger/c2.aiff", "r")

player = audiodev.AudioDev()
player.setoutrate(sound.getframerate())
player.setsampwidth(sound.getsampwidth())
player.setnchannels(sound.getnchannels())

bytes_per_frame = sound.getsampwidth() * sound.getnchannels()
bytes_per_second = sound.getframerate() * bytes_per_frame

#print "bytes_per_frame:",bytes_per_frame
#print "bytes_per_second:",bytes_per_second

i = 0
while 1:
print str(i) + " COMPLETED"  # debug
data = sound.readframes(bytes_per_second)
if not data:
    break
#print data  # debug
player.writeframes(data)  #  this line is causing this problem with
every .aiff file I try:

i += 1

#import sys; sys.exit()
player.wait()



-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outbound HTML Authentication

2007-11-29 Thread Shane Geiger
twill is a simple language for browsing the Web.  It's designed for
automated testing of Web sites, but it can be used to interact with
Web sites in a variety of ways.  In particular, twill supports form
submission, cookies, redirects, and HTTP authentication.



Mudcat wrote:
> Hi,
>
> I was trying to do a simple web scraping tool, but the network they
> use at work does some type of internal authentication before it lets
> the request out of the network. As a result I'm getting the '401 -
> Authentication Error' from the application.
>
> I know when I use a web browser or other application that it uses the
> information from my Windows AD to validate my user before it accesses
> a website. I'm constantly getting asked to enter in this info before I
> use Firefox, and I assume that IE picks it up automatically.
>
> However I'm not sure how to tell the request that I'm building in my
> python script to either use the info in my AD account or enter in my
> user/pass automatically.
>
> Anyone know how to do this?
>
> Thanks
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lib for audio?

2007-11-29 Thread Shane Geiger
This should do the trick:
http://www.libsdl.org/


Dave wrote:
> I need to read microphone input and determine frequency. Is there a lib
> for that?
>
> Thanks,
> Dave
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rss Feed Creator

2007-11-26 Thread Shane Geiger
I think this is what you need to make the output readable:

tidy -asxml output.xml





James Matthews wrote:
> Thank You Shane,
>
> However that is using PyRss2Gen which doesn't put newlines in the XML.
> So it's a little out of the picture!
> On Nov 27, 2007 1:57 AM, Shane Geiger < [EMAIL PROTECTED]
> <mailto:[EMAIL PROTECTED]>> wrote:
>
> http://www.bigbold.com/snippets/tag/beautifulsoup
>
>
>
> James Matthews wrote:
> > Hi,
> >
> > I am looking for a library that will create Rss/Atom feeds in
> python.
> > It needs to format the XML in a readable format! Does anyone
> have any
> > suggestions?
> >
> > Thanks James
> >
> >
> > --
> > http://search.goldwatches.com/?Search=Movado+Watches
> > http://www.goldwatches.com/coupons
> > http://www.jewelerslounge.com
>
>
> --
> Shane Geiger
> IT Director
> National Council on Economic Education
> [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>  |  402-438-8958  |  
> http://www.ncee.net
>
> Leading the Campaign for Economic and Financial Literacy
>
>
>
>
> -- 
> http://search.goldwatches.com/?Search=Movado+Watches
> http://www.goldwatches.com/coupons
> http://www.jewelerslounge.com 


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rss Feed Creator

2007-11-26 Thread Shane Geiger
http://www.bigbold.com/snippets/tag/beautifulsoup



James Matthews wrote:
> Hi,
>
> I am looking for a library that will create Rss/Atom feeds in python.
> It needs to format the XML in a readable format! Does anyone have any
> suggestions?
>
> Thanks James
>
>
> -- 
> http://search.goldwatches.com/?Search=Movado+Watches
> http://www.goldwatches.com/coupons
> http://www.jewelerslounge.com 


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add speller to Python application

2007-11-26 Thread Shane Geiger
http://pyenchant.sourceforge.net/


helzer wrote:
> I need to add spell checking to my Python application (for Windows).
> Any ideas on where to start?
>
> Thanks,
> Helzer
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Installer or Executable in Python

2007-11-14 Thread Shane Geiger
A few candidate solutions:

http://nsis.sourceforge.net/Main_Page
http://www.jrsoftware.org/isinfo.php



DanielJohnson wrote:
> I have a small project which has around 10 .py files and I run this
> project using command line arguments. I have to distribute this
> project to somebody.
>
> I was wondering how can I make an executable or some kind of
> installer, so that end user doesn't need to compile and worry if he/
> she has Python installed or not ?
>
> Every help is greatly appreciated.
>
> Thanks,
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: why there is no pythonscript insine web browsers?

2007-11-13 Thread Shane Geiger
At the last PyCon, Brett Cannon told me that he had already implemented
the security architecture (or security template) for Python within
Firefox.  However, he did not go forward with the project because he
would not be able to get a PhD from doing it.  :-) 




Dennis Lee Bieber wrote:
> On Tue, 13 Nov 2007 09:51:49 -, bramble <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
>   
>> Why can't it be safely sandboxed?
>>
>> That is, why not just have a Python interpreter and some safe subset
>> of the Python standard library run with the browser? I mean, aside
>> 
>
>   It's not just the library (at a start you'd need to strip out
> modules os, popen, and subprocess), but you'd also need to block out
> exec, eval() (and by extension, input() ) from the interpreter core.
> Might need to do nasty things to the low-level import mechanism so that
> villains can't rig a web site to contain an import module with ability
> to access the local file system.
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: 911 was a hoax!

2007-11-12 Thread Shane Geiger
ChairmanOfTheBored,

Since a friend of mine found in his WTC dust little iron-rich spheres
because I asked him to look for them, I have verification for myself
what RJ Lee Group already stated in their report:  These iron-rich
spheres are characteristic of the WTC dust.  This is evidence of
temperatures that were in excess of 2800F--temperatures for which the
NIST report has no explanation. 

In a nutshell:  The molten metal that NIST described until 2004 as
having come from the jet fuel fires and which in 2005 they claimed did
not exist--this molten metal is proof that the final report of September
2005 is incorrect.  (See the Kevin Ryan letter, linked to from my page
below for evidence that the official story changed over time.)

Some people who question the official story have real reason to do
so--based on physical evidence--as I outline on this Web page: 

http://scimethod.googlepages.com/verify

I know the page is a little long, but if you have the attention span,
you can verify for yourself that the NIST report is incorrect.  The NIST
report does not even discuss WTC7, and they have not come forth with an
explanation for it or for the way in which the Twin Towers collapsed. 
(They merely describe the "initial collapse conditions" of the Twin
Towers--so even the name of their report is incorrect.)  Don't take my
word for this, verify this from the links I provide to the actual NIST
report.

I know this is off-topic for these mailing lists, and I don't condone
spamming.  Furthermore, hat bullshit talk about "jew" this and "jew"
that makes me think this spammer is some kind of agent that is trying to
make everyone hate the 9/11 Truth movement.  Please stop that
immediately, and stop spamming these lists.

Incidentally, I also don't condone tirades based on myths.  Please
verify for yourself that some problems exist.


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Proposal: Decimal literals in Python.

2007-10-26 Thread Shane Geiger

D = lambda x: decimal.Decimal(str(x))

>> D(3.2)
Decimal("3.2")



Steven D'Aprano wrote:
> On Fri, 26 Oct 2007 19:19:46 +1000, Ben Finney wrote:
>
>   
>>> Of course we can intruduce a single character function name as an alias
>>> for the Decimal type constructor, but even then we have to use both
>>> parentheses and quotes for each and every decimal constant. We cannot
>>> make it shorter than D("12.34")
>>>   
>> Nor should we. A function or type name should be short but explicit, and
>> 'Decimal' is about as short as I'd want.
>> 
>
> You don't like str, int, float, list, set, dict, or bool?
>
> Or for that matter, enum
> http://www.python.org/dev/peps/pep-0354/
>
> *wink*
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to best send email to a low volume list?

2007-10-24 Thread Shane Geiger
A mailing list manager is really overkill for what he is trying to do
*IF* he is not maintaining a discussion list.  A "newsletter" list
doesn't sound like a discussion list, especially since he wants to hide
the email addresses of the other people. 

If you want to manage your mailing list in a mail client like Mozilla
Thunderbird, you can export them in CSV format.  You could put some
string in a certain field that would denote that someone is on the
mailing list, and you could compile the email addresses rather easily
and send out a message via the mailto: protocol (which I will use via
the 'open' command available in MacOSX).

import os

subject = ''   # note: you will have problems if you insert certain
characters.
body = '' # You are better off simply writing the message subject
and body once your mail client starts up.

to = ''
cc = ''
bcc=','.join("""[EMAIL PROTECTED]
[EMAIL PROTECTED]
[EMAIL PROTECTED]
[EMAIL PROTECTED]
[EMAIL PROTECTED]""".splitlines())
addresses = ''

headers = 'TO=' + to + '&CC=' + cc + '&BCC=' + bcc
url = 'mailto:' + addresses + '?subject=' + subject + '&' + headers +
'&body=' + body
os.system('open ' + url)


Contact me off list if you would like a little code to help you even
more.  I suspect there is a little bug in this code, but the idea is there.




Adam Lanier wrote:
> On Wed, 2007-10-24 at 16:54 +, chris wrote:
>   
>> I need to maintain a list of subscribers to an email list for a
>> "newsletter" that will be sent via a web form probably once a month.
>> I anticipate low numbers--tens to maybe one hundred subscribers at the
>> most.  Just curious what the best way to code this is.  Should I just
>> loop through the addresses and send one-off emails to each, or is it
>> better to somehow send to every recipient in one shot?  One thing I
>> would like to avoid in the latter scenario is each recipient being
>> able to see the entire list of recipients.  Also don't want to trigger
>> any kind of spam thing on my web host by sending out too many emails.
>>
>> Anyway, any tips appreciated.
>>
>> Thanks,
>> Chris
>>
>> 
>
> Before you reinvent the wheel, you should look into using a mailing list
> manager, Mailman for example:
>
> http://www.gnu.org/software/mailman/index.html
>
> Regardless, confirmed double-opt-in should be a requirement as should a
> mechanism for subscribers to unsubscribe themselves.
>
> Using a 'list address' as the from address and using bcc addressing will
> prevent your recipients from being able to see all the other recipient
> addresses.
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: calling a function from string

2007-10-22 Thread Shane Geiger
>>> exec("import datetime") ; exec("x = datetime." + "date." + "today()")
>>> print x
2007-10-22




james_027 wrote:
> hi,
>
> i have a function that I could like to call, but to make it more
> dynamic I am constructing a string first that could equivalent to the
> name of the function I wish to call. how could I do that? the string
> could might include name of the module.
>
> for example
>
> a_string = 'datetime.' + 'today()'
>
> how could I call a_string as function?
>
> Thanks
> james
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pull Last 3 Months

2007-10-17 Thread Shane Geiger
A simpler way, imho:

import datetime
m = {
1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'
}
month = datetime.date.today().month
if month == 1:
ans = [m[11], m[12], m[1]]
elif month == 2:
ans = [m[11], m[12], m[1]]
else:
ans = [m[month-2], m[month-1], m[month]]
print ans


Tim Chase wrote:
>> Is there a module that can pull str values for say the last 3 months?
>> Something like:
>>
>> print lastMonths(3)
>>
>> ['Sep', 'Aug', 'Jul']
>> 
>
> I don't think there's anything inbuilt.  It's slightly 
> frustrating that timedelta doesn't accept a "months" parameter 
> when it would be rather helpful (but how many days are in a 
> month-delta is something that changes from month-to-month).
>
> It's somewhat inelegant, but this works for me:
>
>import datetime
>
>def last_months(months):
>  assert months > 0
>  d = datetime.date.today()
>  m = d.strftime('%b')
>  yield m
>  while months > 1:
>d -= datetime.timedelta(days=28)
>m2 = d.strftime('%b')
>if m2 <> m:
>  m = m2
>  months -= 1
>  yield m
>
>print list(last_months(3))
>for month in last_months(24): print month
>
> The alternative would likely be to do something like subtract one 
> from the current month, and if it drops below 1, decrement the 
> year and reset the month to 12.  Equally fuzzy:
>
>def lastN(months):
>  assert months > 0
>  d = datetime.date.today()
>  for _ in xrange(months):
>yield d.strftime('%b')
>y,m = d.year, d.month
>if m > 1:
>  m -= 1
>else:
>  m = 12
>  y -= 1
>d = datetime.date(y,m,1)
>
> Use whichever you prefer.
>
> -tkc
>
>
>
>
>
>   

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: confused on calculating date difference in days.

2007-10-16 Thread Shane Geiger
# Example

import datetime
def days_old(birth_year=1974,birth_month=12,birth_day=7):
return (datetime.date.today() -
datetime.date(birth_year,birth_month,birth_day) ).days

>>> days_old()
12000



krishnakant Mane wrote:
> hello,
> thanks all of you for providing valuable help.
> right now I am confused about the delta object.
> how can I extract the difference between two dates in terms of day
> using the delta object?
> I tried reading the python docs but did not understand the concept of
> delta object and how can I measure the difference in terms of days
> between two dates.
> I expect that the days would be integers.
> secondly the format of my date is actually "16/10/2007", and this is
> all in varchar field inside a postgresql database.
> I understand that datetime.datetime.strptime would convert this string
> "16/10/2007" into a date object which I can then compare with the
> current date created by datetime.now().
> is that right?
> if yes then please explain me how I can get the delta object to give
> me results in days.
> regards,
> Krishnakant.
>   

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Building a Python app with Mozilla

2007-07-05 Thread Shane Geiger
Brett Cannon was doing some work with the Firefox security model to
allow Python coding from within Firefox.  He may have stopped doing the
work because it would not lead to a PhD.  I am really looking forward to
seeing someone making this a possibility.



Stefan Sonnenberg-Carstens wrote:
> On Do, 5.07.2007, 03:45, greg wrote:
>   
>> [EMAIL PROTECTED] wrote:
>>
>> 
>>> wxWidgets will give you native looking apps on both Linux and Windows
>>>   
>> Well, maybe. There's more to getting a native feel than
>> just using the right widgets. I once saw a Qt-based app on
>> MacOSX that had tiny little buttons that were too small
>> for the text they contained -- Aqua buttons just don't
>> scale down like that. :-(
>>
>> --
>> Greg
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>> 
> Qt based buttons don't either.
> If some fool uses absolute positioning and sizing,
> then it is not the toolkit to blame.
> I'm using wxPython for instance and use the sizers and placeholders
> there, so this is possible with Qt also.
> So, perhaps (which I don't know) Aqua buttons simply don't permit
> absolute stuff ?
> Or the Aqua programmers read the user interface guidelines carefully ?
>   

-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Off Topic: What is the good book to learn Python ?

2007-05-30 Thread Shane Geiger

Here are some excellent online books and tutorials to get started with:
http://www.python.org/doc/tut/ http://www.ibiblio.org/obp/thinkCSpy/ 
http://www.python.org/topics/learn/prog.html  
http://www.python.org/topics/learn/non-prog.html  
http://docs.python.org/lib/  http://diveintopython.org/ 
http://gnosis.cx/TPiP/  http://rox.sourceforge.net/basic_python.html



Here are some lists of books you can read online:
http://www.techbooksforfree.com/perlpython.shtml
http://en.wikibooks.org/wiki/Programming:Python
http://wiki.python.org/moin/PythonBooks


Some books:

Byte of Python
- online: http://www.byteofpython.info/files/120/byteofpython_120.pdf

Quick Tour of Python
- online: 
http://stsdas.stsci.edu/pyraf/doc/python_quick_tour/python_quick_tour.pdf


Python in Nutshell
- online: 
http://files.nixp.ru/books/programming/python/O%27Reilly%20--%20Python%20In%20A%20Nutshell.chm


Python Standard Library
- online: http://effbot.org/zone/librarybook-index.htm

Python tutorial
- online: 
http://www.ensta.fr/~enstar/doc/python/Python-Docs-2.4-PDF/tut.pdf



kaens wrote:

On 30 May 2007 11:25:22 -0700, Katie Tam <[EMAIL PROTECTED]> wrote:
  

I am new to this filed and begin to learn this langague. Can you tell
me the good books to start with ?


Katie Tam
Network administrator
http://www.linkwaves.com/main.asp
http://www.linkwaves.com

--
http://mail.python.org/mailman/listinfo/python-list




If you're experienced with other programming languages, I'd recommend
python in a nutshell, or perhaps programming python. I personally just
skimmed through the online tutorial, and kept the library and api
references handy.

Orielly publishers almost always have excellent books on learning new
programming languages.

I would also recommend to stay away from any "for dummies" or "in x
(hours/days)" books. They can be decent introductory material, but
unless you are really really new to programming, you probably wouldn't
be getting enough information to justify the cost of the book (and a
lot of times they have a lot of bad practices in them)

Good luck!
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Creating a distro of python... What would you include in it?

2007-05-30 Thread Shane Geiger
This is for Windows only, but since your target audience is newbies, 
that might be fine.


Python Sumo-Distribution for Windows - Freely downloadable Python 
distributions for Windows with many extra packages already installed and 
ready for use.

 -- http://code.enthought.com/enthon/




BJörn Lindqvist wrote:

On 30 May 2007 08:25:48 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
  

I am creating a distro of Python to be licensed as GPL am
wondering, what would anyone suggest as to 3rd party modules being put
into it (non-commercial of course!)? I know I'd put MySQLdb into it at
the very least. Any suggestions?



If your distro is to be GPL-licensed, does that mean that you want
your components to be GPL too? If so, the number of components you can
select is reduced drastically.

I'd like a distro with a good IDE, GUI toolkit (PyGTK for example),
Django and PyGame. Something you could point a newbie to and they
would be able to create "real" applications with, without needing to
download hundreds of dependencies.

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A best approach to a creating specified http post body

2007-05-18 Thread Shane Geiger

Why not use scotch.recorder?



Dave Borne wrote:

I need to build a special http post body that consists of :
name=value +\r\n strings.
Problem is that depending on operations the number of  name,value
pairs can increase and decrease.
Values need to be initialized at runtime, so storing premade text
files is not possible.



I'm not completely understanding your problems here. Can you explain
why urllib.urlencode wouldn't work?
(http://docs.python.org/lib/module-urllib.html)

Thanks,
-Dave
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

ipython environment question

2007-05-08 Thread Shane Geiger

"""
I'm trying to import ipython shell (which works great!) to set some 
variables and then run a function (which doesn't work).
It seems like such a simple thing.  Here's an example script to show 
what I'm trying to do.


Run the script and then try to change the variable project_name from the 
ipython prompt and then type create()
and the new value you assigned will *not* be used.  I tried to use "def 
create(project_name = project_name):"  Even that didn't work.


What slight of hand is necessary?



import os, sys

project_name = 'python_packages'
group_name = 'sgeiger'
repo = '/var/svn'

def create(repo=repo,group_name=group_name,project_name=project_name):
#def create():
  #os.system("sudo mkdir -p " + repo )
  #os.system("sudo svnadmin create " + repo)
  #os.system("sudo chown -R " + group_name + " " + repo)
  print "sudo mkdir -p " + repo + '/' + project_name
  print "sudo svnadmin create " + repo + '/' + project_name
  print "sudo chown -R " + group_name + " " + repo + '/' + project_name

if __name__ == '__main__':
  sys.argv.append('-cl')
  from IPython.Shell import IPShellEmbed
  ipshell = IPShellEmbed()
  print "Please set these variables:  project_name, group_name   ...and 
then type create()"

  ### I even tried to put all my
  ipshell() # this call anywhere in your program will start IPython

--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: script for seconds in given month?

2007-04-16 Thread Shane Geiger


import datetime

def first_day_of_next_month( year, month ):
   """returns the first day of the next month
   >>> first_day_of_next_month(2007,5)
   datetime.datetime(2007, 6, 1, 0, 0)
   >>> first_day_of_next_month(2007,12)
   datetime.datetime(2008, 1, 1, 0, 0)
   """
   oneday = datetime.timedelta(days=1)
   day = datetime.datetime(year, month, 1)
   if day.day == 1:
   day += oneday
   while day.day != 1:
   day += oneday
   return day


from time import mktime
def secondsInMonth(year, month):
   s1 = mktime((year,month,1,0,0,0,0,0,-1))
   day = first_day_of_next_month(year, month)
   year = day.year
   month = day.month
   s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
   return s2-s1


year = 2007
month = 2
print secondsInMonth(year, month)





[EMAIL PROTECTED] wrote:

Matt> from time import mktime
Matt> def secondsInMonth(year, month):
Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1))
Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
Matt> return s2-s1

Probably won't work if month==12. ;-)

Skip
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie help with array handling

2007-04-12 Thread Shane Geiger



"""

Since you are a beginner and since RCCILA (Runnable, Commented Code Is 
Least Ambiguous) I'm proving this example code to help you get used to 
manipulating data with python.  This should give you an idea of how to 
juggle a bit.  After you learn how to do this you likely still will not 
be juggling in the optimal way, but you will at least be able to manage 
your data.


Not having an ordered dictionary causes beginners some grief because 
they haven't yet wrapped their minds around the way the basic data types 
work.  (I don't recally understand why ordered dictionaries are not part 
of the standard library.  It seems that this would be a commonly used 
feature.)  However, UserDict is part of the standard library, and it can 
be used to create an ordered dict.  Due to Python's attempt to be 
accessible to all people, I would think a little more support for an 
ordered dictionary would be in Python already.


Nevertheless, beginners often stumble because they think they need an 
ordered dict when they really just need to learn to use various data 
types together.  I think this covers the basics.  If you can think of 
something not covered, let me know so I can add it to my examples.


"""

## dictionary
d1 = {
   'keyvalue2':[ 'value21', 'value22', 'value23'],
   'keyvalue3':[ 'value31', 'value32', 'value33'],
   'keyvalue1':['value11', 'value12', 'value13']
   }

d2 = {
   'keyvalue4':[ 'value41', 'value42', 'value43'],
   'keyvalue6':[ 'value61', 'value62', 'value63'],
   }

# merge the two dictionaries
d1.update(d2)


print d1.has_key('keyvalue3')  # True

# get the values of a dictionary key
v1,v2,v3 = d1['keyvalue3']
print v1,v2,v3   # value31 value32 value33


# now they are combined
print d1  # {'keyvalue4': ['value41', 'value42', 'value43'], 
'keyvalue6': ['value61', 'value62', 'value63'], 'keyvalue1': ['value11', 
'value12', 'value13'], 'keyvalue3': ['value31', 'value32', 'value33'], 
'keyvalue2': ['value21', 'value22', 'value23']}


# now they are a list of tuples
myList = list( d1.items() )

print myList #   [('keyvalue4', ['value41', 'value42', 'value43']), 
('keyvalue6', ['value61', 'value62', 'value63']), ('keyvalue1', 
['value11', 'value12', 'value13']), ('keyvalue3', ['value31', 'value32', 
'value33']), ('keyvalue2', ['value21', 'value22', 'value23'])]


myList.sort()  # sorts on the first item in the tuple
print myList  # [('keyvalue1', ['value11', 'value12', 'value13']), 
('keyvalue2', ['value21', 'value22', 'value23']), ('keyvalue3', 
['value31', 'value32', 'value33']), ('keyvalue4', ['value41','value42', 
'value43']), ('keyvalue6', ['value61', 'value62', 'value63'])]


newDictionary = {}

# loop through all the items in the list and create a dictionary
for key, values in myList:
   newDictionary[key] = values

print newDictionary  # 'keyvalue4': ['value41', 'value42', 'value43'], 
'keyvalue6': ['value61', 'value62', 'value63'], 'keyvalue1': ['value11', 
'value12', 'value13'], 'keyvalue3': ['value31', 'value32', 'value33'], 
'keyvalue2': ['value21', 'value22', 'value23']}




do something like this
{keyvalue1:[ value1, value2, value3],keyvalue2:[value1,value2, 
value3],keyvalue3,:[value1,value2,value3]}


On 12 Apr 2007 00:58:54 -0700, *loial* < [EMAIL PROTECTED] 
<mailto:[EMAIL PROTECTED]>> wrote:


I am new to python and am converting an awk script to python

I need to store some data in an array/table of some form

keyvalue1, value1, value2, value3
keyvalue2, value1,value2, value3
keyvalue3, value1,value2,value3
etc

I will later need to sort in keyvalue order and also need to be able
to check if a key already exists

It is not clear how to do this in python. All the examples I see have
just a key and a single value

--
http://mail.python.org/mailman/listinfo/python-list




--
Regards--
Rishi Pathak
National PARAM Supercomputing Facility
Center for Development of Advanced Computing(C-DAC)
Pune University Campus,Ganesh Khind Road
Pune-Maharastra 


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: bittorent

2007-04-11 Thread Shane Geiger
 be installed. If 
you're testing from another machine, you can use the BitTorrent download 
link at the bottom of the links page to download BitTorrent (or just go 
to bittorrent.com). You can use any BitTorrent client that you like. We 
just link to the mainline one because our friends wrote it.


Step 7 - Customize your page

There are three customizable parts to your links page: the user picture, 
the CSS stylesheet, and the blurb at the bottom. These are all in the 
snakebite web directory (by default /var/snakebite/web). Change them to 
whatever you'd like. I find that customizing your user picture makes the 
page feel about ten times more awesome.


Step 8 - Send your link to all of your friends

Remember, the link http://actlab.tv/snakebite/redirect/username will 
always send you to your currently running snakebite even if your IP 
changes. We think this is really handy because we always forget our IP.
If you already using dyndns or something, you can use that instead, we 
won't be hurt.


Step 9 - Reflect

Now you're sharing files over BitTorrent. Who knew that it could be this 
easy? If you have more files to share, you just drop them in the 
directory. Everything is automatic, everything is fun! With all the time 
we just saved setting this up, we can spend more time finding cool files 
to share and making funny user pictures. It's kind of like myspace 
really, except it's not broken every other day. (Well, let's hope.)






--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I import functions from another python file

2007-04-09 Thread Shane Geiger



Hi,
i have 2 python files in *different directory* , how can I import
python functions from 1 python file to another?

i get this error:
import task
ImportError: No module named task/





The directory that module is in must by on your python
path in order to import it.
That's not exactly correct.  You *can* import from files that aren't in 
your sys.path.  What follows is a full-working (with python 2.5) 
example.  Perhaps ihooks is going to be obsolete at some point, but it 
works now.  See PEP 302 for more info.  (I'm not sure how to modify this 
example to work with a newer import mechanism or else I would provide it 
to you.)




import os
def writefile(f, data, perms=750): open(f, 'w').write(data) and 
os.chmod(f, perms)


foobar = """
print "this is from the foobar module"

def x():
   print "This is the x function."

"""

writefile('/tmp/foobar.py', foobar)


# File:ihooks-example-1.py
import ihooks, imp, os, sys
def import_from(filename):
   "Import module from a named file"
   if not os.path.exists(filename):
   sys.stderr.write( "WARNING: Cannot import file." )
   loader = ihooks.BasicModuleLoader()
   path, file = os.path.split(filename)
   name, ext = os.path.splitext(file)
   m = loader.find_module_in_dir(name, path)
   if not m:
   raise ImportError, name
   m = loader.load_module(name, m)
   return m

foo = import_from("/tmp/foobar.py")

print foo.x
print foo.x()
print foo.x()





 You can do it by modifying
sys.path or by setting the PYTHONPATH env variable.


$ mkdir otherdir
$ cat > otherdir/amod.py
def afunc():
return 'found'
$ python
  

import amod


Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named amod
  

import sys
sys.path.append('otherdir')
import amod
amod.afunc()


'found'
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can i compare a string which is non null and empty

2007-04-01 Thread Shane Geiger
It is probably worth noting that the example is not executable code:  
str() is a function.



[EMAIL PROTECTED]:~$ python
Python 2.4.4c0 (#2, Jul 30 2006, 15:43:58)
[GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if str: print "whoah, str is a function!"
...
whoah, str is a function!
>>>


/me pines for the day when all examples are executable code




Grant Edwards wrote:

On 2007-04-01, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

  

how can i compare a string which is non null and empty?


[...]
  

In java,I do this:
if (str != null) && (!str.equals("")) 

how can i do that in python?



If you want to litterally do that, it's

  if (str != None) and (str != ""):
  


However, the standard idiom for doing that in Python is

  if str:



  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Measureing memory used by a subprocess

2007-04-01 Thread Shane Geiger

Getting the pid:



http://timgolden.me.uk/python/wmi_cookbook.html

List all running processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
 print process.ProcessId, process.Name


List all running notepad processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process (name="notepad.exe"):
 print process.ProcessId, process.Name


Create and then destroy a new notepad process

import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create 
(CommandLine="notepad.exe")

for process in c.Win32_Process (ProcessId=process_id):
 print process.ProcessId, process.Name

result = process.Terminate ()




Andrew McLean wrote:
I want to script the benchmarking of some compression algorithms on a 
Windows box. The algorithms are all embodied in command line 
executables, such as gzip and bzip2. I would like to measure three things:


1. size of compressed file
2. elapsed time (clock or preferably CPU)
3. memory used

The first is straightforward, as is measuring elapsed clock time. But 
how would I get the CPU time used by a sub-process or the memory used?


I'm guessing that the Windows Performance Counters may be relevant, see 
the recipe


http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339

But I don't see any obvious way to get the process id of the spawned 
subprocess.


- Andrew
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [Python-Dev] Python 3000 PEP: Postfix type declarations

2007-04-01 Thread Shane Geiger

OMG, I was starting to reconsider Ruby.



Maël Benjamin Mettler wrote:
  Is this supposed to be a joke? 



First of April? Likely.
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: clean up html document created by Word

2007-03-30 Thread Shane Geiger
Tidy can now perform wonders on HTML saved from Microsoft Word 2000! 
Word bulks out HTML files with stuff for round-tripping presentation 
between HTML and Word. If you are more concerned about using HTML on the 
Web, check out Tidy's "Word-2000" 
<http://www.w3.org/People/Raggett/tidy/#word2000> config option! Of 
course Tidy does a good job on Word'97 files as well!

  -- source:  http://www.w3.org/People/Raggett/tidy/



jkn wrote:

IIUC, the original poster is asking about 'cleaning up' in the sense
of removing the swathes of unnecessary and/or redundant 'cruft' that
Word puts in there, rather than making valid HTML out of invalid HTML.
Again, IIUC, HTMLtidy does not do this.

If Beautiful Soup does, then I'm intererested!

jon N

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A nice way to use regex for complicate parsing

2007-03-29 Thread Shane Geiger

It would be worth learning pyparsing to do this.



aspineux wrote:

My goal is to write a parser for these imaginary string from the SMTP
protocol, regarding RFC 821 and 1869.
I'm a little flexible with the BNF from these RFC :-)
Any comment ?

tests=[ 'MAIL FROM:<[EMAIL PROTECTED]>',
'MAIL FROM:[EMAIL PROTECTED]',
'MAIL FROM:<[EMAIL PROTECTED]> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:[EMAIL PROTECTED] SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com>',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com',
'MAIL FROM:<"[EMAIL PROTECTED]> legal=email"@address.com> SIZE=1234
[EMAIL PROTECTED]',
'MAIL FROM:"[EMAIL PROTECTED]> legal=email"@address.com SIZE=1234
[EMAIL PROTECTED]',
]

def RN(name, regex):
"""protect using () and give an optional name to a regex"""
if name:
return r'(?P<%s>%s)' % (name, regex)
else:
return r'(?:%s)' % regex


regex={}

#  ::=  "."  "."  "." 
regex['dotnum']=RN(None, r'[012]?\d?\d\.[012]?\d?\d\.[012]?\d?\d\.
[012]?\d?\d' % regex)
#  ::=  |  "." 
regex['dot_string']=RN(None, r'[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*' %
regex)
#  ::=   |  "." 
regex['domain']=RN('domain', r'%(dotnum)s|%(dot_string)s' % regex)
#  ::= any one of the 128 ASCII characters except , , quote
("), or backslash (\)
regex['q']=RN(None, r'[^\n\r"\\]' % regex)
#  ::= any one of the 128 ASCII characters (no exceptions)
regex['x']=RN(None, r'.' % regex)
#  ::=  "\"  | "\"   |  |  
regex['qtext']=RN(None, r'(?:\\%(x)s|%(q)s)+' % regex)
#  ::=  """  """
regex['quoted_string']=RN('quoted_string', r'"%(qtext)s"' % regex)
#  ::=  | 
regex['local_part']=RN('local_part', r'%(quoted_string)s|%
(dot_string)s' % regex)
#  ::=  "@" 
regex['mailbox']=RN('mailbox', r'%(local_part)[EMAIL PROTECTED](domain)s' % 
regex)
#  ::= "<" [  ":" ]  ">"
# also accept address without <>
regex['path']=RN('path', r'(?P<)?%(mailbox)s(?(path_lt)>)' %
regex)
# esmtp-keyword::= (ALPHA / DIGIT) *(ALPHA / DIGIT / "-")
regex['esmtp_keyword']=RN(None, r'[a-zA-Z0-9][-a-zA-Z0-9]*' % regex)
# esmtp-value  ::= 1*

--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Auto execute python in USB flash disk

2007-03-27 Thread Shane Geiger



Is there
a way to auto execute a python script after a user double clicks to
open a folder on the USB drive? How can you capture that double click
event on a specific folder?



That would depend on what desktop / Operating System you're
using. If it's Windows, you need a shell extension (which
is non-trivial to understand and write). If it's one of the
Linux desktops, someone else had better chip in!
  


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_15.shtml#e390


--


There is a new version of `Movable Python
<http://www.voidspace.org.uk/python/movpy/>`_
available.

This is available for **Movable Python** for Python 2.2.3, 2.3.5, 2.4.3
and 2.5rc2 from :

   `The Movable Python Groups Page
<http://voidspace.tradebit.com/groups.php>`_



What is Movable Python
==

Movable Python is a portable distribution of Python for windows,
designed to be run off a USB stick or computers that don't have Python
installed. It features an IDE (Pythonwin and IDLE are included - but
you can also use SPE), and a GUI launcher.

It can be configured to use multiple interpreters from a single
interface, including acting as a GUI for any executable.

It has a host of other features (like logging all output from files,
enabling psyco for all scripts, etc).

See the following link for a list of all the new features in Movable
Python 2.0.0 :


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_15.shtml#e390

For an overview of the most important features (with screenshots) see :


http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_22.shtml#e396

Other uses for Movable Python include testing programs with different
versions of Python, and providing clean install 'sandboxes' for testing
programs. It is also an ideal launcher for IronPython.




--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: enumerating processes

2007-03-27 Thread Shane Geiger



I believe you are looking for os.getpid()
I apologize for providing that bit of incorrect info. 

It looks to me as if Python 1.5 had os.process which might have done 
what you wanted (although perhaps not in an OS-independent way).  I 
wonder why there isn't an OS-independent way to do that in Python now.


After having seen your message about tomcat.exe, I assume we are talking 
just about Windows.  ;-)  This looks like an excellent way to deal with 
processes on Windows:


# http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes

# List all running processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
 print process.ProcessId, process.Name


# List all running notepad processes

import wmi
c = wmi.WMI ()
for process in c.Win32_Process (name="notepad.exe"):
 print process.ProcessId, process.Name


# Create and then destroy a new notepad process

import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create 
(CommandLine="notepad.exe")

for process in c.Win32_Process (ProcessId=process_id):
 print process.ProcessId, process.Name

result = process.Terminate ()









李现民 wrote:

hi ,all
   any one knows how to enumerate the current running processes , or 
how to obtain a specific process by its name or process id. I know I 
can do this in many  programming languages , but how in python? any 
one know?

 Thanks for any guidance.

--
li xianmin

   [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> 




--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: enumerating processes

2007-03-26 Thread Shane Geiger

I believe you are looking for os.getpid()


李现民 wrote:

hi ,all
   any one knows how to enumerate the current running processes , or 
how to obtain a specific process by its name or process id. I know I 
can do this in many  programming languages , but how in python? any 
one know?

 Thanks for any guidance.

--
li xianmin

   [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> 


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using remote source code

2007-03-24 Thread Shane Geiger

Alex,

I see that you aren't using ihooks.  Below is an example I found that 
uses ihooks.  I think it would be worth comparing and contrasting both 
approaches (though I am not familar enough with this aspect of Python to 
do so).  IIRC, this code addresses some path related issues of other 
import-from-file methods.


Note: This might not work from within ipython, but it works from within 
Python.






"""


The ihooks module
This module provides a framework for import replacements. The idea is to 
allow several alternate

import mechanisms to co-exist.

Example: Using the ihooks module
"""


import os
def writefile(f, data, perms=750): open(f, 'w').write(data) and 
os.chmod(f, perms)


foobar = """
print "this is from the foobar module"

def x():
   print "This is the x function."

"""

writefile('/tmp/foobar.py', foobar)


# File:ihooks-example-1.py
import ihooks, imp, os, sys
def import_from(filename):
   "Import module from a named file"
   if not os.path.exists(filename):
   sys.stderr.write( "WARNING: Cannot import file." )
   loader = ihooks.BasicModuleLoader()
   path, file = os.path.split(filename)
   name, ext = os.path.splitext(file)
   m = loader.find_module_in_dir(name, path)
   if not m:
   raise ImportError, name
   m = loader.load_module(name, m)
   return m

foo = import_from("/tmp/foobar.py")

print foo.x
print foo.x()
print foo.x()




[EMAIL PROTECTED] wrote:

On Mar 25, 3:20 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
  

<[EMAIL PROTECTED]> wrote:


Is there any possible way that I can place a .py file on the internet,
and use that source code in an .py file on my computer?
  

You can write an import hook in any way you like; see
<http://www.python.org/dev/peps/pep-0302/> .

Here's a trivial example (bereft of much error checking, etc).  I've
uploaded tohttp://www.aleax.it/foo.pya toy module w/contents:

def foo(): return 'foo'

Here's a tiny program to import said module from my site:

import urllib2, sys, new

theurl = 'http://www.aleax.it/'

class Examp(object):
names = set([ 'foo', ])
def find_module(self, fullname, path=None):
if fullname not in self.names: return None
self.foo = urllib2.urlopen(theurl+fullname+'.py')
return self
def load_module(self, fullname):
module = sys.modules.setdefault(fullname,
  new.module(fullname))
module.__file__ = fullname
module.__loader__ = self
exec self.foo.read() in module.__dict__
return module

def hooker(pathitem):
print 'hooker %r' % pathitem
if pathitem.startswith(theurl): return Examp()
raise ImportError

sys.path_hooks.append(hooker)
sys.path.append(theurl)

import foo
print foo.foo()

Alex



Thanks for your help, now I can continue building my source code
generator. :)

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List comprehension returning subclassed list type?

2007-03-24 Thread Shane Geiger

To the best of my understanding, this answers your question:

  iterable
 A container object capable of returning its members one at a
 time. Examples of iterables include all sequence types (such as
 list, str, and tuple) and some non-sequence types like dict and
 file and objects of any classes you define with an __iter__()
 or __getitem__() method. Iterables can be used in a for loop
 and in many other places where a sequence is needed (zip(),
 map(), ...). When an iterable object is passed as an argument
 to the builtin function iter(), it returns an iterator for the
 object. This iterator is good for one pass over the set of
 values. When using iterables, it is usually not necessary to
 call iter() or deal with iterator objects yourself. The for
 statement does that automatically for you, creating a temporary
 unnamed variable to hold the iterator for the duration of the
 loop. See also iterator, sequence, and generator.


bullockbefriending bard wrote:

Given:

class Z(object):
various defs, etc.

class ZList(list):
various defs, etc.

i would like to be able to replace

z_list = ZList()
for y in list_of_objects_of_class_Y:
z_list.append(y)


with something like this:

z_list = [Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y]

Of course this just gives me a plain list and no access to the
methodsof z_list. I could, of course go and write a static method in
ZList which takes a plain list of Z objects and returns a ZList.

Anyway, my question is whether or not this can be done more elegantly
via list comprehension?

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Removing Python 2.4.4 on OSX

2007-03-24 Thread Shane Geiger
You don't have to uninstall 2.4.4 to use 2.5.  Just change where the 
symlink points:


[EMAIL PROTECTED]:~\ 14:45:35$ ls -la /usr/bin/python
lrwxr-xr-x   1 root  wheel  24 Mar  1 12:48 /usr/bin/python -> 
/usr/local/bin/python2.5

[EMAIL PROTECTED]:~\ 14:45:40$

In general, I am a little wary of uninstalling programs like Python 
which are used by many applications.  You don't want to find out after 
you have uninstalled it that something actually needed it.  It is much 
safer to keep it around.



[EMAIL PROTECTED] wrote:

On Mar 24, 11:30 am, "Robert Hicks" <[EMAIL PROTECTED]> wrote:
  

I want to upgrade to 2.5 but I don't see any unistall instructions
anywhere.

Robert



Windows allows us to uninstall it. I think the only thing it really
installs is the files, and then it sets the system path, so just
delete the files and change your path. Unfortunately, I do not have a
Mac to test with.

Mike

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Join strings - very simple Q.

2007-03-24 Thread Shane Geiger

import string

def test_join(l):
   print "Joining with commas: ",  string.join(l,',')
   print "Joining with empty string:   ",  string.join(l,'')
   print "Joining same way, using another syntax:  ",  ''.join(l)
   print "Joining with the letter X:   ",  'X'.join(l)
   print "Joining with <-> ",  '<->'.join(l)

l = ['a','b','c']

test_join(l)


"""
Example output:

Joining with commas:  a,b,c
Joining with empty string:abc
Joining same way, using another syntax:   abc
Joining with the letter X:aXbXc
Joining with <->  a<->b<->c

"""






Dustan wrote:

On Mar 24, 5:59 am, "Dustan" <[EMAIL PROTECTED]> wrote:
  

On Mar 23, 1:30 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:



Mike Kent escreveu:
...
  

New way:
l=['a','b','c']
jl=','.join(l)


I thank you all.
  
Almost there ...

I tried "".join(l,',') but no success ... :-(
  
Paulo
  

Perhaps you're doing it wrong, despite having an example right in
front of you?

Side by side comparison:
jl=string.join(l,',')
jl=','.join(l)

The sequence is passed as an argument to the join method, and the
delimiter is the string whose method is being called.



To further demonstrate (because I got a weird email that seemed to
think that my code didn't work):

  

import string
l = ['a','b','c']
string.join(l,',')


'a,b,c'
  

','.join(l)


'a,b,c'

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Create new processes over telnet in XP

2007-03-23 Thread Shane Geiger
This reminds me of something I once wanted to do:  How can I install 
Python in a totally non-gui way on Windows (without the use of VNC)?  I 
think I was telnetted into a computer (or something like that) and I was 
unable to run the usual Python installer because it uses a GUI.






Laurent Pointal wrote:

Jorgen Grahn wrote:

  

On 23 Mar 2007 03:47:14 -0700, Godzilla <[EMAIL PROTECTED]> wrote:


Hello,

How do you create/spawn new processes in XP over telnet using python?
I.e. I would like to create a new process and have it running in the
background...
  

Ssh -- or even rsh -- are better choices than telnet for these things.
For some reason, they are not standard in Windows, though.

  ssh somewhere some command with arguments
  rsh somewhere some command with arguments

compared to

  telnet somewhere

and then performing expect-like things (basically simulating
someone typing "some command with arguments" in the telnet
session).



+ for an sshd running as a service under XP, look at CopSSH.

+ hope started process doesn't want a GUI... else, look at UltraVNC running
as daemon, and port redirection using ssh.

  

when I terminate the telnet connection, I would what the
spawned processes to keep running until I shut it off...
  

That's a function of the remote OS; what happens when its terminal
goes away is not under the control of the client side.



Maybe the process starting job can be done by a Python program running as
Windows service and waiting for requests on a port (or Pyro object or Corba
object...). 
No need for telnet/ssh connection, no logout problem.


Just care of possible security problems :-) 




  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: flattening/rolling up/aggregating a large sorted text file

2007-03-21 Thread Shane Geiger
Apparently you want to use this data to know how many blue circles, blue 
squares, red circles and red squares.  In other words, I doubt you want 
to output redundant data columns, you just want this data in a more 
usable format and that you don't actually need to do multiple passes 
over it.


This is a fun problem to solve because it uses two very powerful tools: 
cvs.dictreader and bitwise categorization.


Note: your initial data has three records with the same ID.  I assumes 
the ID is the unique key.  So I changed the data slightly.






[EMAIL PROTECTED] wrote:

Hi,

Given a large ascii file (delimited or fixed width) with one ID field
and dimensions/measures fields, sorted by dimensions, I'd like to
"flatten" or "rollup" the file by creating new columns: one for each
combination of dimension level, and summing up measures over all
records for a given ID.

If the wheel has already been invented, great, please point me in the
right direction. If not, please share some pointers on how to think
about this problem in order to write efficient code.

Is a hash with dimension level combinations a good approach, with
values reset at each new ID level?

I know mysql, Oracle etc will do this , but they all have a cap on #
of columns allowed. SAS will allow unlimited columns, but I don't own
SAS.

Thanks.


ID,color,shape,msr1
--
001, blue, square,  4
001, red , circle,5
001, red,  circle,6


ID, blue_circle, blue_square, red_circle, red_square
--
001,0,4,11,0
002 ...

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy


"""

Apparently you want to use this data to know how many blue circles, blue 
squares, red circles and red squares.  In other words, I doubt you want to 
output redundant data columns, you just want this data in a more usable format 
and that you don't actually need to do multiple passes over it.

This is a fun problem to solve because it uses two very powerful tools: 
cvs.dictreader and bitwise categorization.

Note: your initial data has three records with the same ID.  I assumes the ID 
is the unique key.  So I changed the data slightly.

--

Given a large ascii file (delimited or fixed width) with one ID field
and dimensions/measures fields, sorted by dimensions, I'd like to
"flatten" or "rollup" the file by creating new columns: one for each
combination of dimension level, and summing up measures over all
records for a given ID.

If the wheel has already been invented, great, please point me in the
right direction. If not, please share some pointers on how to think
about this problem in order to write efficient code.

Is a hash with dimension level combinations a good approach, with
values reset at each new ID level?

I know mysql, Oracle etc will do this , but they all have a cap on #
of columns allowed. SAS will allow unlimited columns, but I don't own
SAS.

Thanks.


ID,color,shape,msr1
--
001, blue, square,  4
001, red , circle,5
001, red,  circle,6


ID, blue_circle, blue_square, red_circle, red_square
--
001,0,4,11,0
002 ...

"""

import string


## BITWISE CATEGORIZATION STUFF

def gNextBit(val=0):
while True:
y = 2**val
val += 1
yield y

nb = gNextBit()

categories = ['blue','red','square','circle']
#categories_value = ['blue','red','square','circle']

def bitwise_categorize(items):
d = {}
for item in items:
d[item] = nb.next()
return d

categories_dict = bitwise_categorize(categories)

#print categories_dict  # {'blue': 1, 'circle': 8, 'square': 4, 'red': 2}  

def get_properties(category_int):
p_list = []
for k,v in categories_dict.items():
if category_int & v == v:  
p_list.append(k)
return p_list

def list_properties():
for i in range(len(categories)**2):
print "Properties for something with category_int 
of",str(i),str(get_properties(i))

#list_properties()



### EXAMPLE DATA

header_fields = ['id','color','shape','msr1']

example_data = """
001, blue, square,  4
002, red , circle,5
003, red,  circle,6
"""

# write out the example
import os
def writefile(f, data, perms=750): open(f, 'w').write(data) and os.chmod(f, 
perms)
csv_file = "/Users/shanegeiger/temp.csv"
writefile(csv_file, example_data)




###   READING IN THE DATA AND CATEGORIZING IT WITH BITWISE CATEGORIZATION

import csv
reade

Re: Pycron for windows - please help

2007-03-20 Thread Shane Geiger
Here's something else you should consider:  Look at the source code of 
pycron.  I just downloaded it.  Much to my surprise, this is implemented 
in about 115 lines of code.


In particular, look at the run() function.  You should try adding a 
try-except block around the system call to get a hint as to where the 
problem lies:



   try:
os.system('start ' + command)  


   
except:  

   print "Unexpected error to catch:", 
sys.exc_info()[0]



I've been trying to use it myself (on a Mac) since I saw you mention it 
on the mailing list.  I'm also having problems using pycron.  Email me 
directly if you figure out the problem.  I'll do the same for you.






Gabriel Genellina wrote:

En Mon, 19 Mar 2007 16:00:04 -0300, Al <[EMAIL PROTECTED]> escribió:

  

I looked in the pycron.log file, and I noticed that for the entires of
my new job, I see "rc=4" and the end of each line. All other jobs have
"rc=0" at the end of the line. I assume then, that rc=4 is a reference
to an error code of some kind, but there is no information on this in
the readme.txt, at the pycron website, or here in groups.

Does anyone know how to troubleshhot this? Thanks in advance.



Contacting the author?

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Anything available that can read Microsoft .MDB files from Python?

2007-03-20 Thread Shane Geiger
Try installing it from source.  Perhaps getting a newer verion is all 
you would need.  If at that point you find there is a bug, report it.



Diez B. Roggisch wrote:

   What MDBtools did you install?  The RPM, a checkout from CVS,
or the downloadable distribution?  They're all different.




The one that comes with ubuntu edgy. Just


apt-get install mdbtools

or something, that's it.

I don't want to start a distro war here - but I always found the 
RPM-based distros lacking, to say the least.


Diez
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: using regexp

2007-03-19 Thread Shane Geiger


import re
line = '123456789123456789'
print re.findall('([0-9]{3})', line)



Shane Geiger wrote:

You don't even need regex.

def 
split_seq(seq,size):   

   # this is sort of the inverse of 
flatten   

   # Source: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044   

   return [seq[i:i+size] for i in range(0, len(seq), 
size)]   

  

line = 
'123456789123456789'

  

print 
split_seq(line,3)




Will that work for you?



[EMAIL PROTECTED] wrote:

hi
how can i use regexp to group these digits into groups of 3?

eg
line 123456789123456789

i have :

pat = re.compile("line\s+(\d{3})" , re.M|re.DOTALL)

but this only gives the first 3. I also tried

"line\s+(\d{3})+"
but also not working.
I need output to be ['123' ,'456','789', '123','456','789', .]
thanks.

  




--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: using regexp

2007-03-19 Thread Shane Geiger

You don't even need regex.

def 
split_seq(seq,size):   

   # this is sort of the inverse of 
flatten   

   # Source: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044   

   return [seq[i:i+size] for i in range(0, len(seq), 
size)]   

  

line = 
'123456789123456789'

  

print 
split_seq(line,3)




Will that work for you?



[EMAIL PROTECTED] wrote:

hi
how can i use regexp to group these digits into groups of 3?

eg
line 123456789123456789

i have :

pat = re.compile("line\s+(\d{3})" , re.M|re.DOTALL)

but this only gives the first 3. I also tried

"line\s+(\d{3})+"
but also not working.
I need output to be ['123' ,'456','789', '123','456','789', .]
thanks.

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: check if files are the same on Windows

2007-03-19 Thread Shane Geiger

In the unix world, 'fc' would be like diff.

"""
Python example of checksumming files with the MD5 module.

In Python 2.5, the hashlib module would be preferable/more elegant.
"""

import md5

import string, os
r = lambda f: open(f, "r").read()
def readfile(f,strip=False): return (strip and stripper(r(f))) or r(f)
def writefile(f, data, perms=750): open(f, "w").write(data) and 
os.chmod(f, perms)


def get_md5(fname):
   hash = md5.new()
   contents = readfile(fname)
   hash.update(contents)
   value = hash.digest()
   return (fname, hash.hexdigest())

import glob

for f in glob.glob('*'):
   print get_md5(f)




A crude way to check if two files are the same on Windows is to look
at the output of the "fc" function of cmd.exe, for example

def files_same(f1,f2):
cmnd= "fc " + f1 + " " + f2
return ("no differences" in popen(cmnd).read())

This is needlessly slow, because one can stop comparing two files
after the first difference is detected. How should one check that
files are the same in Python? The files are plain text.

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list comprehension help

2007-03-18 Thread Shane Geiger
Since you are dealing with that much information perhaps pytables would 
be useful to you.http://pytables.sourceforge.net




[EMAIL PROTECTED] wrote:

Hi
I need to process a really huge text file (4GB) and this is what i
need to do. It takes for ever to complete this. I read some where that
"list comprehension" can fast up things. Can you point out how to do
it in this case?
thanks a lot!


f = open('file.txt','r')
for line in f:
db[line.split(' ')[0]] = line.split(' ')[-1]
db.sync()
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: where function

2007-03-18 Thread Shane Geiger
a = 
[0,1,2,3,4,2,8,9]   

   

# method 
1  

print [i for i in xrange(len(a)) if 
a[i]==2]

   

def 
where(a,val):   

   return [i for i in xrange(len(a)) if 
a[i]==val] 

   

# method 
2  

print 
where(a,2)

   






[EMAIL PROTECTED] wrote:

On Mar 18, 10:48 pm, [EMAIL PROTECTED] wrote:
  

vorticitywo:



Is there a function in Python analogous to the "where" function in
IDL?
  

Python gives very elastic syntax, you can simply do:

data = [0,1,2,3,4,2,8,9]
print [pos for pos, el in enumerate(data) if el==2]

Bye,
bearophile



Thank you both, a little more cumbersome than I expected, but it does
the job! Thanks!

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re:

2007-03-17 Thread Shane Geiger

Milton,

This isn't terribly elegant, but it gets the job done:

dirs = ['C:\Images', 'C:\Images\2006', 'C:\Images\2007', 'C:\Music', 
'C:\Files', 'C:\Software', 'C:\Software\Python', 'C:\Software\iTunes'] 

exclude_list = 
['Software','Images'] 



def foo(d):
   retval = d
   for item in exclude_list:
   if item in d:
   retval = False
   return retval

dirs = map(foo, dirs)
dirs = filter(bool, dirs)  # removes the Falses
print dirs


Milton Segura wrote:

Hello, I'm trying to exclude files from a list using the following code:
 
for item in dirs:

if item.find('Software') > -1:
dirs.remove(item)
elif item.find('Images') > -1:
dirs.remove(item)
 
let's supose dirs = ['C:\Images', 'C:\Images\2006', 'C:\Images\2007', 
'C:\Music', 'C:\Files', 'C:\Software', 'C:\Software\Python', 
'C:\Software\iTunes']
 
For some reason.. it just won't exclude them.

I'd like to know why and how to fix it.
Thanks in advance.
Milton


Explore the seven wonders of the world Learn more! 
<http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE>


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get the previous line in a file?

2007-03-16 Thread Shane Geiger
lines = open('/tmp/foo.py', 
"r").read().splitlines()

previous_line = 
''  

for line in 
lines:  

   if "foo" in 
line:   

   print "found foo in the current line.  The previous line is:  " 
+ 
previous_line 

   previous_line = 
line




Qilong Ren wrote:

Hi,all

I am new to this list. And I am glade I am here.
I have a question. I need to do some text processing. I need to read 
from a file line by line. If some line is met with some condition, the 
previous line needs some modification. How to get the info of the 
previous line?


Thanks!
Qilong


Never miss an email again!
Yahoo! Toolbar 
<http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolbar/features/mail/> 
alerts you the instant new Mail arrives. Check it out. 
<http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/features/mail/>


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: distributing python software in jar like fashion

2007-03-14 Thread Shane Geiger



Hi,

I have a small app which consist of a few .py files. Is there any way to 
distribute it in jar like fashion as a single file I can just run python 
on. I obviously look for platform independent solution.


Thx in advance, A.
  


"""
Author:  Shane Geiger <[EMAIL PROTECTED]>


Wed Mar 14 21:55:58 CDT 2007

Hi,

I have a small app which consist of a few .py files. Is there any way to
distribute it in jar like fashion as a single file I can just run python
on. I obviously look for platform independent solution.

--

Here's an answer to your question.


To use this script put it in the same directory as your .py files.
See the glob.glob function below if you want to specify a directory if 
you want to change that.

(I tried to keep this example simple.)


Use the 'pack_mode()' and 'unpack_mode()' function calls at the bottom 
of the script to

control it.

Note: I have not tested this on Windows.

"""


import base64
import string, os
import zipfile
import glob

def readfile(f): return open(f, "r").read()
def writefile(f, data, perms=750): open(f, "w").write(data) and 
os.chmod(f, perms)


zip_file_name = 'python_modules.zip'


def write_test_modules():
   ## some test modules
   srgexample="""
print "This was base64 encoded."
   """
   srgexample2="""
print "This, too, was base64 encoded, and it was imported from a zip."
   """
   writefile('srgexample.py',srgexample)
   writefile('srgexample2.py',srgexample2)

def test_mode_cleanup():
   os.remove('srgexample.py')
   os.remove('srgexample2.py')
   os.remove(zip_file_name)


def pack_mode():
   """
   PACKING MODE:
   (you could automate this procedure if it is important to you)
   Zip the source files into one .zip file for easier handling.
   Base64 encode the zip file to avoid problems of including the file.
   Include the base64 representation of the zip file in a docstring, a
  step that you could automate (but I haven't).
   """

   write_test_modules()
  
   # open the zip file for writing, and write stuff to it

   import zipfile
   import glob, os
   # open the zip file for writing, and write stuff to it
   file = zipfile.ZipFile(zip_file_name, "w")

#for name in glob.glob("*.py"):
   for name in [x for x in glob.glob("*.py") if x != __file__]:  # 
dont' try to zip up this file

   file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
   file.close()
   ## Here's how to watch what gets added
   ## open the file again, to see what's in it
   #file = zipfile.ZipFile(zip_file_name, "r")
   #for info in file.infolist():
   #print info.filename, info.date_time, info.file_size, 
info.compress_size


   contents = open(zip_file_name, "r").read()
   file_contents_in_base64 = base64.encodestring(contents)
   print "Assign the following base64 encoded string to the 
'python_modules_zip_base64' "

   print "  variable (after which you can use unpack mode)."
  
   print file_contents_in_base64

   # THEN MANUALLY ADD THAT to your main file.
   # You could automatically edit the currently running file like this:

   test_mode_cleanup()


def unpack_mode():
   """
   UNPACKING MODE:
   """
   python_modules_zip_base64="""
UEsDBBQIABq8bjYpPJvJJgAAACYNc3JnZXhhbXBsZS5weeMqKMrMK1FQCsnILFYo
TyxWSEosTjUzUUjNS85PSU3RU+JSAAIAUEsDBBQIABq8bjZ5v8x4SEwOc3Jn
ZXhhbXBsZTIucHkdyTEKgDAMBdC9p/h0Dk7iSXqBaCJmaFPagODpFd/6Uh/WArlcNgnhTrh5Yuep
2wpth4sKgZvA4i+r3Ueo4BxewXisLznh8wJQSwECFAMUCAAavG42KTybySYmDQAA
pIEAc3JnZXhhbXBsZS5weVBLAQIUAxQIABq8bjZ5v8x4SEwO
AACkgVEAAABzcmdleGFtcGxlMi5weVBLBQYAAgACAHcAAADFAAA=
"""
   zip_file_contents = base64.decodestring(python_modules_zip_base64)
   def writefile(f, data, perms=750): open(f, "w").write(data) and 
os.chmod(f, perms)

   writefile(zip_file_name,zip_file_contents)

   # open the file, to see what's in it
   #file = zipfile.ZipFile("test.zip", "r")
   #for info in file.infolist():
   #print info.filename, info.date_time, info.file_size, 
info.compress_size


   import sys
   sys.path.insert(0, zip_file_name)  # Add .zip file to front of path
   import srgexample
   import srgexample2

   ### you could even remove the file after using it
   os.remove(zip_file_name)

pack_mode()
#unpack_mode()





--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: dict.items() vs dict.iteritems and similar questions

2007-03-14 Thread Shane Geiger
# Just by looking at the output, it seems pretty obvious that xrange 
would be more memory effcient for large ranges:


print "With range():",range(100,200)
print
print "With xrange():",xrange(100,200)

d = {1:2,2:3,3:4}
d.items()
d.iteritems()

#  I have been curious to use Pysizer (which requires patching Python) 
to demonstrate the difference.




Drew wrote:

When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
  print key,val

for key,val in mydict.iteritems():
  print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Thanks,
Drew

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: number generator

2007-03-14 Thread Shane Geiger
Raymond:   It looks to me as if you are trying to turn a generator into 
a list in the final line.  That doesn't work.




Raymond Hettinger wrote:

To make the solutions equi-probable, a simple approach is to
recursively enumerate all possibilities and then choose one of them
with random.choice().



Since people are posting their solutions now (originally only hints
were provided for the homework problem), here's mine:

def genpool(n, m):
if n == 1:
yield [m]
else:
for i in xrange(1, m):
for rest in genpool(n-1, m-i):
yield rest + [i]

import random
print random.choice(list(genpool(n=4, m=20)))

  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Mocking OpenOffice in python?

2007-03-14 Thread Shane Geiger
My take was that this is an effort to manipulate these files without the 
need for Open Office, so I replied as follows:


Open Office files (.ods and perhaps .odt) are just zipped or gzipped.  
Unpack that and then you are dealing with manipulating regular text 
files--probably HTML. 



Carsten Haese wrote:

On Wed, 2007-03-14 at 01:39 -0700, PaoloB wrote:
  

Hi everyone,

during our development, we need to write some unit tests that interact
with OpenOffice through pyUno.

Is there anyone who has got any experience on it? As OpenOffice is
quite a large beast, and interaction is rather complex, I would like
to know if there is someone who is willing to share experience (and,
possibly, code).



I have some experience with pyuno, but your question is very open-ended.
It would be helpful if you asked specific questions or gave more
background on what kind of interaction you're trying to achieve.

The generic answer to your request for code examples is that there's a
tutorial with example code at
http://udk.openoffice.org/python/python-bridge.html, and then there's
the API documentation at
http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html.

-Carsten


  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

-- 
http://mail.python.org/mailman/listinfo/python-list