[Tutor] USB Access

2010-03-30 Thread Marc
Hi,
I was wondering if anyone could point me to Python modules or example code for 
accessing USB connected devices.  I would like to get as close to the hardware 
as possible with Python.  I would like to be able to monitor as well as control 
USB connected devices.  I've looked at the missile launcher code by Pedram 
Amini at dvlabs.tippingpoint.com, but am looking to see what else has been done 
in this area.  

thanks,
Marc
Sent from my Verizon Wireless BlackBerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Issues Parsing XML

2009-03-10 Thread marc
Hello,

I am new to Python and as a first project decided to try to parse an XML
report using Python.  I have the following, which works to extract one
element.  I am stuck, however, at one element.  I want to extract several
differenct elements per line, creating a comma separated variable (CSV)
line that can be imported to a spreadsheet.  Not all elements are in each
line or part of the XML document - so if an element is not in a line, I
would leave a blank (2 commas).  I can probably figure that out - it's the
extracting multiple elements and putting them in one line that has me
stumped.  Help would be greatly appreciated.  Thank you.  What I have so
far (and I would like to stick to the DOM model):

import xml.dom.minidom
import sys


datasource=open(sys.argv[1])
domDatasource=xml.dom.minidom.parse(datasource)

def getText(nodelist):
rc=""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc=rc+node.data
return rc

def HandleStatus(Finding):
for Status in Finding:
print getText(Status.childNodes)

HandleStatus (domDatasource.getElementsByTagName("FINDING_STATUS"))

domDatasource.unlink()

An excerpt of the xml file:



GD2.0.8.8TRUEDTBI134-Allow
paste operations via
scripts-Restric2V0006310NFGD2.0.8.8TRUEDTBI135-Scripting
of Java applets -
Restricted2V0006311OThe value:
Software\Policies\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\4\1A00 does not exist.

The value:
Software\Policies\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\4\1A00 does not exist.

GD2.0.8.8TRUEDTBI136-User
Authentication - Logon -
Restricted2V0006312NFGD2.0.8.8TRUEDTBI150-Microsoft
Java VM is
installed2V0006313NFGD2.0.8.8TRUEDTBI151-Cipher
setting for DES 56/56 not
set2V0006314NFGD2.0.8.8TRUEDTBI152-Cipher
setting for Null is not
set2V0006315NFGD2.0.8.8TRUEDTBI153-Cipher
setting for Triple DES is not
set2V0006316OThe value:
SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled
does not exist.

The value:
SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled
does not exist.

GD2.0.8.8TRUEDTBI160-Hash
setting for SHA is not set
properly2V0006317NFGD2.0.8.8TRUEDTBG007-IE
is not capable to use 128-bit
encryptio2V0006318OThe key:
SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671
does not exist.

The key:
SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671
does not exist.

GD2.0.8.8TRUEDTBG010-DoD
Root Certificate is not
installed2V0006319NAGD2.0.8.8TRUEDTBI140-Error
Reporting tool is installed or
enabl2V0007006OThe value: Software\Microsoft\Internet
Explorer\Main\AutoSearch does not exist.

The value: Software\Microsoft\Internet
Explorer\Main\AutoSearch does not exist.



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


Re: [Tutor] Parse XML file

2009-03-15 Thread marc
> Message: 5
> Date: Sun, 15 Mar 2009 10:56:22 +0100
> From: Stefan Behnel 
> Subject: Re: [Tutor] Parse XML file
> To: tutor@python.org
> Message-ID: 
> Content-Type: text/plain; charset=ISO-8859-1
>
> Lukas Agrapidis wrote:
>> I am trying to parse an XML file using Python and found this resource
http://diveintopython.org/xml_processing/parsing_xml.html
>
> You might be interested in ElementTree:
>
> http://effbot.org/zone/element.htm
>
> It's a lot easier to use than minidom, especially for new users. It's
available in the standard library as "xml.etree.ElementTree" module
since
> Python 2.5.
>

I would agree - I was struggling with minidom, Stefan recommended
ElementTree and another person (deleted the email and can't recall his
name) recommended lxml.  I was able to get a working understanding of
these libraries in less than an hour and solve the problems I had
encountered with minidom in a very short time. (BTW, parsing xml was
probably a poor choice for my first project while learning Python, but
then again, nobody has ever accused me of making my life easy)

Marc



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


[Tutor] Trouble Parsing XML using lxml

2009-04-03 Thread marc
Hi - I'm hoping to get some guidance

I am trying to parse a structure that looks like:

{urn:FindingImport}TOOL - GD
{urn:FindingImport}TOOL_VERSION - 2.0.8.8
{urn:FindingImport}AUTHENTICATED_FINDING - TRUE
{urn:FindingImport}GD_VUL_NAME - Rename Built-in Guest Account
{urn:FindingImport}GD_SEVERITY - 2
{urn:FindingImport}FINDING - None
{urn:FindingImport}FINDING_ID - V0001115
{urn:FindingImport}FINDING_STATUS - NF
{urn:FindingImport}TOOL - GD
{urn:FindingImport}TOOL_VERSION - 2.0.8.8
{urn:FindingImport}AUTHENTICATED_FINDING - TRUE
{urn:FindingImport}GD_VUL_NAME - Rename Built-in Administrator Account
{urn:FindingImport}GD_SEVERITY - 2
{urn:FindingImport}FINDING - None
{urn:FindingImport}FINDING_ID - V0001117

This is the result when the original data is run through 'for element in
root.iter():' as described in the lxml tutorial.  This structure repeats
many times in the document with different values after each tag.  I want
to take the values and place them in one csv line for each structure in
the file.  The closest I have come is something like (but doesn't work):

for element in root.iter("{urn:FindingImport}TOOL"):
print element.text
print element.getnext().text
print element.getnext().text

The initial print element.tag and the first element.getnext().text work as
I would like, but I am not finding a way to parse past that.  The second
element.getnext().text returns the value for the same tag as the one prior
to it.  I know I am missing something, but don't see it.  Any assistance
is appreciated.

Thanks,

marc


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


[Tutor] Sending an email alert

2009-08-28 Thread Marc
Hello,

 

I am trying to code an email alert and am running into the following error:

Connecting to server

Traceback (most recent call last):

  File "C:\Users\Marc1\Documents\Python\email test\email.py", line 1, in


import smtplib

  File "C:\Python26\lib\smtplib.py", line 46, in 

import email.utils

  File "C:\Users\Marc1\Documents\Python\email test\email.py", line 12, in


s = smtplib.SMTP('smtp.marcd.org')

AttributeError: 'module' object has no attribute 'SMTP'

 

The code I am trying to use is:

 

import smtplib

import time

>From ="m...@mydomain.org"

To = ["m...@mydomain.org"]

Date = time.ctime(time.time())

Subject = "Email Python Test"

Text = "It Works!!"

mMessage = ('From %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To,
Date, Subject, Text))

print 'Connecting to server'

s = smtplib.SMTP('smtp.mydomain.org')

rCode = s.sendmail(From, To, mMessage)

s.quit()

if rCode:

   print 'Error sending message'

else:

   print 'message sent'

 

Of course, I am substituting m...@mydoamin.org with my email address and
'smtp.mydomain.org' with my domain email server.

 

The error seems to say that the method or function SMTP does not exist
within smtplib, but if I run the lines

 

import smtplib

s = smtplib.SMTP('smtp.mydomain.org')

 

in IDLE, it connects and then times out, as I would expect.

I tried this on Windows and Linux with the same result.

 

Thanks,

Marc

 

What am I missing here?

 

 

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


Re: [Tutor] Sending an email alert

2009-08-28 Thread Marc
> On Fri, Aug 28, 2009 at 3:00 PM, Marc wrote:
> > Hello,
> >
> >
> >
> > I am trying to code an email alert and am running into the following
> error:
> >
> >     s = smtplib.SMTP('smtp.marcd.org')
> >
> > AttributeError: 'module' object has no attribute 'SMTP'
> 
> Your file 'email.py' is hiding the std lib 'email' module and this is
> creating a circular import and basically a mess :-)
> 
> Try calling your program something else.
> 
> Kent

That did it - Thanks!!

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


Re: [Tutor] mod_python authentication

2009-12-07 Thread Marc
> On Mo, 2009-12-07 at 09:35 -0400, Rayon wrote:
> > How do I Check for an active login session on every page that
> requires
> > authentication
> >
> To understand sessions you first need to understand that HTTP is a
> stateless protocol: you connect, send your request, receive a response
> and the connection is closed.
> 
> There are several ways to accomplish this. The most straightforward way
> would be remembering the client's IP 
> Another method is putting the session's ID in the URLs you display to
> your users. 
> The most common and reliable choice is the good old session cookie

While I agree with the cookie (as long as it has a short expiration),
another way to do this is by using expiring tokenization (credentials + some
unique data for the transaction) in the URL header (see section 14.8 at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).  Tokenization
substitutes some random string for confidential data (such as credentials).
The payment card industry uses this in the form of an authorization code for
card transactions.  Add to the data represented by the token some unique
data (maybe a random number or some data from the last transaction - it
doesn't matter as the token does not expose the data in any way) for each
http transaction so you have unique token in each header and you can get an
essentially stateful session with a method of checking authentication that
has some spoof protection built in.  Wrap it all in SSL/TLS and then you've
got something.  Granted, this requires some serious server side work, and is
probably not a good beginner exercise, but if this level is what you
need  I have never coded anything like this in Python, but I can see
abstractly how it could be done (I'm a novice with Python). If you're bored,
you can read http://www.shift4.com/pdf/TokenizationWhitePaper.pdf especially
sec1:7.  Ok, Ok, I'll shut up now - I've got to go play with some XML
anyhow...Thanks for listening.





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


[Tutor] Parsing a multi-line/record text file

2012-11-10 Thread Marc
Hello,

I am trying to parse a text file with a structure that looks like:

[record: Some text about the record]
Attribute 1 = Attribute 1 text
Attribute 3 = Attribute 3 text
Attribute 4 = Attribute 4 text
Attribute 7 = Attribute 7 text

[record: Some text about the record]
Attribute 1 = Attribute 1 text
Attribute 2 = Attribute 2 text
Attribute 3 = Attribute 3 text
Attribute 4 = Attribute 4 text
Attribute 5 = Attribute 5 text
Attribute 6 = Attribute 6 text

[record: Some text about the record]
Attribute 2 = Attribute 2 text
Attribute 3 = Attribute 3 text
Attribute 7 = Attribute 7 text
Attribute 8 = Attribute 8 text

Etc.for many hundreds of records

I am looking to create output that looks like:

Attribute 1 text | Attribute 3 text
Attribute 1 text | Attribute 3 text
Blank  | Attribute 3 text

Treating each record as a record with its associated lines is the holy grail
for which I am searching, yet I seem to only be coming up with dead parrots.
It should be simple, but the answer is eluding me and Google has not been
helpful.

Pathetic thing is that I do this with Python and XML all the time, but I
can't seem to figure out a simple text file.  I 'm missing something simple,
I'm sure.  Here's the most I have gotten to work (poorly) so far - it gets
me the correct data, but not in the correct format because the file is being
handled sequentially, not by record - it's not even close, but I thought I'd
include it here:

 for line in infile:
  while line != '\n':
   Attribute1 = 'Blank'
   Attribute3 = 'Blank'
   line = line.lstrip('\t')
   line = line.rstrip('\n')
   LineElements = line.split('=')
if LineElements[0] == 'Attribute1 ':
Attribute1=LineElements[1]
if LineElements[0] == 'Attribute3 ':
Attribute3=LineElements[1]
   print("%s | %s\n" % (Attribute1, Attribute3))

Is there a library or example I could be looking at for this?  I use lxml
for xml, but I don't think it will work for this - at least the way I tried
did not.

Thank you,
Marc

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


[Tutor] Parsing multiple lines from text file using regex

2013-10-27 Thread Marc
Hi,
I am having an issue with something that would seem have an easy solution,
which escapes me.  I have configuration files that I would like to parse.
The data I am having issue with is a multi-line attribute that has the
following structure:

banner  
Banner text
Banner text
Banner text
...


The regex 'banner\s+(\w+)\s+(.+)' captures the command nicely and
banner.group(2) captures the delimiter nicely.

My issue is that I need to capture the lines between the delimiters (both
delimiters are the same).

I have tried various permutations of 

Delimiter=banner.group(2)
re.findall(Delimiter'(.*?)'Delimiter, line, re.DOTALL|re.MULTILINE)

with no luck

Examples I have found online all assume that the starting and ending
delimiters are different and are defined directly in re.findall().  I would
like to use the original regex extracting the banner.group(2), since it is
already done.  

Any help in pointing me in the right direction would be most appreciated.

Thank you,

Marc

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


[Tutor] check_range

2004-12-14 Thread Marc Gartler
Hi all,
I am fairly new to both Python & programming, and am attempting to 
create a function that will test whether some user input is an integer 
between 10 and 89, but the check isn't happening...

def check_range(myrange):
if range(myrange) != range(10,89):
return "False"
else:
return "True"
...this gets called later via:
if check_range(input):
done = "True"
return int(input)
What am I doing wrong?
Thanks!
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] User selection as both string and int

2004-12-14 Thread Marc Gartler
I am trying to have a user select from amongst a list of items, and 
then make use of that choice later on as both a string (e.g. "you chose 
_").  My function currently allows for a numerical choice, but I am 
not sure how to return it as the item (e.g. apple) rather than the 
integer corresponding to the position in the list:

def get_material(mylist):
mycount = 1
for item in mylist:
print mycount, item
mycount = mycount + 1
material = raw_input("Please select material:")
myposition = int(material) - 1
return myposition
fruit_list = ['apple', 'orange', 'banana']
fruit = get_material(fruit_list)
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] User selection as both string and int

2004-12-14 Thread Marc Gartler
Better still.  Thanks Brian.
On Tuesday, December 14, 2004, at 09:44  PM, Brian van den Broek wrote:
Marc Gartler said unto the world upon 2004-12-14 22:13:
I am trying to have a user select from amongst a list of items, and 
then make use of that choice later on as both a string (e.g. "you 
chose _").  My function currently allows for a numerical choice, 
but I am not sure how to return it as the item (e.g. apple) rather 
than the integer corresponding to the position in the list:
def get_material(mylist):
mycount = 1
for item in mylist:
print mycount, item
mycount = mycount + 1
material = raw_input("Please select material:")
myposition = int(material) - 1
return myposition
fruit_list = ['apple', 'orange', 'banana']
fruit = get_material(fruit_list)
Hi Marc,
Since fruit_list is a list, you can 'fetch' an element out of it like 
so:
fruit_list[index]
where index is an integer.

Your function returns an integer. So, for the minimal change to get 
what you want done, try replacing your last line with these two:
fruit = fruit_list[get_material(fruit_list)]
print fruit

Best,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] User selection as both string and int

2004-12-14 Thread Marc Gartler
Thanks.  That was pretty basic...
On Tuesday, December 14, 2004, at 09:18  PM, Loptr Chaote wrote:
On Tue, 14 Dec 2004 21:13:00 -0600, Marc Gartler
<[EMAIL PROTECTED]> wrote:
I am trying to have a user select from amongst a list of items, and
then make use of that choice later on as both a string (e.g. "you 
chose
_").  My function currently allows for a numerical choice, but I 
am
not sure how to return it as the item (e.g. apple) rather than the
integer corresponding to the position in the list:

It looks like all you need is a
  print 'You selected: ', fruit_list[fruit]
after the get_material() call.
This accesses the position >fruit< (i.e. the value in fruit) in the
array fruit_list.
Try
  print fruit_list[0], fruit_list[1], fruit_list[2]
and you'll understand how it works.
-L.C
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] AttributeError: instance has no __call__ method

2004-12-15 Thread Marc Gartler
Hi everybody,
Prior to this chunk of code 'glass' has been chosen from a list of 
colors via user input, and I now want to have that choice connect to 
one of several possible classes:

def glass_type(glasstype):
if glasstype == 'Red':
myglass = RedGlassCost()
elif glasstype == 'Blue':
myglass = BlueGlassCost()
elif glasstype == 'Yellow':
myglass = YellowGlassCost()
return myglass
glasschoice = glass_type(glass)
myglass = glasschoice()
I've tried various approaches and keep getting different errors.  But 
this one seems closest to my goal, as I know it is at least passing 
'glass' into the function:

AttributeError: RedGlassCost instance has no __call__ method
What is this trying to tell me?  Or is that irrelevant as I would be 
better off trying some other approach altogether?

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


Re: [Tutor] AttributeError: instance has no __call__ method

2004-12-15 Thread Marc Gartler
# --superclass--
class FrameCost:
	def __init__(self):
		self.width = int(0)
		self.length = int(0)
# Calculate cost per square foot
	def Cost_per_sqft(self, cost):
		return (((self.width) * (self.length) / 144.00) * (cost))
# Calculate cost per linear foot
	def Cost_per_ft(self, cost):
		return (self.width) * 2.00) + ((self.length) * 2.00)) / 12.00) * 
(cost))
	def Width(self, argt):
		self.width = argt
	def Length(self, argt):
		self.length = argt

# --Three subclasses for glass --

class RegGlassCost(FrameCost):
def Cost(self):
self.cost = 3   # Define costs in dollars
return (self.Cost_per_sqft(self.cost))

class BlueGlassCost(FrameCost):
def Cost(self):
self.cost = 4
return (self.Cost_per_sqft(self.cost))

class YellowGlassCost(FrameCost):
def Cost(self):
self.cost = 5
return (self.Cost_per_sqft(self.cost))

# -- Another Subclass for Labor --
class LaborCost(FrameCost):
def Cost(self):
self.cost = 5.25
return (self.Cost_per_sqft(self.cost))
On Wednesday, December 15, 2004, at 09:20  PM, Max Noel wrote:
	Can we see your code for the *GlassCost classes?
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AttributeError: instance has no __call__ method

2004-12-15 Thread Marc Gartler
That did it.  Thanks, Max.
On Wednesday, December 15, 2004, at 09:28  PM, Max Noel wrote:
On Dec 16, 2004, at 04:20, Max Noel wrote:
def glass_type(glasstype):
if glasstype == 'Red':
myglass = RedGlassCost()
elif glasstype == 'Blue':
myglass = BlueGlassCost()
elif glasstype == 'Yellow':
myglass = YellowGlassCost()
return myglass
glasschoice = glass_type(glass)
myglass = glasschoice()
	Can we see your code for the *GlassCost classes?
	Nevermind, I just figured out the problem. RedGlassCost() returns an 
instance of the RedGlassCost class, whereas RedGlassCost is the class 
itself. Thus, you need to remove the parentheses either in the 
def_glasstype function (you then return a class, affect it to 
glasschoice and then create an instance of it by instanciating 
glasschoice) or in your last line (glass_type returns an instance of 
the class you want).

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


Re: [Tutor] check_range

2004-12-14 Thread Marc Gartler
Thanks all, that was very helpful!
On Tuesday, December 14, 2004, at 06:39  PM, Brian van den Broek wrote:
Marc Gartler said unto the world upon 2004-12-14 18:12:
Hi all,
I am fairly new to both Python & programming, and am attempting to 
create a function that will test whether some user input is an 
integer between 10 and 89, but the check isn't happening...
def check_range(myrange):
if range(myrange) != range(10,89):
return "False"
else:
return "True"
...this gets called later via:
if check_range(input):
done = "True"
return int(input)
What am I doing wrong?
Thanks!
Hi Marc,
Welcome to Python and the list. :-)
Others have pointed out how to solve your immediate problem with in or 
a comparison, and that you can just return True and False unquoted. 
(They are special builtin objects, so making strings for them isn't 
needed.)

A minor correction to Kent's suggestion, though. He suggested to use
10 < x < 90, but since I gather you want 10 to return True, you need
9 < x < 90:
>>> 10 < 10 < 90
False
>>> 9 < 10 < 90
True
This sort of thing is an "off by 1 error" and will happen to you all 
the time :-(

I have a some style suggestions for you, too.
Try it this way:
>>> def check_in_range(value):
in_range = False
if 9 < value < 90:
in_range = True
return in_range
>>> check_in_range(35)
True
This way, by setting a name to point to False, and over-riding that 
when the test is met, there is only a single return statement. That is 
often considered a good thing. This function is too small for it to 
matter lots, but have multiple returns can make the debugging a bit 
harder.

Another tip is that for debugging such things it often helps to use 
print statements when things don't go as expected. If you'd added them 
to your original function like so:

>>> def check_range(myrange):
print range(myrange)
print range(2,5)
if range(myrange) != range(2,5):
return "False"
else:
return "True"

>>> check_range(3)
[0, 1, 2]
[2, 3, 4]
'False'
The problem would have likely been much more clear.
HTH,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numpy unexpected result: subtraction of cell values

2010-01-11 Thread Marc Tompkins
On Mon, Jan 11, 2010 at 10:20 AM, Carnell, James E <
jecarn...@saintfrancis.com> wrote:

>
> I'm sure this is easy, but I am having a difficult time finding the right
> search terms to find it on the Internet. Any help much appreciated.
>
> 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array using
> 'asarray' function.
>
> I want to subtract the Red Value in an array cell from a neighboring Red
> Value cell.
>
> >>> pictArray[39][4]#pixel at 39 4
> array([150, 140, 120], dtype=unint8)
>
> >>> pictArray[39][5]#pixel at 39 5
> array([160, 150, 120], dtype=unint8)
>
> >>> pictArray[39][4][0] #red pixel
> 150
>
> >>> pictArray[39][5[0]  #neighboring red pixel
> 160
>
> >>> pictArray[39][4] - pictArray[39][5] )
> 246  # <---  ???  vs -10
>
> How do I get the number -10? Does this have to do with the dtype?
>

It looks like you're re-typing from your terminal window into your Compose
window... your life (and ours!) will be simpler if you just cut and paste.
There are a couple of weirdnesses in what you posted - unmatched parentheses
and such - that are probably just typos.

Anyway, assuming that what you've posted IS the same as what you're trying
to do, in your last line you're trying to subtract one entire cell from
another (instead of just the red value of one from the red value of the
other.)  I don't know where the number 246 came from, but I'm not really
sure what number I would have expected anyway (matrix algebra was a LONG
time ago, I'm afraid!)

I think what you want to do is
>>> pictArray[39][4][0] - pictArray[39][5][0]

I'm not in a place where I can test, but I think that should do it.

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


Re: [Tutor] Numpy unexpected result: subtraction of cell values

2010-01-11 Thread Marc Tompkins
On Mon, Jan 11, 2010 at 11:02 AM, Carnell, James E <
jecarn...@saintfrancis.com> wrote:

>
> >
> > I'm sure this is easy, but I am having a difficult time finding the
> > right search terms to find it on the Internet. Any help much
> > appreciated.
> >
> > 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array
> > using 'asarray' function.
> >
> > I want to subtract the Red Value in an array cell from a neighboring
> > Red Value cell.
> >
> > >>> pictArray[39][4]#pixel at 39 4
> > array([150, 140, 120], dtype=unint8)
> >
> > >>> pictArray[39][5]#pixel at 39 5
> > array([160, 150, 120], dtype=unint8)
> >
> > >>> pictArray[39][4][0] #red pixel
> > 150
> >
> > >>> pictArray[39][5[0]  #neighboring red pixel
> > 160
> >
> > >>> pictArray[39][4][0] - pictArray[39][5][0]
> > 246  # <---  ???  vs -10
> >
> > How do I get the number -10? Does this have to do with the dtype?
> >
>
> It looks like you're re-typing from your terminal window into your Compose
> window... your life (and ours!) will be simpler if you just cut and paste.
>
> - sorry I am at work and due to security reasons can't plug a
> thumb drive in for copying copde from my laptop. I have corrected the values
> above.
>
> - pictArray[39][4][0] - pictArray[39][5][0] = 246  is where I am
> getting stuck
>
>
> Silly of me not to have noticed, but those are UNsigned 8-bit integers,
which means values 0-255.  -10 wraps around to 246.



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


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


Re: [Tutor] Guess my number? Guess what's wrong!

2010-04-17 Thread Marc Tompkins
On Sat, Apr 17, 2010 at 1:04 PM, Matthew Carpenter-Arevalo <
matthew.carpenter.arev...@googlemail.com> wrote:

> Hi Everyone,
>
> I'm a beginner python programmer, and I've been working on
> the perennial 'guess my number' example.
>
> When I run this in my module, I get an infinite loop of 'higher' or
> 'lower.' Can anyone see where I'm going wrong herE?
>
> I think you just have an indentation problem.  Take a look at your loop.




> Thanks,
>
> MCA
>
>
> # Guess my number
>
> # the computer picks a random number between 1 and 100
> # the player tries to guess it and the computer lets
> # the player know if the guess is too high, too low
> # or right on the money
>
> print "\tWelcome to 'Guess my number'!"
> print "\nI'm think of a number between 1 and 100."
> print "Try to guess it in as few attempts as possible. \n"
>
> # set the initial values
> # the number - represents the number the player has to guess
> # raw_input = the player's first guess & converts it into an integer.
> # tries = # of guesses so far.
>
> import random
>
> the_number = random.randrange(100) + 1
> guess = int(raw_input("Take a guess: "))
> tries = 1
>
> # guessing loop
> while (guess != the_number):
> if (guess > the_number):
> print "lower..."
> else:
> print "Higher..."
>
> guess = int(raw_input("Take a guess: "))
> tries += 1
>
> print "You guessed it! The number was", the_number
> print "and it only took you", tries, "tries!\n"
>
> raw_input("\n\nPress the enter key to exit.")
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Boa Constructor list control

2010-04-29 Thread Marc Tompkins
On Thu, Apr 29, 2010 at 11:07 PM, Ray Parrish  wrote:

> OK, I've discovered the collection editor, and now know how to use it, but
> when I click the new button in the collection editor for a list control, it
> pops up an error message stating that the list needs to be created with the
> wx.LC_REPORT flag, and I have no idea how to accomplish that.
>
> Could someone please enlighten me?
>
> Ray --

I hate to say it ('cause I always hate it when I get an answer like this
myself), but you're asking on the wrong list: this isn't exactly a Python
question, it's either a BoaConstructor or a wxPython question.

Python itself is not a graphics language, but you can integrate various
graphics packages with Python to write GUI programs.  (One package, called
tkInter, ships with Python.)  WX is a popular cross-platform graphics
package written in C; wxPython is the Python translation/wrapping of wx.
Boa Constructor, in turn, is a rapid development tool for automatically
generating wxPython code.

The message you're reporting might be a bug in BoaConstructor (not too
likely), or a problem with how BoaConstructor is installed on your machine,
or...

Anyway, the first place I'd try would be the wxpython-users mailing list:
wxpython-us...@lists.wxwidgets.org
http://lists.wxwidgets.org/mailman/listinfo/wxpython-users

I use wxPython myself, and I do know how to create a list with the
wx.LC_REPORT flag, but I don't think that's actually going to help you right
now - you need to talk to somebody who uses BoaConstructor.  (I'm an SPE man
myself.)

Hope that helps -

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


Re: [Tutor] OT: need computer advice from wise Tutors

2010-06-26 Thread Marc Tompkins
On Sat, Jun 26, 2010 at 2:30 PM, Richard D. Moores wrote:

> On Sat, Jun 26, 2010 at 13:39, Sithembewena Lloyd Dube
>  wrote:
> > Hi Dick,
> >
> > In that case, perhaps you could externally back up all your important
> stuff
> > and then format your hard disk. That way, any drivers etc intended for
> > Windows Vista will be wiped off, and you can then perform a clean
> > installation from your disk. Now, as far as upgrade disks go, I do not
> know
> > whether it will work as a "clean installation" disk, or whether it is
> only
> > meant for use on an existing windows installation (hence the name
> > "upgrade"). You might want to check that out first.
>
> I don't believe the disk I have will enable a clean installation.
>
I'm pretty sure it will:
http://www.winsupersite.com/win7/clean_install_upgrade_media.asp
http://www.mydigitallife.info/2009/10/27/clean-install-windows-7-with-upgrade-media-and-product-key-on-formatted-or-empty-blank-hard-drive/

The upshot of both those articles is: boot from the upgrade disk as if it
were a normal Full Install disk; when it asks for the Windows key, leave it
blank.  Don't enter the key until after the installation is complete, when
you want to activate.

Since you CAN use that disk as a clean install, I definitely recommend that
you DO.  When I upgraded my laptop to Windows 7, I bought myself a new 500GB
hard drive for the purpose.  $60 and five minutes with a small screwdriver
brought me a huge dividend in peace of mind.

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


Re: [Tutor] OT: need computer advice from wise Tutors

2010-06-27 Thread Marc Tompkins
On Sat, Jun 26, 2010 at 4:46 PM, Steven D'Aprano wrote:

> Apart from:
>
 The OP was asking about upgrading from Vista to 7, so let me answer your
objections here...

 having no default email client (what sort of two-bit operating system
> doesn't have an email client in 2010?);
>
Jesus, you _miss_ Outlook Express?  Seriously:  the new default is webmail.
Like it, don't like it, but it's really not as if you can't get your mail.


> the automatic upgrades that run silently in the background with no easy
> way to turn them on or off

Just like XP and Vista, you're asked during installation whether you want to
allow or disallow automatic updates.  If you breeze past that question, then
- just like in XP and Vista - you can right-click on the little icon that
appears in your system tray (oops, I mean "notification area.")  True,
Windows 7 is proactive about hiding stuff in the tray... but it does still
appear there.

A more legitimate gripe is that, after downloading those updates, Windows
insists on applying them when you shut down the computer.  If you're in a
hurry, that can be a PITA.


> (always fun when your Internet download cap
> is completely used up TWO DAYS into the month -- especially when you
> don't know because you can't read the email from your ISP due to not
> having an email client,

To paraphrase, "what sort of two-bit ISP doesn't have a webmail site in
2010?"

the gratuitous UI changes (am I missing something, or does Internet
> Explorer no longer have a menubar?);
>
That's IE, not Windows.  Windows 7 comes with IE 8; Vista came with IE 7; XP
came with IE 6.  I don't care for the look myself, but then I never use IE
if I can avoid it (Firefox for mail and searching, 'cause I love me some
plugins; Chrome for everything else, 'cause it's fast as hell.  IE when I'm
on a client machine and there's nothing better.)  IE 8 is being rolled out
to all versions of Windows in any case, so that's not a reason not to
upgrade - unless you were planning to turn off Windows Update in Vista,
which is a bad idea for security reasons...

the use of third-party applications like Adobe Acrobat Reader which have
> become overloaded with *stupid* security vulnerabilities *by design*
> (years after Microsoft themselves got burnt, time and time again, by
> allowing the web-browser and mail client to execute random code found
> on the internet, somebody at Adobe apparently thought it would be a
> good idea for the PDF reader to do the same thing *facepalms*); and
>
Microsoft doesn't provide a PDF reader of its own - I'm not sure, but I
suspect that's for legal reasons - so whatever PDF reader you use, it HAS to
be third-party.  Why Adobe?  Probably because it's called "_Adobe_ Acrobat?"

Now, I hate Adobe products for the same reasons you mentioned, so I use and
recommend the free Foxit Reader (www.foxitsoftware.com).  But that was the
same under XP and Vista.


> consequently the proliferation of adware and spyware (even
> the "legitimate" anti-malware companies fill your browser with ad-laden
> toolbars and try terrifying the user with "your computer is
> unprotected" warnings -- no wonder the average user can't tell the
> difference between legitimate anti-malware and trojan horses).
>

 Again, not new in 7 - and, as a matter of fact, possibly somewhat better
than in Vista.


> On the other hand, it is quite pretty.
>
Screw pretty.  Pretty don't pay the rent.  First thing I do on any machine I
get my hands on is turn off the $%^&* Aero Glass - why would I take that
kind of performance hit for the dubious pleasure of a translucent titlebar?
But guess what?  MS introduced that piece of idiotism in - wait for it -
Vista.

My reasons FOR upgrading:

- Better UAC.  UAC is never going to feel natural to users (like me - I
freely admit it) who came up from DOS, and are stuck in a single-user
mindset.  Users raised on *nixes, on the other hand, find UAC to be a
laughable baby step on the way to a real least-privilege security model.
That said, 7 does a much more natural job (than Vista) of asking for
elevation only when needed, and staying out of the way most of the rest of
the time.

- Faster sleep/hibernation and wakeup.  I have no idea what they did under
the covers, but on my laptop under Vista 64-bit, it took a minute or so to
hibernate, and 30 seconds or so to wake up.  7 takes 30 seconds or so to
hibernate, and 15 seconds to wake up.  Not astronomical, but coupled with
the next point, it's HUGE.

- Better wireless networking.  Coming out of sleep or hibernation, it used
to take up to a minute and a half to connect to a known wireless network (in
other words, a network I'd previously connected to and saved settings for.)
Now, I'm generally connected even before I can see the desktop - 3 to 5
seconds, maybe.  I carry my laptop everywhere, and connect to wireless
networks at my clients (and Starbucks!) all day long, so this is a MAJOR
deal for me.

- Seriously improved multi-monitor support.  I've loved using dual m

Re: [Tutor] OT: need computer advice from wise Tutors

2010-06-27 Thread Marc Tompkins
On Sun, Jun 27, 2010 at 7:41 AM, Alan Gauld wrote:

> "Marc Tompkins"  wrote
>
>  having no default email client (what sort of two-bit operating system
>>
>>> doesn't have an email client in 2010?);
>>>
>>>  Jesus, you _miss_ Outlook Express?  Seriously:  the new default is
>> webmail.
>> Like it, don't like it, but it's really not as if you can't get your mail.
>>
>
> I will miss OE. I actually quite like it, its simple but has all the bits
> I need for both email and newrgroups. I tried thunderbird and use it
> on my Linux box but on windows I usually revert to OE.
>
I always hated OE, but I suppose it does have its uses. Backing up OE was
always problematic...



> And its lots better than webmail which is only useful for occasional
> browsing. But I get around 200 plus emails a day (and sometimes the
> same again in news messages) and trying to manage that on webmail
> is a nightmare - and you can't read it while offline. I really need an
> offline mail client.

As Richard mentioned and I will second, GMail handles that volume easily;
Gears enables offline reading, and if you've drunk the Kool-Aid like I have,
integration with Android is seamless.  Also it's instantly portable from
machine to machine.

In any case, I only meant to whole-heartedly endorse upgrading from Vista to
7, and dismiss the loss of OE as a reason not to.  Embracing the GMail way
appears to be another one of those dreaded religious topics - I certainly
can feel myself morphing into a ranting fanatic...


>  Just like XP and Vista, you're asked during installation whether you want
>> to
>> allow or disallow automatic updates.  If you breeze past that question,
>> then
>> - just like in XP and Vista - you can right-click on the little icon that
>> appears in your system tray (oops, I mean "notification area.")
>>
>
> OOh. I've never noticed the icon - what does it look like? I didn't
> do the install so had no say in the decision for work, but for my
> home PC I'd much rather decide if/when I do "upgrades" - I've had
> too mamy Windows upgrades kill my PC to the point of needing
> rebuiilds!

It looks like a rectangular pane of glass (a Window, maybe?) with an orange
halo orbiting it.  I don't see it on my machine at the moment (because I -
wait for it - turned off automatic updates when I installed), so I'm a
little fuzzy on whether it's a left-click, double-click, or right-click that
gets you the option to turn off the auto updates.
Regardless, here's a more direct way:
   Control Panel\System and Security\Windows Update\Change settings


 - Better wireless networking.  Coming out of sleep or hibernation, it used
> to take up to a minute and a half to connect to a known wireless network
>

I'll need to check that - I've just gotten used to going for a coffee when I
> boot up - it usually takes me around 5 minutes for everything to get
> started so I've never noticed the WiFi changes.


I was driving on the freeway a while back, talking to my sister on the phone
(hands-free!) when she mentioned that her computer was giving her trouble.
I exited and pulled into a Starbucks I'd used before (so my machine already
knew "attwifi7" or whatever it is).  I opened my laptop, signed in, and used
Chrome to sign into the AT&T captive portal; within less than a minute of my
butt hitting the banquette I was in Copilot.  She and I commiserated about
the good old days when at least I could have ordered my coffee before I had
to get down to work... 8-)


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


Re: [Tutor] TypeError when io.open is used

2010-06-27 Thread Marc Tompkins
On Sun, Jun 27, 2010 at 3:20 PM,  wrote:

> I have tried the following, too:
>
> from pg8000 import DBAPI
> import os
> import os.path
> import sys
>
> # !!! that is test data. It must be changed
> conn=DBAPI.connect(host="localhost", database="postgres", user="postgres",
> password="test")
>
> #conn.cursor will return a cursor oject, you can use this cursor to perform
> queries
> cursor = conn.cursor()
>
> file = open(
> "C:\\Blender_Library\\BlenderLib\\objectLib\\Faqns\\Osaka2\\faqns_osaka_2.jpg",
> "rb" )
> data1 = DBAPI.Binary(file.read())
> data2 = 'faqns_osaka_2'
>
> # execute our Query
> cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s",
> data1, data2)
> sys.stdout.flush()
>
> # Save (commit) the changes
> conn.commit()
>
> # We can also close the cursor if we are done with it
> cursor.close()
>
> The problem this time was:
> Traceback :
>   File "insertdb_pg8000.py", line 19, in 
>  cursor.execute("UPDATE testtable SET jpeg = %s WHERE testtable_n =
> %s", data1, data2)
>   File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn
> TypeError: execute() takes at most 3 arguments (4 given)
>
>
I don't have any insight into your other piece of code, but here I think you
just need another set of parentheses - so that the string interpolation is
done first, and the result of it becomes the argument to cursor.execute().
I can't really test it at the moment, but try changing it to:
cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s",
data1, data2) )

Either that, or break it into two lines:

myQuery = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1,
data2
cursor.execute(myQuery)

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


Re: [Tutor] TypeError when io.open is used

2010-06-27 Thread Marc Tompkins
On Sun, Jun 27, 2010 at 5:13 PM,  wrote:

> On Sun, 27 Jun 2010 15:56:23 -0700
>  Marc Tompkins  wrote:
>
>> On Sun, Jun 27, 2010 at 3:20 PM,  wrote:
>>
>> I don't have any insight into your other piece of code, but here I think
>> you
>> just need another set of parentheses - so that the string interpolation is
>> done first, and the result of it becomes the argument to cursor.execute().
>> I can't really test it at the moment, but try changing it to:
>> cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n = %s",
>> data1, data2) )
>>
>> Either that, or break it into two lines:
>>
>> myQuery = "UPDATE testtable SET jpeg = %s WHERE testtable_n = %s", data1,
>> data2
>> cursor.execute(myQuery)
>>
>> --
>> www.fsrtechnologies.com
>>
>
> Thank you for the suggestion that i should enforce the parantheses. At
> least that changed the error. Unfortunately that is wierd one, too:
>
> Traceback :
>   File "insertdb_pg8000.py", line 20, in 
>
>  cursor.execute( ("UPDATE testtable SET jpeg = %s WHERE testtable_n =
> %s", data1, data2) )
>   File "build\bdist.win32\egg\pg8000\dbapi.py", line 243, in _fn
>   File "build\bdist.win32\egg\pg8000\dbapi.py", line 314, in execute
>   File "build\bdist.win32\egg\pg8000\dbapi.py", line 319, in _execute
>   File "build\bdist.win32\egg\pg8000\interface.py", line 303, in execute
>   File "build\bdist.win32\egg\pg8000\interface.py", line 108, in _init_
>   File "build\bdist.win32\egg\pg8000\protocol.py", line 913, in _fn
>   File "build\bdist.win32\egg\pg8000\protocol.py", line 1048, in parse
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 49:
> ordinal not in range()
>
> I mean, as far as i know, for binary files i do not need to set encoding
> when i open them.
>

OK - when I answered before, I was only looking at the error message and the
actual line of code that generated it; I hadn't really looked at what you're
trying to do.

Now that I've stepped back a bit, here's what I think you're trying to
achieve:
- open the file "faqns_osaka_2.jpg"
- read its contents
- write the contents to a BLOB field (or whatever the Postgres equivalent is
- anyway, a field that can hold an arbitrary chunk of data)
- write the name 'faqns_osaka_2' to a label field.

Unfortunately, you're trying to build the SQL command to do that using
string interpolation (the %s notation.)  So your program gets as far as
reading the contents of the file, and then tries to decode them into a
string  - and that's why you get this error.  Be happy you got the error -
if it had succeeded, the resulting binary data would have been unreadable as
an image, and you wouldn't have known why.

I'm certain that there are proper ways to pass chunks of binary data for
insertion into BLOB fields - people must do this every day - but I don't
actually know them.

Here's a possibility:
http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-7-sect-11.html

Or try searching for "python postgres blob".



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


Re: [Tutor] Problems installing

2010-06-29 Thread Marc Tompkins
On Tue, Jun 29, 2010 at 10:35 PM, Andrew Martin wrote:

> I just downloaded Python 2.6.5 onto my windows vista laptop. I am
> attempting to install "escript version 3: Solution of Partial Differential
> Equations (PDE) using Finite Elements (FEM)." I downloaded the files and
> manually placed them in their appropriately place on my computer according
> to the ReadMe file. However, when I try to import escript, I get an error:
>
> >>> import esys.escript
>
> Traceback (most recent call last):
>   File "", line 1, in 
> import esys.escript
> ImportError: Bad magic number in
> C:\Python26\lib\site-packages\esys\escript\__init__.pyc
> >>>
>
> Can anybody lend me a hand?
>
> I don't know anything about escript, I'm afraid, but try this  - .pyc files
are always replaceable, as long as the .py or .pyw files they correspond to
still exist.  So delete __init__.pyc (I'm assuming that there's also a
__init__.py file) and try again.

Of course, this is only a solution if the problem is a corrupt .pyc file,
which I've run into on a couple of occasions.  If it's something else...

Hope that helps.

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


Re: [Tutor] Difficulty Understanding Example Code for Blender Script

2010-07-21 Thread Marc Tompkins
On Wed, Jul 21, 2010 at 9:48 PM, Andrew Martin wrote:

> This code was part of a Blender script to build a 3d bar graph, so I don't
> know if understanding Blender is a prereq for understanding this code. The
> function is for the axis labels.
>
> def label(text,position,orientation='z'):
> txt=Text3d.New('label')
> txt.setText(text)
> ob=Scene.GetCurrent().objects.new(txt)
> ob.setLocation(*position)
> if orientation=='x':
> ob.setEuler(-pi/2.0,0,0)
> elif orientation=='z':
> ob.setEuler(0,0,pi/2.0)
> print 'label %s at %s along %s' %(text,position,orientation)
>
>  I understand it for the most part except for the orientation part. I
> assume orientation is for the 3d text object, but how is it determined
> whether it is x or z?


I don't use Blender myself, so this will be a more generic, high-level
answer...

> def label(text,position,orientation='z'):
>
This definition specifies that label() takes two mandatory parameters - text
and position - and one optional parameter, orientation.  What makes
"orientation" optional is the fact that a default value is supplied:
"orientation='z'".  In other words, "orientation" is equal to "z" unless you
specify otherwise in your call to label().

Take a look at this section of the Python docs:
http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions

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


Re: [Tutor] Databases in Python

2010-08-24 Thread Marc Tompkins
On Tue, Aug 24, 2010 at 12:44 PM, aug dawg  wrote:

>  if searcher in database:
>> # Figure this out.
>>
>> You need some sort of actual Python statement there as a placeholder -
even just "print()".

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


Re: [Tutor] Newbie - regex question

2010-08-30 Thread Marc Tompkins
On Mon, Aug 30, 2010 at 2:56 PM, Hugo Arts  wrote:

> To solve, we have the non-greedy patterns. They eat not as much
> possible, but as little as possible. To make a qualifier non-greedy,
> simply add an asterix at its end:
>
> r'WORD1-.*?'
>
> I would also like to offer one small correction: an asterisk may be greedy,
but Asterix is a cheerful, brave Gaul.


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


Re: [Tutor] a logic problem in an if statement

2010-09-26 Thread Marc Tompkins
On Sun, Sep 26, 2010 at 1:01 PM, Bill Allen  wrote:

>
> Any thoughts how I am going wrong here?
>
> Looks like you've got two different names for the first mouse click...

mouse_pos1 = mouse_pos
>

but

> if mouse_pos[1] < height/2 and mouse_pos2[1] > height/2:
>


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


Re: [Tutor] a logic problem in an if statement

2010-09-26 Thread Marc Tompkins
On Sun, Sep 26, 2010 at 1:36 PM, Bill Allen  wrote:

> I hate it when I do something like that!A combination of poor choice of
> names for the variables and programming tunnel vision
>

Been there, done that!
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issues In Terminal

2010-09-26 Thread Marc Tompkins
On Sun, Sep 26, 2010 at 2:55 PM, Bill DeBroglie wrote:

> Which is great, but when I try and run the same code in the Terminal by
> calling a program I've written (print("hello world") again) I get the
> following:
>
>matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
>./chapter_2.py: line 4: syntax error near unexpected token `"Hello
> World"'
>./chapter_2.py: line 4: `print("Hello World")'
>
> I'm using a Mac OS X 10.5.8. I had previously downloaded Python 2.6.5 AND
> 3.1 and had them both on this computer simultaneously but was having trouble
> with 3.1 crashing. I have since put both in the trash but obviously still
> have 2.6.5 on my system, I assume that was the version pre-installed on this
> Mac.
>


I think that's a shell issue, not specifically a Python issue.  You need to
include a line at the top of the script to tell the OS how to find the
Python interpreter.  Try adding this line at the beginning:

> #!/usr/bin/env python
>
> Your default Python install probably is NOT installed at /usr/bin/python,
but there should be a symbolic link there that points to the actual
location.  If not, you'll need to adjust things a bit.

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


Re: [Tutor] Issues In Terminal

2010-09-26 Thread Marc Tompkins
On Sun, Sep 26, 2010 at 3:04 PM, David Hutto  wrote:

> > Pretty sure it's the parentheses, but I'm not an expert. In python 3 you
> use
> > print(), in 2.6 you either use import from __futur__ or print "string
> here".
>
> I mean __future__ .
>

The parentheses are optional in 2.6, mandatory in 3.  In 2.6, print and
print() are alternate ways to invoke the print statement; in 3 the print
statement has been replaced by the print() function.  If you want to use the
function instead of the statement, you must do this:

from __future__ import print_function

 but I'm pretty sure that's not the OP's issue.


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


Re: [Tutor] Issues In Terminal

2010-09-26 Thread Marc Tompkins
On Sun, Sep 26, 2010 at 3:24 PM, Bill DeBroglie wrote:

>
> Is this what you mean?
>
> matthew-parrillas-macbook:Dawson_Book matthewparrilla$ #!/usr/bin/env
> python
> matthew-parrillas-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
> ./chapter_2.py: line 1: syntax error near unexpected token `"Hello World"'
> ./chapter_2.py: line 1: `print("Hello World")'
>
> If so, obviously still no dice.
>
> No, I meant that you should edit your .py file and add

> #!/usr/bin/env python
>
as the first line, THEN try to run it.

Right now what's happening is that you're handing a line of Python script to
the shell and asking it to run it; the shell is telling you (oh-so-politely)
"what the hell is this?"  You need to give it a clue.

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


Re: [Tutor] IDEs

2010-11-22 Thread Marc Tompkins
On Mon, Nov 22, 2010 at 1:13 AM, Josep M. Fontana  wrote:

> Alan gave me this piece of advice in his response to another message I
> sent to the list. Since the topic is a bit different from the one in
> the original message, I think it is better to start a different
> thread.
>
> > Don;t run your code inside the IDE except for testing. IDEs are
> > Development Environments, they are not ideal for executing production
> > code. Run your file from the Terminal command prompt directly.
>
>
The issue is that phrase "production code".  If you're just noodling around,
"production" can mean printing "Hello World."  If, on the other hand, you're
writing Python code to solve real-world problems and the end goal is for
users to install and run your applications on their own machines... then
testing/running inside the IDE is an issue, because the environment is so
different from anything you'll find "in the wild."
The most egregious case is trying to run GUI code from inside of IDLE (the
basic IDE that ships with Python.)  Nothing works properly, and IDLE
introduces all sorts of weirdness, but people keep doing it.

Testing outside the IDE doesn't have to be a big deal.  You don't have to
type "$python filename.py" every time; you could keep a terminal window open
so you can just up-arrow through the command history, or (what I usually do)
create a shortcut to my file on the desktop.  Just make sure you've saved
your changes - you generally don't have to close the IDE.

> I thought the code was not run inside the IDE but it was run by Python
> independently, that is, the IDE just provides an interface.
>

The IDE spawns an instance of Python as a child process; it inherits the
IDE's environment.  That can lead to surprising behavior if you don't know
what's been set in the IDE'S environment.

b) with the terminal I don't get the debugging benefits that an IDE
> provides (I must say though that I still haven't really taken
> advantage of the benefits that Eclipse provides since the code I'm
> writing so far is pretty simple).
>

Nobody is saying that you shouldn't debug in the IDE!  Just that the IDE is
not the best place to run finished code, nor is IDE-based debugging the last
step in testing code that's intended to run on other people's machines.

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


Re: [Tutor] Copy file function works, but not with adding the date copied

2009-02-13 Thread Marc Tompkins
On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote:

>
>> {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440
>>
>
> The problem is that this is an RTF format which is a binary format.
> You can process binary data ion Python (see the box on the files
> topic page) but it is much more difficult that normal plain text files.
>

I'd like to correct a misapprehension here: RTF files are not a "binary
format" in the usual sense of that phrase - there are no non-ASCII
characters, newlines are handled normally, etc.  They're text files, but
with lots of funky formatting codes included - which are themselves all
text.  They're a lot like badly-formatted, insanely complicated XML,
actually.

They're full of gibberish-looking strings like the above, and the nesting of
curly braces can run to dozens of layers deep - however, if you want to get
a quick idea of what's going on in an RTF, the fastest way is to unfold it
(search-and-replace each "{" and "}" with "{\n" and "}\n" respectively) and
indent each opened curly brace.  Then if you want to give yourself a
headache, you can sit down with Microsoft's RTF specification and figure out
what all those codes do.


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


Re: [Tutor] Copy file function works, but not with adding the date copied

2009-02-13 Thread Marc Tompkins
On Fri, Feb 13, 2009 at 11:35 AM, Marc Tompkins wrote:

> On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote:
>
>>
>>> {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440
>>>
>>
Here's a quick-and-dirty way to do what (I think) you want to do:

Skip the first curly brace ("{") - find the next one.  Just before it,
insert a space + the datestamp text.  That's it.  Now if you open the RTF
file in Word, or WordPad, or whatever RTF reader you have on your system,
your text will appear (in the system-default font and style, 'cause you
inserted it before any document styles) at the top of the document.

Note: this is absolutely NOT valid RTF; it only works because Microsoft
specifically requires that RTF readers obey Posten's Law.  If you later edit
the modified file in Word, WordPad, etc. your datestamp text will be moved
to a more appropriate area of the file and you might have a hard time
finding it again.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Extract image from RTF file

2009-02-14 Thread Marc Tompkins
Forgot to Reply All.

-- Forwarded message --
From: Marc Tompkins 
Date: Sat, Feb 14, 2009 at 11:35 AM
Subject: Re: [Tutor] Extract image from RTF file
To: Bryan Fodness 


On Sat, Feb 14, 2009 at 8:40 AM, Bryan Fodness wrote:

> I have a large amount of RTF files where the only thing in them is an
> image.  I would like to extract them an save them as a png.
> Eventually, I would like to also grab some text that is on the image.
> I think PIL has something for this.
>
> Does anyone have any suggestion on how to start this?
>

I'm no kind of expert, but I do have a pointer or two...  RTF files are text
with lots and lots of funky-looking formatting, but generally not "binary"
in the sense of requiring special handling (although, now that I just read
about how pictures are stored in them, it seems there might be some
exceptions...)  There's a Python library for dealing with RTF files (
http://www.nava.de/2005/04/06/pyrtf/) but I haven't tried it; if you're
comfortable opening text files and handling their contents, it might be
simpler to roll your own for this task.

You'll want to look at the Microsoft RTF specification, the latest version
of which (1.6) is available here:

http://msdn.microsoft.com/en-us/library/aa140277(office.10).aspx<http://msdn.microsoft.com/en-us/library/aa140277%28office.10%29.aspx>

In particular, you'll be interested in the section on Pictures, which I'll
excerpt here:
Pictures

An RTF file can include pictures created with other applications. These
pictures can be in hexadecimal (the default) or binary format. Pictures are
destinations, and begin with the \*pict* control word. The *\pict* keyword
is preceded by* \*\shppict* destination control keyword as described in the
following example. A picture destination has the following syntax:
  '{' *\pict* (? & ? &  &  &
?)  '}'   |* \emfblip* |* \pngblip*
|*\jpegblip | \macpict
* | *\pmmetafile* | *\wmetafile* | *\dibitmap*  | *\wbitmap *
   *\wbmbitspixel *& *\wbmplanes* & *\wbmwidthbytes*
 (\*picw* & *\pich*) \*picwgoal*? & \*pichgoal*? *\picscalex*? & *
\picscaley*? & *\picscaled*? & *\piccropt*? & *\piccropb*? & *\piccropr*? &
*\piccropl*?   *\picbmp *& *\picbpp*   (\*bin* #BDATA) |
#SDATA


Basically, it looks like you can search for "{\pict", then search for the
closing "}".  Everything in between will be your picture, plus metadata that
tells you how to decode it.

Now that you've caught your rabbit... I'm out of advice; I've never used PIL
(though I used to listen to them all the time.)

-- 
www.fsrtechnologies.com



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


Re: [Tutor] exec "self.abc=22" ?

2009-02-16 Thread Marc Tompkins
On Mon, Feb 16, 2009 at 11:58 AM, Wayne Watson  wrote:

>  Python doesn't like the code in the Subject (unqualified exec not allowed
> in function). but easily likes self.abc="22". However, I'd like to assemble
> the assignment as a string, as shown in Subject, and execute it. Is there a
> way to do this?
> --
>
> varName = "abc"
varValue = 22
setattr(self, varName, varValue)


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


Re: [Tutor] Changing the Attribute of a Variable

2009-02-16 Thread Marc Tompkins
On Mon, Feb 16, 2009 at 8:24 PM, Wayne Watson
wrote:

>  I suspect I'm in need of setattr for this in a GUI program I'm modifying.
>
> Initally, a variable. self.stop_time is created as type datetime.time, with
> the default value 06:00:00, a time stamp, during entry into the mainloop.
> self.stop_time = datetime.time(10,10,10). The user reads his configuration
> file with the time stamp value of 08:00:00. self.time_stop becomes type
> string. He then goes to a dialog to change time stop, and it tries to access
> self.time_stop, and find is needs to have the attribute strftime, as in:
> set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S")
> When reading the configuration file, how do I make sure that self.time_stop
> is really has the strftime attribute?
>

You already received an answer to your immediate question, but I wanted to
clarify: "strftime" is NOT an attribute, it's a method.  Calling the
strftime method of a time object returns a string, formatted according to
the pattern you specify - so what you're storing as "stop_time" is not a
time, but a string.

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


Re: [Tutor] Changing the Attribute of a Variable

2009-02-17 Thread Marc Tompkins
On Tue, Feb 17, 2009 at 12:16 AM, wesley chun  wrote:

> marc: i will slightly disagree with you with regards to strftime *not*
> being an attribute. it *is* an attribute, just not a *data
> attribute*... i call it a "function attribute," but that's just
> terminology. any time you have an object x with an attribute y, the
> fact that you can issue x.y means that y is indeed an attribute of x.
> if it's a data attribute, you access it with x.y. if it's a function
> attribute, i.e., a method, you also access it with x.y, esp. if you
> want to pass the function object around, and finally, if you actually
> want to *execute* it *and* it's a method, then you add the parens,
> x.y().
>

Which follows from the fact that in Python, functions are objects too.
However, in the context of the OP's question, I think that if he referenced
strftime with no parentheses the result would NOT be what he expected or
intended; the distinction between methods and what you call "data
attributes" can be an important one.  Point taken, though.

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


Re: [Tutor] Changing the Attribute of a Variable

2009-02-17 Thread Marc Tompkins
On Tue, Feb 17, 2009 at 4:44 AM, Wayne Watson
wrote:

> Note that the diagnostic output in the image shows attributeError: 'str'
> object has no attribute 'strftime'.
>
> Let me see if I clarify what's really going on by including some of the
> code.
>

Everything in Python - both variables and code - is an object.  Objects have
attributes - data, basically - and methods - functions - associated with
them.  (As Wesley pointed out, since pieces of code are also objects,
methods are attributes too.)

However, not all objects have the same attributes or methods associated with
them!  datetime.time objects have a "strftime" method, which, when called,
returns a string representation of the time.  String objects do not have any
such method or data attribute, hence the error.

You're showing us both too much code and too little -
  print "wtw self.stop_time", self.stop_time, type(self.stop_time)
  # set in GUI as datetime.time(6,0,0)
  # HEY wtw self.stop_time.strftime("%H:%M:%S")
  set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S")
< from validate import Validator

...

> cfgFileName = os.getcwd() + os.sep + 'fsr_1500.ini'
> tmpStr = """
> npiXMLFile = string(default="npiMap.XML")
> UCFformLength = integer(min=50, max=80, default=66)
> FIformLength = integer(min=50, max=80, default=64)
> OutformLength = integer(min=50, max=80, default=64)
> IncludeLegacy = boolean(default=False)
> TopLeft = int_list(min=2, max=2)
> BottomRight = int_list(min=2, max=2)
> FIHist = string_list(default=None)
> UCFHist = string_list(default=None)
> OutHist = string_list(default=None)
> LastRunUCF = boolean(default=True)
> LastRunPrinter = boolean(default=False)
> detailLeft = integer(min=0, max=80, default=0)
> detailTo = integer(min=0, max=80, default=9)
> detailPOS = integer(min=0, max=80, default=19)
> detailCode = integer(min=0, max=80, default=25)
> detailMods = integer(min=0, max=80, default=32)
> detailDiags = integer(min=0, max=80, default=44)
> detailCharge = integer(min=0, max=80, default=49)
> detailUnits = integer(min=0, max=80, default=58)
> detailEPSDT = integer(min=0, max=80, default=62)
> detailEMG = integer(min=0, max=80, default=22)
> detailID = integer(min=0, max=80, default=67)
> bodyLeftBlock = integer(min=0, max=80, default=0)
> bodyMidBlock = integer(min=0, max=80, default=24)
> bodyRightBlock = integer(min=0, max=80, default=49)
> bodyLabelEdge = integer(min=0, max=80, default=40)
> ConfirmSuccess = boolean(default=True)
> """
> cfgSpec = StringIO.StringIO(tmpStr)
> cfgFile = ConfigObj(cfgFileName,
> configspec=cfgSpec, raise_errors=True,
> write_empty_values=True,
> create_empty=True, indent_type='', list_values=True)
> vtor = Validator()

...

> cfgFile['TopLeft'] = data.GetMarginTopLeft()  # writing a couple of
> values
> cfgFile['BottomRight'] = data.GetMarginBottomRight()
>
 ...

> test = cfgFile.validate(Global.vtor, copy=True)
> cfgFile.write()
>

Looking at that, I see a few things I want to clean up.  That's the danger
(and advantage) of exposing your own code to public scrutiny...

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


Re: [Tutor] Changing the Attribute of a Variable

2009-02-17 Thread Marc Tompkins
On Tue, Feb 17, 2009 at 11:01 AM, Wayne Watson  wrote:

>  Here's the print from the code line below.
>
> Second line from the top.
>

There it is - stop_time is a str at this point in the program, so has no
strftime attribute or method.  Step back through your code and see why...  I
find Control-F very helpful in situations like this!


>
> Regarding, ConfigObj, I was aware of it when I decided to go this route.
> That's the one that uses has an init file like Windows?  Rather than have to
> go through a learning process on it (the Win init module/object), and some
> uncertainty about it's acceptability in my situation, I thought I'd be more
> exploratory and proceed as I have. So far it has paid off in many learning
> dividends. ConfigObj, if not the Win stuff, may be attractive. Anyway, I'd
> like to proceed for the moment with this effort.
>

There's nothing sacred about the ".ini" extension - any text file that
contains "variable = value" pairs is game.  ConfigObj is not
Windows-centric.  The advantage - which is what I was trying to show when I
posted that gosh-awful hunk of code - is that you can define the format of
the file in one central section of your program - it could even be a
separate module if you wanted - and in one swell foop you tell ConfigObj the
name of the variable, its type, acceptable values or range, and a default
value in case it's missing.  Opening, reading, closing, writing, validating
- all handled.

I certainly wouldn't want to dissuade you from writing your own as a
learning exercise - I'm glad I did - but each time I need to update one of
my old programs that still uses my homegrown ConfigFile, that's the first
thing I re-factor.

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


Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Marc Tompkins
On Tue, Feb 17, 2009 at 7:09 PM, Wayne Watson
wrote:

I have a few notes, but first I just have to say: you're working very hard
to implement an ordered dictionary, and you really, really don't need to.
Python's (unordered) dictionaries work just fine for reading and writing
configurations; you just need to rethink a little.  Or, try ConfigObj, which
reads and writes your config files exactly according to your specification
with very little fuss and minimal wheel-reinvention.  'Nuff said.

Ok, let's see how this works. I've defined this function and the
> config_var_list. stop time is the last entry shown. It is part of the
> constructor for mainloop, Sentinel_GUI. and loads sdict as shown.
> def Set_ConfigDictionary():
>
> *config_var_list* = (['config_file_name',  ['Initial.sen',
> STR]],
> ['mask_file_name',  ['xyz', STR]],
> ...
> ['stop_time',  ['datetime.time(6, 0, 0)', DAT]],
> ...
> )
> # load sdict
> *sdict* = {}
> for j in range(0, len(config_var_list)):
> #print "j: ", j, "str part: ", str(config_var_list[j][0]),
> config_var_list[j][1]
> sdict[str(config_var_list[j][0])] =
> config_var_list[j][1][0]
>   ...
>

These two lines are unnecessary:
*self.sdict = sdict*
*self.config_var_list* = config_var_list
You don't need to create and load "sdict" and "config_var_list" before
assigning them to self - you could start out with
*self.sdict* = {} and *self.config_var_list* = etc.
and work from there.

  ...
> sdict and config_var_list become global to Sentinel_GUI. The first index of
> conf_var_list maintains order for sdict. That is, when I want to output the
> config file, I use to to fetch from sdict what I need, which is a value and
> the "user" type, i.e., STR, DAT, BOO, etc.
>

I don't understand the need for STR, DAT, BOO - if you're type-checking, you
don't need to create your own types to do it, and if they're informational
only, you could just give your variables descriptive names.

Relax and learn to love Python's iterators.  You don't need an index to step
through the members of a list or tuple - Python is happy to give them to you
one at a time and in order!
Instead of:
for j in range(0, len(config_var_list)):
sdict[str(config_var_list[j][0])] = config_var_list[j][1][0]
try this:
for var in config_var_list:
sdict[var[0]] = var[1][0]

Also - config_var_list is a tuple of lists.  (I'm guessing you intended to
make it a list of lists - that's what the name indicates, after all - but
putting it between "( )" makes it a tuple.)  Myself, I'd make it either a
list of dictionaries (preserves ordering), or a dictionary of dictionaries.
Here's what I'm talking about -
*config_var_list* = [{"name":"config_file_name",
"value":"Initial.sen", "type": "STR"},
{"name":"mask_file_name",  "value":"xyz", "type":"STR"},
...
{"name":"stop_time",  "value":"datetime.time(6, 0, 0)",
"type":"DAT"},
...
]
# load sdict
*sdict* = {}
for var in config_var_list:
sdict[var["name"]] = var["value"]

I just find it much, much easier to understand what's going on - with [0]
and [1][0] I had to read the code four or five times to grok it.  I haven't
benchmarked the two approaches - it's possible that access by list indices
is faster - but it's hard to overestimate the importance of clarity.

Now in SaveConfigFile, I go merrily along thusly:
>
>...
> # SAVE CONFIG FILE
> items = self.sdict.keys()
> items.sort()
> for (j, conf_entry) in enumerate(self.config_var_list):
> varName = conf_entry[0]
> varType = self.config_var_list[j][1][1]
> # Note, date-time vars are in hh:mm:ss
> varValue = eval('self.' + varName)
> var_assignment = varName + "=" + str(varValue)<<--- Beep,
> beep
> config_file.write(var_assignment + "\n")
>  ...
>

Don't work so hard!  You're using enumerate() to get both the index and the
item - but you don't need to, and it's easier to use and to read if you
don't.  In other words,
varType = self.config_var_list[j][1][1]
could be shortened to
varType = conf_entry[1][1]
You already did that for varName - just take it the rest of the way.

Next, that eval() - better this way:
varValue = getattr(self, varName)
There _are_ some valid use cases for eval() - but getting and setting
attributes ain't it.

So, taking just this section in isolation (assuming you don't implement any
of my other suggestions) -
for conf_entry in enumerate(self.con

Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson
wrote:

>  See Subject. I've run across a 58 page document
> ,
> but am uncertain of its applicability to my present needs (see my thread on
> "Changing the Attribute"). Usually, I end up with some 3-4 page document, so
> this raises an eyebrow. Am I on the right trail? In the meantime, I think
> I'll turn it into a more manageable pdf file before putting it to paper.
>

It's a very powerful module - does lots of things you don't need yet, and
maybe never will - and I agree that it could benefit from a
hit-the-ground-running guide...

Here's a quick-and-dirty; you can flesh out the details from the
documentation you downloaded.  (By the way, you'll also want to use the
validate module - another 14 pages or so...)
==
* Download configobj.py and validate.py; put them somewhere in your
Python path (or in the same folder as your project, if you want)
* Add two lines to the top of your program:
from configobj import ConfigObj
from validate import Validator
* To make working with your spec easier,
import StringIO  # allows you to work with strings as if they were
files
# You could just create a spec file, and open it normally, but this
keeps everything in one place.
* Somewhere in your program, create your spec and load it.  There are a
lot of ways you can do this - for me, the simple thing is to put it in a
class.  I create a class called Global - it's a crutch, I know...
class Global(object):
cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current
directory + "\" + filename - but you could put it anywhere and call it
anything
# create your spec as a multi-line string between triple quotes
tmpStr = """
mask_file_name = string(default=None)
gray_scale = boolean(default=True)
post_event_stack = boolean(default=False)
post_event_format = string(default="Tiff 2")
show_real_time = boolean(default=False)
hourly_rate = integer(min=0, default=0)
slowdown= integer(min=0, max=10, default=1) # I don't know what
this value is/does, so this is probably wrong
start_time = string(default="00:00:00") # or you could make the
default None?
stop_time = string(default="00:00:00")
lat = float(min=0.0, max=90.0) # I have no idea what you'd want
as a default latitude, if any...

"""
cfgSpec = StringIO.StringIO(tmpStr) # turns the above string
into a file-like object, which ConfigObj is expecting
cfgFile = ConfigObj(cfgFileName,
configspec=cfgSpec, raise_errors=True,
write_empty_values=True,
create_empty=True, indent_type='',
list_values=True) # creates the actual ConfigObj object
vtor = Validator() # creates a validator to match your config
data against your spec
* Invoke the above code when your program starts - I do it just before
my mainloop, like so:
def main(argv=None):
if argv is None:
argv = sys.argv
test = Global.cfgFile.validate(Global.vtor, copy=True) # tries
to load cfgFile; if it doesn't exist, creates it; fills in defaults for any
missing values
Global.cfgFile.write() # saves the validated file (you don't
need to do this here at the start, but I usually do)
app = MyApp(0)
app.MainLoop()
if __name__ == '__main__':
main()
* Your ConfigObj is ready to use!  Simply access the contents like a
regular dictionary.  To save back to the file, call the write() method.
Global.cfgFile['mask_file_name'] = 'bogus.txt'
Global.cfgFile.write()

maskFile = Global.cfgFile['mask_file_name']
* Or use the values directly without copying to intermediate variables:
with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile:
maskFile.write('some bogus text')
==
I'm attaching that as a text file too - I suspect that my indentation won't
survive the trip...

My Global class is an ugly hack.  I'm sure you'll come up with something
more aesthetically pleasing...
ConfigObj has lots of very cool features - sections, repeated sections,
custom input validators - that's what the 50+ pages of documentation are
about.  When you need that stuff, it's available.
-- 
www.fsrtechnologies.com

* Download configobj.py and validate.py; put them somewhere in your Python 
path (or in the same folder as your project, if you want)
* Add two lines to the top of your program: 
from configobj import ConfigObj
from validate import Validator
* To make working with your spec easier, 
import StringIO  # allows you t

Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 1:01 PM, Wayne Watson
wrote:

>  OK, I got the ObjectConfig and Validate downloads, and copied your Global
> class successfully. Don't I need to get the two files into Python as a
> module? How does that work?
>

Simplest: put them in the same folder as your own program.  More standard:
put them in one of the folders in your Python path - same general idea as
the DOS search path, it's a list of directories where Python will look for
modules you ask it to import.

>From the docs: (http://docs.python.org/tutorial/modules.html)
The Module Search
Path¶<http://docs.python.org/tutorial/modules.html#the-module-search-path>

When a module named spam is imported, the interpreter searches for a file
named spam.py in the current directory, and then in the list of directories
specified by the environment variable
*PYTHONPATH*<http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH>.
This has the same syntax as the shell variable *PATH*, that is, a list of
directory names. When
*PYTHONPATH*<http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH>is
not set, or when the file is not found there, the search continues in
an
installation-dependent default path; on Unix, this is usually
.:/usr/local/lib/python.

Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing the
input script (or the current directory),
*PYTHONPATH*<http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH>and
the installation- dependent default. This allows Python programs that
know what they're doing to modify or replace the module search path. Note
that because the directory containing the script being run is on the search
path, it is important that the script not have the same name as a standard
module, or Python will attempt to load the script as a module when that
module is imported. This will generally be an error. See section *Standard
Modules* <http://docs.python.org/tutorial/modules.html#tut-standardmodules>for
more information.



>
> Marc Tompkins wrote:
>
> On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson <
> sierra_mtnv...@sbcglobal.net> wrote:
>
>> See Subject. I've run across a 58 page document
>> <http://www.voidspace.org.uk/python/configobj.html><http://www.voidspace.org.uk/python/configobj.html>,
>> but am uncertain of its applicability to my present needs (see my thread on
>> "Changing the Attribute"). Usually, I end up with some 3-4 page document, so
>> this raises an eyebrow. Am I on the right trail? In the meantime, I think
>> I'll turn it into a more manageable pdf file before putting it to paper.
>>
>
> It's a very powerful module - does lots of things you don't need yet, and
> maybe never will - and I agree that it could benefit from a
> hit-the-ground-running guide...
>
> Here's a quick-and-dirty; you can flesh out the details from the
> documentation you downloaded.  (By the way, you'll also want to use the
> validate module - another 14 pages or so...)
> ==
> * Download configobj.py and validate.py; put them somewhere in your
> Python path (or in the same folder as your project, if you want)
> * Add two lines to the top of your program:
> from configobj import ConfigObj
> from validate import Validator
> * To make working with your spec easier,
> import StringIO  # allows you to work with strings as if they were
> files
> # You could just create a spec file, and open it normally, but this
> keeps everything in one place.
> * Somewhere in your program, create your spec and load it.  There are a
> lot of ways you can do this - for me, the simple thing is to put it in a
> class.  I create a class called Global - it's a crutch, I know...
> class Global(object):
> cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current
> directory + "\" + filename - but you could put it anywhere and call it
> anything
> # create your spec as a multi-line string between triple quotes
> tmpStr = """
> mask_file_name = string(default=None)
> gray_scale = boolean(default=True)
> post_event_stack = boolean(default=False)
> post_event_format = string(default="Tiff 2")
> show_real_time = boolean(default=False)
> hourly_rate = integer(min=0, default=0)
> slowdown= integer(min=0, max=10, default=1) # I don't know what
> this value is/does, so this is probably wrong
> start_time = string(default="00:00:00") # or you could make the
> default

Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 2:57 PM, Wayne Watson
wrote:

>  Thanks. I recall installing several libraries though, where somehow they
> were packaged to automatically install when opened.
>
> In the 
> description,
>  I do not see much of an explanations of examples of items like,
> integer(min=0, default=0). It looks like they may be called configspecs. I
> see this in section 5.3.2.2.
>
> key1 = integer(0, 30, default=15)
> key2 = integer(default=15)
> key3 = boolean(default=True)
> key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today')
>
> but not much else. Validators? Are there others like integer, booleand and
> option?  Items like start_time would then be called keywords?
>
The configspec (configuration specification) is that thing I put inside of
triple quotes.  It's basically a template of what your config file will look
like once it has actual data in it.

In 5.3.2, the sentence "The validate method uses the
validatemodule to do
the validation" links to the validate.py documentation - but
you won't see that if you're reading it on paper...

Remember I said there's a bunch of stuff there you might not need just now?
A good deal of it has to do with extending ConfigObj for your own twisted,
nefarious purposes (bwahahahahaha!) - you can write your own validators for
just about any kind of values you can imagine.  However, just to get
started, the built-ins are probably good (from the validate.py doc,
http://www.voidspace.org.uk/python/validate.html#the-standard-functions):




The standard functions come built-in to every Validator instance. They work
with the following basic data types :

   - integer
   - float
   - boolean
   - string
   - ip_addr

plus lists of these datatypes.

Adding additional checks is done through coding simple functions.

The full set of standard checks are :
  'integer':

matches integer values (including negative). Takes optional 'min' and 'max'
arguments :

integer()
integer(3, 9)# any value from 3 to 9
integer(min=0) # any positive value
integer(max=9)

 'float':

matches float values Has the same parameters as the integer check.
 'boolean':matches boolean values: True or False.

Acceptable string values for True are :

true, on, yes, 1

 Acceptable string values for False are :

false, off, no, 0

Any other value raises an error.
 'string':

matches any string. Takes optional keyword args 'min' and 'max' to specify
min and max length of string.
 'ip_addr':

matches an Internet Protocol address, v.4, represented by a dotted-quad
string, i.e. '1.2.3.4'.
 'list':

matches any list. Takes optional keyword args 'min', and 'max' to specify
min and max sizes of the list. The list checks always return a list.
 'tuple':

matches any list. This check returns a tuple rather than a list.
 'int_list':

Matches a list of integers. Takes the same arguments as list.
 'float_list':

Matches a list of floats. Takes the same arguments as list.
 'bool_list':

Matches a list of boolean values. Takes the same arguments as list.
 'string_list':

Matches a list of strings. Takes the same arguments as list.
 'ip_addr_list':

Matches a list of IP addresses. Takes the same arguments as list.
 'mixed_list':

Matches a list with different types in specific positions. List size must
match the number of arguments.

Each position can be one of :

int, str, boolean, float, ip_addr

So to specify a list with two strings followed by two integers, you write
the check as :

mixed_list(str, str, int, int)

 'pass':

matches everything: it never fails and the value is unchanged. It is also
the default if no check is specified.
 'option':

matches any from a list of options. You specify this test with :

option('option 1', 'option 2', 'option 3')

  ===


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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 7:42 PM, Wayne Watson
wrote:

>  I took your "starter" code, and formatted it to be what I hope is an
> acceptable program, Gobal_Config.py. See attached.  I'm using Python 2.5.2.
> I put the two modules in the same folder with it, and executed it in IDLE. I
> got this:
>   ...
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1637, in _parse
> ParseError, infile, cur_index)
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1748, in _handle_error
> raise error
> ParseError: Invalid line at line "1".
>
> As far as I can tell, line 1 of config.obj looks OK. It's a comment.
> Something is amiss.
>

I hate to say it, but IDLE is really holding you back.  It's convenient
because it installs automagically with Python, but it does funky, confusing
things - as in this case, where it's somehow stepped on the real error and
assigned blame in the wrong place; you've already experienced its internal
conflicts with Tkinter...  I use wxPython for my GUI goodness, and swear by
SPE (Stani's Python Editor).  I don't want to re-ignite the IDE wars, but I
definitely think you need to do yourself a favor and move away from IDLE.

Anyway, I didn't mean for that to be a standalone program, but to be picked
apart into chunks and dropped into an existing program (or, actually, just
to be used as an example - maybe of what _not_ to do, but an example...)
First error:
if argv is None:
   argv = sys.argv  <<== you haven't imported "sys"

Second error:
app = MyApp(0)  <<== you haven't defined a class called "MyApp", so you
can't do this...

So I cut it down to just this bit:
test = Global.cfgFile.validate(Global.vtor, copy=True)
Global.cfgFile.write()

(unindented all the way to the left, so that it executes as the main body of
the program) and it works just fine... except:
Third error (well, issue not error):
Take all my comments out!  They weren't meant to be included in final code.
ConfigObj allows inline comments in your config file, and in the configspec
- so my comments show up in there too.  Here's what Initial.sen ends up
looking like:

mask_file_name = None
gray_scale = True
post_event_stack = False
post_event_format = Tiff 2
show_real_time = False
hourly_rate = 0
slowdown = 1# I don't know what
#   this value is/does, so this is probably wrong
start_time = 00:00:00# or you could make the default None?
stop_time = 00:00:00
#   as a default latitude, if any...

I've cut everything down; I'm attaching it as Global_Config1.py (just to
avoid confusion with the earlier version).  If you do actually want to use
it as the basis of anything, you'll want to place the call to .validate()
somewhere near the beginning of the action - remember, the call to .write()
just afterward is completely optional; I had it in there for testing and
have kept it in there for the same reason.



> Does PYTHONPATH apply in Win XP? I haven't played at the level of paths for
> a long time in any OS. We can worry about an install "package" later for the
> modules. It might be best for the users of this program.
>

Ya know, I have no idea anymore.  I thought I knew - but I just did a SET
from a command prompt, and I don't have a PYTHONPATH variable.  I seem to
reacall something from a year or two ago... (looking now)  Oh yes - there's
a directory under your Python directory (Python25 in my case) called "Lib",
and a folder under that called "site-packages"; any text files with the
extension ".pth" will be scaned for the names of folders to add to the
search path.  As much as I love Python, I wish they'd get all this
together...

-- 
www.fsrtechnologies.com
import os, os.path
from configobj import ConfigObj
from validate import Validator
import StringIO

class Global(object): 
cfgFileName = os.getcwd() + os.sep + 'Initial.sen'
tmpStr = """
mask_file_name = string(default=None)
gray_scale = boolean(default=True)
post_event_stack = boolean(default=False)
post_event_format = string(default="Tiff 2")
show_real_time = boolean(default=False)
hourly_rate = integer(min=0, default=0)
slowdown= integer(min=0, max=10, default=1) 
start_time = string(default="00:00:00")
stop_time = string(default="00:00:00")
lat = float(min=0.0, max=90.0)
"""
cfgSpec = StringIO.StringIO(tmpStr) 
cfgFile = ConfigObj(cfgFileName,
configspec=cfgSpec, raise_errors=True, write_empty_values=True,
create_empty=True, indent_type='', list_values=True) 
vtor = Validator() 

test = Global.cfgFile.validate(Global.vtor, copy=True)
Global.cfgFile.write()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 4:51 AM, Wayne Watson
wrote:

>  Hi, actually I had two aims with the pseudo code, 1. print it, and 2.
> check to see if it would pull in the two modules. I pulled it into Word, and
> quickly formatted it to get the line wrap out, and put it in some sort of
> readable format. After that, I thought why not just take it as it was, and
> scoop it into IDLE.  My plan was to right a test program to get a better
> understanding of how to use ConfigObj rather than just try it through the
> program I plan to use it in.
>
> I've tried to keep to IDLE for no reason other than the author recommended
> it. Well, OK, I had gotten comfortable with the editor.  I'll try wxPython.
>

I wasn't very clear (and I shouldn't have mentioned wx at all, for
clarity!)  wxPython is not an alternative to IDLE, it's an alternative to
Tkinter.  SPE happens to have been written using wx (as IDLE uses Tkinter).
As I say, I should have left wx out of that... my point was that IDLE was
messing with the error somewhow and leading you to think it was a problem
with ConfigObj, when in fact it was probably the missing "import sys".
Since IDLE does that sort of thing A LOT, and also has known issues with
Tkinter (which you've experienced firsthand), I thought I'd slip in a gentle
suggestion to change tools.


>
> I took a quick look look at where Python was installed and found it was
> directly under C:, and not under Program Files. That's a surprise. Now I
> recall where I found something about classes and paths. It's on the File
> menu of IDLE, Class Browser and Path Browser.
>
> I thought, in the last post, I asked about items like: show_real_time =
> boolean(default=False) and hourly_rate = integer(min=0, default=0); but,
> apparently, I accidentally knocked it out.  Anyway, here's the question.
> Where is the syntax for items like boolean,  integer, and others described?
> The doc I have barely refers to them.
>

I posted it a few messages back - here's the link again:
http://www.voidspace.org.uk/python/validate.html
In particular you want this section:
http://www.voidspace.org.uk/python/validate.html#the-standard-functions


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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 9:58 AM, Wayne Watson
wrote:

>  I now have wxPython, IDLE and Vim installed. IDLE didn't disappear during
> the wx install.  It looks as though wxPython re-compiled library files. I'll
> be exploring vim now.
>

wxPython doesn't replace or remove anything - I still have IDLE on my
machine, I just don't use it.  The wxPython installer wasn't re-compiling
Python - it was using Python to compile its own scripts for use on your
machine.

Once again, to be clear: wxPython is an alternative to Tkinter, not to IDLE
- it's a different toolkit for creating GUI applications.
The upsides:
 - it's a good deal more sophisticated and powerful (I feel) than Tkinter,
and the apps you produce using it will look a lot more "native" (on Windows,
they'll look like Windows apps; on OS X they'll have the Apple look and
feel, etc.) and therefore more professional/less hobbyist-like.
 - the syntax of working with wxPython widgets feels more Pythonic (to me).
It's a matter of personal taste, but I tried Tkinter for a few days and
hated it; I tried wxPython and got hooked.
The downsides:
 - it's not part of Python proper, so it's an extra dependency (although
there's a great install-package creator called Gui2Exe that will bundle your
program along with Python and all other dependencies into a Windows-style
installer, so you can distribute just one file to your potential users.)
 - it's not part of Python proper, so most tutorials/Python books barely
mention its existence.  There's (1) excellent book, "wxPython in Action", a
couple of very active mailing lists, an excellent and gigantic demo program
with sample code for almost every widget, and Google.  Other than that,
you're on your own.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 10:59 AM, Wayne Watson  wrote:


> I'm willing to give vim a shot. I believe in an earlier thread unrelated to
> this, Alan suggested it. I'm perhaps incorrectly assuming vim will take care
> of the Tkinter problem. If these editors aren't really the source of some
> the error reporting problem, then I'm going to have to come up with new
> thinking or some tactic that will get to the real errors. If there is an
> influence of the editors, then I would think it has something to do with the
> interface to Python, so it comes down to which editor has the best or most
> stable interface with Python.  When Alan suggested it, there was something
> about the apparent awkwardness of executing the code, which made me pass on
> it. I'm going back to find out what that was.
>

The problem is not with IDLE as an editor, but with IDLE as a shell.
You can edit your code in any editor, and as long as it doesn't slip funky
hidden characters into your file (not an issue with any normal text editor
AFAIK, but you definitely don't want to use Word!) it will make NO
difference to your code.  The problem with IDLE is that it tries to be an
IDE (Integrated Development Environment - in other words, you can edit the
code, execute it, debug it, get rudimentary language help all in one
program) and it does a p#$$-poor job of it.  Alan's advice is to avoid the
IDE approach and get used to editing your program in one window and running
it in another - after all, that's how your users will see it.  And it's good
advice and a valid approach.  Myself, I like using an IDE - the one thing I
used to like about using Visual Studio was the integration.  So I use SPE,
which is an IDE and (IMHO) a good one.  It does not matter in the slightest
which tool you use, as long as that tool does not get in your way.

(Actually, I may be misrepresenting Alan and Vim a bit - I don't use it
myself.  You can run external programs from inside of vim, so Alan's desktop
may look more like a traditional IDE than I'm imagining.)
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Removing control characters

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 11:25 AM, Dinesh B Vadhia  wrote:

> My solution is:
>
> print ''.join[string.replace(c, r) for c in str if c in set]
>
> But, this returns a syntax error.  Any idea why?
>

Probably because you didn't use parentheses - join() is a function.

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


Re: [Tutor] KeyError: 'DEFAULT'

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 11:34 AM, Isaac Eiland-Hall wrote:

>  http://python.pastebin.com/m26864a1b
>
>
>
> Traceback (most recent call last):
>
> File "./loopy", line 328, in 
>
>
> set[current_set][current_section][current_key] = current_value
>
> KeyError: 'DEFAULT'
>
One thing pops out at me - I'm not quite done reviewing yet, but...
Don't use reserved words as variable names!  "set" is a built-in type in
Python, and set() is a constructor for sets.
By doing this:

> set = {}
>
the best you can hope for is to confuse your fellow programmers - worse,
there may be some ambiguity at runtime.

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


Re: [Tutor] KeyError: 'DEFAULT'

2009-02-19 Thread Marc Tompkins
On Thu, Feb 19, 2009 at 8:39 PM, Lie Ryan  wrote:

> On Thu, 19 Feb 2009 11:45:52 -0800, Marc Tompkins wrote:
> > Don't use reserved words as variable names!
>
> 
> str, set is built-in function not reserved words. Reserved words are like
> if, for, from, as (see the whole list type keywords in help() )
>
> Nevertheless, it is a bad idea to use built-in function names.
> 
>

Fair 'nuff.

Furthermore, there _are_ cases when you want to use built-in type or
function names: when you're overloading them with your own versions.  That's
why Python lets you use them in the first place... but if that wasn't what
you wanted to do, then avoid them like the plaque.  (A little dental humor
there.)
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-20 Thread Marc Tompkins
On Fri, Feb 20, 2009 at 9:45 AM, Wayne Watson
wrote:

>  Marc, I'm reaching back here, since something seems to have gone awry. I'm
> looking at the code for Global_Config1.py. When I execute it from IDLE, I
> get again:
>
> ...
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1637, in _parse
> ParseError, infile, cur_index)
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1748, in _handle_error
> raise error
> ParseError: Invalid line at line "1".   <<--- same old, same old
>
> However, we know IDLE can goof up. So I thought I'd execute the code by
> double clicking on the file. A black window appears briefly, then
> disappears. I have raw_input and other tricks to see if I could slow it
> down.  Finally, I went to the MS Command prompt window, and executed the py
> file from there. I get exactly the same message (s) as above. I don't recall
> if you tried the program on your system. Comments?
>

First: the line "1" it's talking about is the first line of the config file,
not of configobj.py.
Second: as written, there's no GUI here, so we _expect_ it to briefly show a
black window, then close - but when it's done, there should be a file called
"Initial.sen" in the current directory, which will look like this (this is
the output on my machine):
"""

mask_file_name = None
gray_scale = True
post_event_stack = False
post_event_format = Tiff 2
show_real_time = False
hourly_rate = 0
slowdown = 1
start_time = 00:00:00
stop_time = 00:00:00

"""
(I've added the triple quotes for visual clarity - they don't appear in the
actual file.)

I suspect that what's happening is that you already have a file called
Initial.sen, and its contents don't match the configspec.  So the ParseError
is an expected result - we either need to tweak the configspec to match your
previous file, or add exception handling, or (simplest) if you don't have
any real installed base, just start from scratch.

Do me two favors:
 - send your existing Initial.sen so I can look at modifying the configspec
or adding exception handling
 - delete or rename it, then try the program again.

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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-20 Thread Marc Tompkins
On Fri, Feb 20, 2009 at 10:45 AM, Paul McGuire  wrote:

> Has anyone already mentioned the article in Python Magazine, May, 2008?
>

No, I for one haven't seen it.  Is it available online, or only for
subscribers?


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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-20 Thread Marc Tompkins
On Fri, Feb 20, 2009 at 5:05 PM, Wayne Watson
wrote:

>  Not because of this particular problem, but, out of curiosity, I tried
> today to give the MS command line facility a shot. I think that's what we
> are discussing here. I immediately ran into something of a problem. My
> assumption was is was fully a DOS window.  Trying to work my way to folder
> was a bit daunting, since I have not used this in a very long time, but this
> wasn't the problem.
>
> As it turns out, there was an easier way. Drag and drop the path+program
> link into the window after placing a CD in the command line. Very non-DOS*.
> :-) One could then backspace to remove the program name, so the result was a
> CD to the program folder, where several programs reside. Now the problem
> became one of typing in the name of the program each time it was to be
> executed. With a pretty long path name and the need to type in the file name
> on each use, it seemed a bit tedious.  Maybe there's another way?
>
> * But yet, no copy and paste from the folder Address area
>

Two tips: Command Prompt Here and tab completion.

1) If you haven't already, check out the Windows XP PowerToys:
http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx
Most of them are useless (to me, anyway) but the two that are indispensible
- I install them on every (XP) machine I work on - are TweakUI and Command
Prompt Here.  It adds a "Comand Prompt Here" item to the menu when you
right-click on a folder.  I remember seeing a few articles explaining how to
do this yourself - but why bother?

2)  Tab completion is turned on by default in Windows XP - just type the
first few letters of the filename, and Windows will fill in the rest.  If
there are several files that start with what you typed, you might need to
add a few letters to get the right one, but it still saves lots and lots of
typing.  It even intelligently handles long filenames with spaces in them,
putting them in quotes when required.  If it's turned off on your machine,
you can turn it back on through TweakUI (see #1 above) under "Command
Prompt."

So for example, you would right-click on your project folder, select Command
Prompt Here, type "python " followed by "G" and a tab, then Enter.  (Or
maybe "GL" then Tab, or whatever - you get the drift.)

If you want a command prompt in your desktop folder, just right-click on a
folder on your desktop, select CPH, then type "cd.."  Much simpler than
Start/Run/cmd followed by "cd \Documents and Settings\username\Desktop".

Copy and paste DOES work, but not with keyboard shortcuts (presumably, those
are intercepted by the command prompt itself) - right-click in the command
window and select Paste.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-21 Thread Marc Tompkins
On Sat, Feb 21, 2009 at 6:42 PM, Wayne Watson
wrote:

>  I tried XP's Help on command prompts. Not much there. Is there another
> source?
>

There are lots, and Google knows most of them - here's a good one to start
with: http://www.ss64.com/nt/

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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-21 Thread Marc Tompkins
On Sat, Feb 21, 2009 at 8:26 PM, Wayne Watson
wrote:

>  I've found others like that, but I was looking for something more
> descriptive. Things like typing fill-in, or cut/paste, use of F8, etc.  I'd
> guess there are more.
>
Click through a little further: http://www.ss64.com/nt/cmd.html
Should tell you more than you could possibly want to know about the XP
command prompt and its options.

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


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-21 Thread Marc Tompkins
On Fri, Feb 20, 2009 at 2:19 PM, Wayne Watson
wrote:

>  Good. Thanks. It works fine for me now.  I deleted the file. I just ran
> the program again straight from the py file, and it put my the black window
> with my raw_input prompt.  It seems odd that it wouldn't have left text
> debris when it crashed.
>
> I've attached a copy of an Initial file. It's still under development, but
> pretty close for the immediate purposes. The "_file_" names will likely end
> up as a string showing the complete path to the file.  start/stop_time will
> be times in
>  the format shown, hh:mm:ss. The first line is just a header, and currently
> gets tossed when the file is read.  "_name" are strings. No others have seen
> the program, so development continues.
>
> Sentinel NC Configuration File Sentinel User 3 - 1/3/2009 (Meteor Software)
> config_file_name=Initial.sen
> mask_file_name=*none*
> gray_scale=True
> post_event_stack=False
> post_event_format=Tiff 2
> show_real_time=False
> hourly_rate=12
> slowdown=1
> start_time=20:00:12
> stop_time=06:03:00
> lat=40.0
> long=120.0
> utc_offset=8
> elevation=1000.0
> site_name=Unknown
> clock_drift=0.0
> zenith_x_pixel=319
> zenith_y_pixel=239
> north_angle_rotation=0.0
> events=Events
> post_events=Post_Events
> meteors=Meteor_Tags
> composites=wtw:same as events?
> flat_mask_val=30
> mask_file_name=*none*
> mask_file_offset=30
> flat_mask_active=False
>
>
OK - first problem is, as the error message indicated, line 1:

> Sentinel NC Configuration File Sentinel User 3 - 1/3/2009 (Meteor Software)
>
It's not a comment, it's not a real configuration item, so ConfigObj barfs.
Put a "#" in front of that, and we run just fine until:

> configobj.DuplicateError: Duplicate keyword name at line 26.
>
which is also correct - line 26 is a duplicate of line 3.  Put a "#" in
front of _that_, and we run just fine with the following result:
"""

config_file_name = Initial.sen
mask_file_name = *none*
gray_scale = True
post_event_stack = False
post_event_format = Tiff 2
show_real_time = False
hourly_rate = 12
slowdown = 1
start_time = 20:00:12
stop_time = 06:03:00
lat = 40.0
long = 120.0
utc_offset = 8
elevation = 1000.0
site_name = Unknown
clock_drift = 0.0
zenith_x_pixel = 319
zenith_y_pixel = 239
north_angle_rotation = 0.0
events = Events
post_events = Post_Events
meteors = Meteor_Tags
composites = wtw:same as events?
flat_mask_val = 30
#mask_file_name=*none*
mask_file_offset = 30
flat_mask_active = False

"""
(Once again, those are my own triple quotes) Notice that the first line has
been suppressed - if you want a comment to survive into the actual file,
you'll need to add it in the configspec; however, line 26 _did_ survive...
there's some mystery there, but I'm not going to kill myself over it.
I haven't modified the actual program or the configspec.  This illustrates
that the configspec dictates the bare minimum that the config file can
contain, not the maximum - any valid lines (of the format "name = value")
that are in the config file but not in the spec will survive (and be
available to your program).


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


Re: [Tutor] Converting "HH:MM:SS" to datetime

2009-03-01 Thread Marc Tompkins
On Sun, Mar 1, 2009 at 10:04 AM, Wayne Watson
wrote:

>  Ok, how do I do what's mentioned in Subject?
>


One thing to be aware of - Python datetimes are just that: date + time.  If
you specify only the time, the date will be filled in with a default value -
generally the beginning of the epoch for your particular platform.

"datetime" objects (but not "time" objects!) have a method called "strptime"
which does exactly what you want - you give it an input string and a format
string to tell it how to interpret the input, and it returns a datetime
object.  Then you can remove the date portion and you're done:
>>> import datetime
>>> blah = datetime.datetime.strptime("13:01:15","%H:%M:%S")
>>> blah
datetime.datetime(1900, 1, 1, 13, 1, 15)
>>> blah = blah.time()
>>> blah
datetime.time(13, 1, 15)

The format string for strptime uses the same conventions as the strftime()
function; they're generally not listed separately.

Or you can hack the string into its component parts and create the time from
a timetuple:
(I'm including the mistakes I made along the way)
>>> inDateStr = "13:01:15"
>>> inHour = inDateStr[:2]
>>> inHour
'13'
>>> inMin = inDateStr[4:6]
>>> inMin
'1:'
>>> inMin = inDateStr[3:5]
>>> inMin
'01'
>>> inSec = inDateStr[-2:]
>>> inSec
'15'
>>> blah = datetime.time(inHour, inMin, inSec)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: an integer is required
>>> blah = datetime.time(int(inHour), int(inMin), int(inSec))
>>> blah
datetime.time(13, 1, 15)
>>>


Hope that helps.


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


Re: [Tutor] What is this [] construction?

2009-03-03 Thread Marc Tompkins
On Mon, Mar 2, 2009 at 11:18 PM, Andre Engels  wrote:

> On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson
>  wrote:
> >self.recent_events = [ event for event in self.recent_events
> >if os.path.exists(event) and
> >(time.time() - os.path.getmtime(event)) <
> > 3600.0 ]
>

In this example, we'll step through self.recent_events - which apparently is
a list of filenames - and call each item we come across "event".  That's the
"for event in self.recent_events" part.
If the filename corresponds to an actual file ("if os.path.exists(event)")
AND that file has been modified less than an hour ago (the difference
between the current time and the file's modification time is less than 3,600
seconds), then we add "event" to the list we're building and move on to the
next "event" until we're done.
At the end, we call our new list self.recent_events, which replaces the list
we were looping through a moment ago.  Chances are it's a bit shorter now.

List comprehensions will make your head hurt the first few dozen times you
encounter them.  After that, they become easier to use than the longer
for-loop structure they replace - as André pointed out, they read almost
like English.

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


Re: [Tutor] What is this [] construction?

2009-03-03 Thread Marc Tompkins
On Tue, Mar 3, 2009 at 7:01 PM, Lie Ryan  wrote:

> Marc Tompkins wrote:
>  > List comprehensions will make your head hurt the first few dozen times
>
>> you encounter them.  After that, they become easier to use than the longer
>> for-loop structure they replace - as André pointed out, they read almost
>> like English.
>>
> I have to disagree, I immediately fell in love with list comprehension when
> I first meet them.
>

OK, I over-generalized.  They made MY head hurt at first.  Now I love them.

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


Re: [Tutor] What is this [] construction?

2009-03-04 Thread Marc Tompkins
On Tue, Mar 3, 2009 at 11:56 PM, Alan Gauld wrote:

>
> In Python v3 list comprehensions and generator expressions have been
> "merged" in that putting a GE inside [] has the same effect as a LC. In
> practice this makes little or no difference to the programmer its just how
> Python handles it behind the scenes.
>

In Python 3000, lists comprehend YOU!  (With apologies to Yakov Smirnoff...)
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Executing a C Program from RH Linux in Python for Win

2009-03-20 Thread Marc Tompkins
On Fri, Mar 20, 2009 at 8:46 AM, Wayne Watson
wrote:

>  I guess I haven't made clear above. This is a Red Hat Linux compiled C
> program. Indications from others above, suggest it is possible to execute it
> under Win Python. If that's true, then my guess is that something prior to
> the call must be done in the way of informing the call it is dealing with a
> non-Win program.
>

Neither Python proper nor Popen() are actually executing the program - the
Windows shell/command interpreter does that (command.com or cmd.exe,
depending on your Windows version); Popen() is just a mechanism for making
the request, waiting for a response, and processing the result when it
comes.

If you want to run a non-Windows executable on Windows, you need to use an
alternate shell - someone mentioned Cygwin - although I'm not certain that
even that will do it for you.  What makes an executable OS-specific is not
the language it's written in, but the libraries that it's compiled/linked
with. If you have access to the source code, the simplest thing would
probably be to recompile it on your own machine...  the GCC (Gnu Compiler
Collection) is free.

You mentioned the 'A' attribute - in Windows, that stands for Archive, and
was created as a way for early backup programs to do differential backups
(i.e. you do a full backup - the backup program copies every file, clearing
the A attribute as it does so; new and updated files have the A attribute
set, so the next time you do a backup, the program only copies files that
have the A attribute...)
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Executing a C Program from RH Linux in Python for Win

2009-03-20 Thread Marc Tompkins
On Fri, Mar 20, 2009 at 10:02 AM, Marc Tompkins wrote:

> If you want to run a non-Windows executable on Windows, you need to use an
> alternate shell - someone mentioned Cygwin - although I'm not certain that
> even that will do it for you.  What makes an executable OS-specific is not
> the language it's written in, but the libraries that it's compiled/linked
> with. If you have access to the source code, the simplest thing would
> probably be to recompile it on your own machine...  the GCC (Gnu Compiler
> Collection) is free.
>

Nope, just checked the Cygwin page:
What Isn't Cygwin?

Cygwin is *not* a way to run native linux apps on Windows. You have to
rebuild your application *from source* if you want it to run on Windows.
Cygwin is *not* a way to magically make native Windows apps aware of UNIX ®
functionality, like signals, ptys, etc. Again, you need to build your
apps *from
source* if you want to take advantage of Cygwin functionality.

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


Re: [Tutor] Executing a C Program from RH Linux in Python for Win

2009-03-20 Thread Marc Tompkins
On Fri, Mar 20, 2009 at 10:02 AM, Marc Tompkins wrote:

> Neither Python proper nor Popen() are actually executing the program - the
> Windows shell/command interpreter does that (command.com or cmd.exe,
> depending on your Windows version); Popen() is just a mechanism for making
> the request, waiting for a response, and processing the result when it
> comes.
>

I wasn't very clear here: instead of "the Windows shell/command interpreter
does that..." I should have said "the underlying operating system/shell does
that..."

There are versions of Python for many platforms, and Python code is intended
to be as cross-platform as possible, so if you were running some other
operating system on your machine, Popen() would be passing your request
to... whatever.  And if you were running, say, Linux, and trying to execute
a Windows program... that wouldn't work either.  (Unless you told Popen to
pass it through WINE, but I'm not even sure that's possible.  There isn't an
equivalent to WINE for running Linux executables under Windows, so far as I
can Google.)
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax error

2009-03-22 Thread Marc Tompkins
On Sun, Mar 22, 2009 at 8:35 PM, John Jenkinson wrote:

> I am trying to write a program that displays the string expression "Game
> Over", in a console window that remains open.
>
> my code is as follows:
>
> # Game Over console window
>
> print "Game Over"
> raw input("\n\nPress the enter key to exit.")
>

Assuming that you've posted exactly what's in your program, the problem is
"raw input()" (which would mean 'execute a statement called raw, with an
input() function following it') instead of "raw_input()".  Since there isn't
a built-in statement called "raw", you get the syntax error.

Spelling counts.

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


Re: [Tutor] printing files

2009-03-26 Thread Marc Tompkins
On Thu, Mar 26, 2009 at 10:42 AM, Bala subramanian <
bala.biophys...@gmail.com> wrote:

>print>>out, handle  <-- Here i want to write only from second line. I
> dnt want to loop over handle here and putting all lines except the first one
> in
> another variable. Is there any
> fancy way of doing it.
>


Without changing anything else, you could do it with a slice:

flist=glob.glob(*.txt)
> out=open('all','w')
>
> for files in flist:
>handle=open(flist).readlines()
>print>>out, handle[1:]  # start with second item (indexes start at 0,
> remember) and go to end
> out.close()
>


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


Re: [Tutor] printing files

2009-03-26 Thread Marc Tompkins
On Thu, Mar 26, 2009 at 10:56 AM, Marc Tompkins wrote:

> Without changing anything else, you could do it with a slice:
>

You should probably also close your input files when you're done with them.

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


Re: [Tutor] why is unicode converted file double spaced?

2009-04-07 Thread Marc Tompkins
On Tue, Apr 7, 2009 at 9:52 AM, Pirritano, Matthew wrote:

> So Kent's syntax worked to convert my Unicode file to plain text. But
> now my data is double space. How can I fix this.  Here is the code I'm
> using.
>

Sounds like you're being stung by the difference in newline handling between
operating systems - to recap, MS-DOS and Windows terminate a line with a
carriage return and linefeed (aka CRLF or '\r\n'); *nixes use just LF
('\n'); Mac OS up to version 9 uses just CR ('\r').  You will have noticed
this, on Windows, if you ever open a text file in Notepad that was created
on a different OS - instead of breaking into separate lines, everything
appears on one long line with funky characters where the breaks should be.
If you use a more sophisticated text editor such as Notepad++ or Textpad,
everything looks normal.  Python has automatic newline conversion;
generally, you can read a text file from any OS and write to it correctly
regardless of the OS that you happen to be running yourself.

However, the automatic newline handling (from my perfunctory Googling)
appears to break down when you're also converting between Unicode and ASCII;
or it could be because you're essentially doing a read() from one file and a
writelines() to the other; or something else entirely.  Anyway, try this -

import codecs
>
> inp = codecs.open('g:\\data\\amm\\text files\\test20090320.txt', 'r',
> 'utf-16')
> outp = open('g:\\data\\amm\\text files\\new_text_file.txt', 'w')
>
for outLine in inp:
> outp.write(outLine.strip())
>
inp.close()
> outp.close()


strip() will remove any leading or trailing whitespace - which should
include any leftover CR or LF characters.

HTH -


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


Re: [Tutor] why is unicode converted file double spaced?

2009-04-07 Thread Marc Tompkins
On Tue, Apr 7, 2009 at 10:26 AM, Pirritano, Matthew wrote:

>  Thanks Marc,
>
>
>
> But I think that got rid of all of my carriage returns. Everything on just
> one line now.
>
Sorry!  My bad!  Try this instead:

> for outLine in inp:
> outp.write(outLine.strip() + '\n')
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why is unicode converted file double spaced?

2009-04-07 Thread Marc Tompkins
On Tue, Apr 7, 2009 at 10:52 AM, Kent Johnson  wrote:

> You really should use rstrip(), leading white space is generally
> significant in a text file, trailing white space not so much.
>

Good point.

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


Re: [Tutor] why is unicode converted file double spaced?

2009-04-07 Thread Marc Tompkins
On Tue, Apr 7, 2009 at 10:57 AM, Pirritano, Matthew wrote:

>  Excellent! Thanks Marc, Kent, and everyone. Marc your code worked. Now to
> see if it will run on the full 4.5 GB file! : )
>
Glad to help - but you should definitely take Kent's advice and replace my
strip() with rstrip().  Good luck!


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


Re: [Tutor] why is unicode converted file double spaced?

2009-04-07 Thread Marc Tompkins
On Tue, Apr 7, 2009 at 11:59 AM, Pirritano, Matthew wrote:

>  I did get an error…
>
>
>
> Traceback (most recent call last):
>
>   File "C:\Projects\unicode_convert.py", line 8, in 
>
> outp.write(outLine.strip()+'\n')
>
> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 640-641: ordinal not in range(128)
>
Should I be worried about this. And where does this message indicate that
> the error is. And what is the error?
>
>  That error is telling you that your input file contains character(s) that
don't have a valid representation in ASCII (which is the AMERICAN Standard
Code for Information Interchange - no furrin languages need apply!)  I came
into this conversation late (for which I apologize), so I don't actually
know what your input file contains; the fact that it's encoded in UTF-16
indicates to me that its creators anticipated that there might be
non-English symbols in it.

Where is the error... well, it's positions 640-641 (which, since most code
points in UTF-16 are two bytes long, might mean character 319 or 320 if you
opened it in a text editor - or it might mean character 640 or 641, I don't
really know...) of _some_ line.  Unfortunately we don't know which line,
'cause we're not keeping track of line numbers.  Something I often do in
similar situations: add print statements temporarily (printing to the screen
makes a significant performance drag in the middle of a loop, so I comment
out or delete the prints when it's time for production.)

Two approaches: add an index variable and print just the number, or print
the data you're about to try to save to the file.  In your case, I'd go with
the index, 'cause your lines are apparently much longer than screen width.

index = 1
for outLine in inp:
print(index)
outp.write(outLine.rstrip() + '\n')
index += 1

You'll have a long string of numbers, followed by the error/traceback.  The
last number before the error should be the line number that caused the
error; open your file in a decent text editor, go to that line, and look at
columns 319/320 (or 640/641 - I'm curious to find out which) - that will
show you which character caused your problem.

What to do about it, though: the "codecs" module has several ways of dealing
with errors in encoding/decoding; it defaults to 'strict', which is what
you're seeing. Other choices include 'replace' (replaces invalid ASCII
characters with question marks, if I recall correctly) and 'ignore' (which
just drops the invalid character from the output.)

Change your file-opening line to:

inp = codecs.open('g:\\data\\amm\\text files\\test20090320.txt',
'r','utf-16', 'replace')
or
inp = codecs.open('g:\\data\\amm\\text files\\test20090320.txt',
'r','utf-16', 'ignore')

depending on your preference.

Have fun -
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] delphi, pascal and Python

2009-05-20 Thread Marc Tompkins
On Wed, May 20, 2009 at 11:10 AM, Alan Gauld wrote:

>
> "Andy Cheesman"  wrote
>
>  Is there a Method for wrapping delphi and/or pascal code into python like
>> SWIG?
>> I've googled to no avail, Can anyone help me?
>>
>
> Try this:
>
> http://membres.lycos.fr/marat/delphi/python.htm
>
> Alan G
>

That's a package to let you embed Python in Delphi; the OP wants to go the
other direction.

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


Re: [Tutor] Needing Help

2009-06-30 Thread Marc Tompkins
On Tue, Jun 30, 2009 at 12:27 PM, Bob Rea  wrote:

> Why doe sit work with a dob in 1943 and not with one in 1980
> then, that's what really bugs me
>

Nothing to do with the year.  Your birth month is BEFORE June; her birth
month is after.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] When are strings interned?

2009-07-01 Thread Marc Tompkins
On Wed, Jul 1, 2009 at 5:29 PM, Robert Berman  wrote:

> > >>> n = "colourless"
> > >>> o = "colourless"
> > >>> n == o
> > True
> > >>> n is o
> > True
> > >>> p = "green ideas"
> > >>> q = "green ideas"
> > >>> p == q
> > True
> > >>> p is q
> > False
> >
> > Why the difference?
>
> The string p is equal to the string q. The object p is not the object q.
>
> Robert
>
Yes, but did you read his first example?  That one has me scratching my
head.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if: else: can not get else to work

2009-07-07 Thread Marc Tompkins
On Tue, Jul 7, 2009 at 6:36 PM, David  wrote:

> My question is I tried to get it to print out when the directory was empty
> like this;
>
> for file in fobj:
>pathname = os.path.join(folder, file)
>if os.path.exists(pathname):
>print 'removing... ', file
>os.remove(pathname)
>else:
>print 'No files to clean'
>
> But if there are no files in the directory it never gets to the else.
>

It shouldn't, the way you've got it set up...  As I read your program, the
only way it would get to the "else" would be if some other process deleted
one of the files in the directory AFTER your script got a directory listing,
but before your script gets around to deleting it.

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


Re: [Tutor] No Elegant XML Output in ElementTree?

2009-07-27 Thread Marc Tompkins
On Mon, Jul 27, 2009 at 8:32 PM, Luis Galvan wrote:

> Hi tutors,
> Okay, so I just started to learn ElementTree (and XML processing in
> general) and I just can't, for the life of me, find a way to output the XML
> file in an actual hierarchic presentation.


What you want is generically called "prettyprinting".  I don't use
ElementTree myself (I use Amara/Akara), so I don't know whether effbot
followed through on this, but take a look at this page:
http://effbot.org/zone/element-lib.htm

I also found this page:
http://renesd.blogspot.com/2007/05/pretty-print-xml-with-python.html
and in the comments there's this, which looks pretty simple:

To pretty print an ElementTree:

from xml.minidom import parseString
from xml.etree import ElementTree

def prettyPrint(element):
txt = ElementTree.tostring(element)
print minidom.parseString(txt).toprettyxml()
Substitute output to a file for "print", and you're done.In Amara, I do
this:
def Save(self):
outFile = open(self.fileName,'w+b')
self.xDoc.xml(outFile,indent=u'yes')
outFile.close()
but that's not much help for etree, I know...

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


Re: [Tutor] New guy question...

2009-09-14 Thread Marc Tompkins
On Mon, Sep 14, 2009 at 12:30 PM, Warren  wrote:
> Type integers, each followed by ENTER; or just ENTER to finish
> Traceback (most recent call last):
>  method  in test.py at line 9
>    line = input()
> EOFError: EOF when reading a line
>
> Why is the "input" statement not waiting for input like it should be and
> instead killing the app?  My google-fu is failing me on this one.
>

Try changing it to raw_input() instead...
>From the docs:
  input([prompt])
Equivalent to eval(raw_input(prompt)).

In other words, Python is trying to evaluate your input as a valid
Python statement at the moment you enter it.
I don't quite see why eval(blank line) == EOF, but apparently it does...

When I tried your code, if I pressed Enter it blew up with the same
error you reported; if I entered integers instead, it accepted them
happily until my first blank line, at which point it again complained
of an EOF.  (I'm running 2.62 on Windows, by the way.)  Changing to
raw_input() made things work, so I think it's the implicit eval().


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


Re: [Tutor] What language should I learn after Python?

2009-10-06 Thread Marc Tompkins
On Tue, Oct 6, 2009 at 12:39 PM, Mark Young  wrote:

> I'm now fairly familiar with Python, so I'm thinking about starting to
> learn a second programming language. The problem is, I don't know which to
> learn. I want a language that will be good for me to learn, but is not so
> different from python that I will be totally confused.
>

May I suggest (some dialect of) SQL?  It _is_ quite different from Python,
but learning it will familiarise you with some concepts that will be very
useful if you want to use your Python skillz in a data-driven application.
 It's true that you can use Python modules to interface with databases, and
maybe never write more than a line or two of real SQL - but those modules
are a lot easier to understand if you know what they're doing under the
hood.

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


Re: [Tutor] Sleep

2009-10-07 Thread Marc Tompkins
On Wed, Oct 7, 2009 at 4:01 PM, Hristos Giannopoulos
wrote:

> Is it possible for a python script to make a windows computer sleep or wake
> from sleep? Preferably in windows?
>

I think your best bet for controlling Windows power management with Python
will be the pywin32 module, at http://sourceforge.net/projects/pywin32/
It wraps the Win32 API so that Python scripts can call it.
You'll find there's not much documentation for pywin32, but you won't need
much, because what you really need to know is how to use the API to do what
you want.

Just Google for that - there's a huge body of information available on the
Web about using the Win32 API - then use pywin32 to wrap whatever API call
you find.

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


Re: [Tutor] Iterable Understanding

2009-11-15 Thread Marc Tompkins
On Sun, Nov 15, 2009 at 4:11 PM, Stephen Nelson-Smith wrote:

> > import gzip
> > from heapq import heappush, heappop, merge
>
> Is this a preferred method, rather than just 'import heapq'?
>
> It has a couple of advantages:
-  convenience: if you "import heapq", then to do a push you need to type
"heapq.heappush"; if you do "from heapq import heappush", then you can
simply type "heappush" to use it.
-  efficiency: you import only what you actually need to use.  Importing all
of a gigantic package to use one or two methods is wasteful; on the other
hand, if a package contains five methods and you're using four of them, this
might not be such a big deal.
Remember, this is Python... there's always going to be more than one way to
do it, and you'll get an argument on this list for every one of them.

What you should NEVER do, though: "from package import *"
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No beep from winsound.Beep(500, 500)

2009-12-19 Thread Marc Tompkins
Richard -  It works (in Python 2.6, mind you) on my 64-bit Win7 machine, but
I suspect that that may be because of Microsoft's compatibility twiddling on
the back end.  I Googled, and there seem to be a number of reports of people
having trouble with 64-bit Vista and winsound.Beep().  I suspect that
allowing programs access to the system speaker is one of those things that
MS decided to cut out in Vista, but then decided to bring back in 7.

Chris - if it were just a disconnected speaker, I don't think he'd get the
runtime error...

On Sat, Dec 19, 2009 at 2:02 AM, Chris Fuller  wrote:

>
> Something to keep in mind is that the audio output of your computer and the
> system speaker are independent.  Sometimes the BELL character (ACSII 0x07)
> will sound the system speaker, spending on your OS, drivers, etc.
>
> The winsound docs say it's the speaker, which is connected to the
> motherboard
> with an odd four pin connector (with only two wires).  It's normally only
> used
> during boot up, so it could have been left disconnected and not missed.
>
> Cheers
>
> On Saturday 19 December 2009, Richard D. Moores wrote:
> > My laptop, a Toshiba Satellite running Python 3.1 and Vista 64-bit
> >
> > SP2, with the speakers on and otherwise working, won't give me a beep:
> > >>> from winsound import Beep
> > >>> Beep(500, 500)
> >
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > Beep(500, 500)
> > RuntimeError: Failed to beep
> >
> > Please give me some hints as to what I can do about this.
> >
> > Thanks,
> >
> > Dick Moores
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


[Tutor] In-place expansion of list members... possible?

2007-11-07 Thread Marc Tompkins
This question has probably been asked and answered many times, but I can't
figure out how to word my question to get relevant results from Google.  So
I thought I'd try some human beings, eh?

I'm working with delimited files (ANSI X12 EDI nonsense, to be precise.)
First I load the records to a list:
tmpSegs = inString.split(self.SegTerm)

Now, I want to replace each string in that list with a string:

for seg in tmpSegs:   # 'seg' is short for 'segment'
seg = seg.split(self.ElemSep)

It doesn't work.  If I check the contents of tmpSegs, it's still a list of
strings - not a list of lists.  So I do this instead:
tmpSegs2 = []
for seg in tmpSegs:
tmpSegs2.append(seg.split(self.sElemSep))
del tmpSegs

This works.  And, for the size of files that I'm likely to run into,
creating the extra list and burning the old one is probably not going to
swamp the machine - but it feels clumsy to me, like if I just knew the
secret I could be much more elegant about it.  I don't want the next guy who
reads my code to scratch his head and say 'What was he thinking?' -
especially if it's me in a year's time!

What puzzles me most is that I can replace 'seg' with just about anything
else -
for seg in tmpSegs:
seg = seg.strip()
or
for seg in tmpSegs:
seg = 'bananas'
or
for seg in tmpSegs:
seg = seg + ' bananas'
and it works.  So why can't I replace it with its own split?

It's not a burning question - development continues - but I'm really
curious.

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


Re: [Tutor] In-place expansion of list members... possible?

2007-11-07 Thread Marc Tompkins
Try this (untested code):

for index in xrange(0, len(tmpSegs)):
   tmpSegs[index] = tmpSegs[index].split(self.ElemSep)


Thank you - that works nicely, and it's a much better replacement for
something else I was doing to achieve the same result (you know, the old
count+=1 nonsense - every day, in every way, I'm struggling to become more
and more Pythonic.)

Now, I did already (intellectually) understand this:

A list is an array of pointers to objects, what you've done here is
create a new name referencing an item in the list, then making that new
name point to something different.

Given that, however, I still don't entirely understand why the other
examples I gave DO work.  Seems it should be one or the other, no?

I'm probably just being dense, though.

Marc

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


Re: [Tutor] In-place expansion of list members... possible?

2007-11-07 Thread Marc Tompkins
> > What puzzles me most is that I can replace 'seg' with just about
> > anything else -
> > for seg in tmpSegs:
> > seg = seg.strip()
> > or
> > for seg in tmpSegs:
> > seg = 'bananas'
> > or
> > for seg in tmpSegs:
> > seg = seg + ' bananas'
> > and it works.  So why can't I replace it with its own split?
>
> If by 'it works' you mean that tmpSegs is changed...you are mistaken or
> there is something you are not showing. Can you show why you think this
> changes tmpSegs?


I see I have been misled by trying too many things in a short time and
confusing my results.  I could have sworn that late last night, before I hit
on the solution of assigning to a new list altogether, I tried the above
examples and followed them with another "for seg in tmpSegs" loop that
simply printed the contents.

I now suspect myself of being too sleepy (and probably inadvertently
assigning to a new list anyway!) at the time, because - as you already know
- when I try it now, tmpSegs is unchanged.  I hang my head in shame.


Thanks for the responses -

Marc
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] XP environment variables (was: Wrong version of Python being executed)

2007-11-12 Thread Marc Tompkins
Thus spake Alan G:

> > Note, these are entered in Ctrl Panel, System environment variables,
> > NOT at the command line.
>
> Umm, have you rebooted? Probably an obvious step but I don't
> think environment vars get reset in real time. They didn't used
> to on NT but that may have changed in W2K or XP... I haven't
> checked in a while.
>

Not quite true.
In W2K and XP (not sure about NT), changes to environment variables made via
the Control Panel will affect any NEW environments instantiated from the
moment you click OK in the Environment Variables dialog.
Easy to test:  Start/Run/CMD; type SET.  Go to
CPanel/System/Advanced/Environment Variables, create a new variable, click
OK to get back to System.  Switch back to your cmd prompt, type SET: no new
variable!Start/Run/CMD again to start a new prompt; type SET: new
variable exists.

Something to be aware of, though - if CMD is being started by some other
process, it may inherit a 'stale' environment.  For instance, when I start a
command prompt via Launchy, my new variable does NOT exist.  It took me a
moment to realize that the new prompt was running in Launchy's environment,
which doesn't get refreshed until I reboot.
(The original poster mentioned that he always uses Start/Run/CMD, so this is
not affecting him; I merely mention this for others who might run into it.)

Let me also mention that this is the only drawback I've found to using
Launchy (www.launchy.net) in the months since I started using it, I've
probably saved several hours I would have wasted poking around in my Start
menu.  I've tried reorganizing my menus, but the mix of programs I use
day-to-day changes constantly.  I wholeheartedly recommend Launchy to any
Windows users out there.  (I have a similar utility in Ubuntu, but I don't
remember its name.  Mac users, of course, don't need anything like this, as
theirs is an entirely faith-based interface.)

Marc
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP environment variables (was: Wrong version of Python being executed)

2007-11-12 Thread Marc Tompkins
Glad to help!  It wouldn't have occurred to me as quickly as it did, except
that I use Sysinternals' Process Explorer as a Task Mangler replacement - it
allows you to see a hierarchical list of processes, as well as the usual
sorted lists - and a week or two ago I happened to notice that CMD was
running as a child of Launchy.  Actually, "noticed" is too strong a word -
but today it clicked.  Learn something new every day, eh?


On Nov 12, 2007 9:01 AM, Tim Golden <[EMAIL PROTECTED]> wrote:

>
> > Something to be aware of, though - if CMD is being started by some other
> > process, it may inherit a 'stale' environment.
>
> *That's* why it is. For years I've launched my command shells from one
> of various shortcut-key utils and I *never* tumbled to the fact that
> that meant my cmd shell was running inside that util's process and so
> didn't inherit env var changes. Thanks so much.
>
> I have used Launchy, as a matter of fact, but for some reason it never
> really clicked for me -- maybe I use a small enough range of programs
> normally -- so I ended up uninstalling it. I agree it did what it did
> very well, though.
>
> TJG
>

I do understand that Launchy might not be for everybody - but I expect to
use fifteen or twenty different programs today, and they are not necessarily
the same fifteen or twenty that I used yesterday.  So until I got hooked on
Launchy, I was wasting a lot of time poking around the Start Menu.  Since
using Launchy,  I've had to find other ways to waste time...

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


Re: [Tutor] Obtaining image date of creation

2007-11-14 Thread Marc Tompkins
Thus spake Roy Chen:

> Hello,
>
> I would like to write a simple script that would rename a bunch of
> photos according to their creation date, i.e. the date which the
> photo was taken.
>
> Is there a way to use Python to obtain that information from the
> image file, or is that information not stored in the file?
>

What you're looking for is called EXIF, which stands for Exchangeable Image
File Format.
A good place to start would be http://www.exif.org  (or maybe Google, now
that you know the name of the format...)
Without having researched very far, I would guess that a lot of the familiar
MP3 tag-manipulation routines floating around out there could be easily
modified to read EXIF data instead - or, perhaps there are already Python
EXIF libraries?

Have fun with that!


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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Thus spake Bart Cramer:

> I have a question... :
>
> >>> class A: pass
> ...
> >>> class B(object) : pass
> ...
> >>> dir(A)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
> What is the difference between classes A and B? The funny thing is, when I
> put these things into an array of length, say, a million, it turns out
> that
> class A eats about 184 bytes per instantiation, and class B a lot less
> (sic!): plm 50 bytes. How come?
>

class B is a "new-style' class, meaning that it inherits from a base,
pre-existing class (in this case "object", which is as basic and generic as
you can get!).  class A has to start from nothing, which is why it consumes
more memory yet has less functionality.  (As a very, very rough analogy,
imagine that you have thirty seconds to paint a sign.  Which would be more
efficient - freehand or a stencil?  Given time, you can achieve more
artistic results freehand, but the stencil gets you quick results.)

As I understand it, in Python 3000 (aka 3.0), new-style classes will be
mandatory.  As you can already see, they give you more bang for the buck, so
you might as well get used to using them now!

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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
I didn't mean that exactly literally - for goodness' sake, this is a
high-level, object-oriented, interpreted language!  We're not writing
machine language here.

What I did mean, and will probably still not express as clearly as I'd like,
is that when you create a "classic" class, lots of options remain unresolved
- slots vs. dict comes to mind - and Python needs to reserve extra space
accordingly.   About 134 extra bytes, it would appear.

On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> Marc Tompkins wrote:
>
> > class B is a "new-style' class, meaning that it inherits from a base,
> > pre-existing class (in this case "object", which is as basic and generic
> > as you can get!).  class A has to start from nothing, which is why it
> > consumes more memory yet has less functionality.
>
> I don't think it is really accurate to say that an old-style class
> "starts from nothing". It doesn't have an explicit base class but it
> does have all the old-style class machinery which is built in to Python.
>
> I don't know why new-style classes are smaller though. My guess is that
> it is because there was an opportunity to streamline the class structure
> based on experience.
>
> Kent
>



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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
I thought of an analogy I like better than my sign-painting one: ordering a
sandwich.
Imagine: you're at the deli, and your waitron asks what you want.  (Granted,
this is a silly example.)
  "Classic" order: "I'd like a sandwich with two slices of rye bread,
Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
grilled."
  "New-style" order: "Reuben, please."

Now, I speak not of the time and materials required to construct the
above-mentioned tasty treat - in my analogy, Python is the long-suffering
waitron, not the cook - but I gotta figure that the second option will take
less space to write on the check.  Perhaps about 134 bytes' worth.

For some reason I'm hungry now...

On Nov 15, 2007 11:22 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> Marc Tompkins wrote:
> > I didn't mean that exactly literally - for goodness' sake, this is a
> > high-level, object-oriented, interpreted language!  We're not writing
> > machine language here.
>
> Yes, I was thinking I should re-word my email, it was worded a bit too
> strongly...
>
> > What I did mean, and will probably still not express as clearly as I'd
> > like, is that when you create a "classic" class, lots of options remain
> > unresolved - slots vs. dict comes to mind - and Python needs to reserve
> > extra space accordingly.   About 134 extra bytes, it would appear.
>
> Still not sure I know what you mean. AFAIK old-style classes don't
> support slots, at least not user-defined slots. I do remember talk of
> new-style classes and properties allowing a much cleaner implementation
> of the class mechanisms, and it seems plausible that such generalization
> would lead to fewer options and streamlining of the class structure, but
> I don't know enough about the specifics to know if that is right.
>
> I poked around a bit in the source to see if I could figure it out but
> got tired of trying to sift through the header files...
>
> Kent
> >
> > On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]
> > <mailto:[EMAIL PROTECTED]>> wrote:
> >
> > Marc Tompkins wrote:
> >
> >  > class B is a "new-style' class, meaning that it inherits from a
> base,
> >  > pre-existing class (in this case "object", which is as basic and
> > generic
> >  > as you can get!).  class A has to start from nothing, which is
> why it
> >  > consumes more memory yet has less functionality.
> >
> > I don't think it is really accurate to say that an old-style class
> > "starts from nothing". It doesn't have an explicit base class but it
> > does have all the old-style class machinery which is built in to
> Python.
> >
> > I don't know why new-style classes are smaller though. My guess is
> that
> > it is because there was an opportunity to streamline the class
> structure
> > based on experience.
> >
> > Kent
> >
> >
> >
> >
> > --
> > www.fsrtechnologies.com <http://www.fsrtechnologies.com>
>
>


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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
And here's another reason to use new-style:  I forgot the sauerkraut!  Oh,
the horror!

On Nov 15, 2007 1:42 PM, Marc Tompkins <[EMAIL PROTECTED]> wrote:

> I thought of an analogy I like better than my sign-painting one: ordering
> a sandwich.
> Imagine: you're at the deli, and your waitron asks what you want.
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> grilled."
>   "New-style" order: "Reuben, please."
>
> Now, I speak not of the time and materials required to construct the
> above-mentioned tasty treat - in my analogy, Python is the long-suffering
> waitron, not the cook - but I gotta figure that the second option will take
> less space to write on the check.  Perhaps about 134 bytes' worth.
>
> For some reason I'm hungry now...
>
>
> On Nov 15, 2007 11:22 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> > Marc Tompkins wrote:
> > > I didn't mean that exactly literally - for goodness' sake, this is a
> > > high-level, object-oriented, interpreted language!  We're not writing
> > > machine language here.
> >
> > Yes, I was thinking I should re-word my email, it was worded a bit too
> > strongly...
> >
> > > What I did mean, and will probably still not express as clearly as I'd
> > > like, is that when you create a "classic" class, lots of options
> > remain
> > > unresolved - slots vs. dict comes to mind - and Python needs to
> > reserve
> > > extra space accordingly.   About 134 extra bytes, it would appear.
> >
> > Still not sure I know what you mean. AFAIK old-style classes don't
> > support slots, at least not user-defined slots. I do remember talk of
> > new-style classes and properties allowing a much cleaner implementation
> > of the class mechanisms, and it seems plausible that such generalization
> >
> > would lead to fewer options and streamlining of the class structure, but
> > I don't know enough about the specifics to know if that is right.
> >
> > I poked around a bit in the source to see if I could figure it out but
> > got tired of trying to sift through the header files...
> >
> > Kent
> > >
> > > On Nov 15, 2007 9:32 AM, Kent Johnson <[EMAIL PROTECTED]
> > > <mailto:[EMAIL PROTECTED]>> wrote:
> > >
> > > Marc Tompkins wrote:
> > >
> > >  > class B is a "new-style' class, meaning that it inherits from a
> > base,
> > >  > pre-existing class (in this case "object", which is as basic
> > and
> > > generic
> > >  > as you can get!).  class A has to start from nothing, which is
> > why it
> > >  > consumes more memory yet has less functionality.
> > >
> > > I don't think it is really accurate to say that an old-style class
> > > "starts from nothing". It doesn't have an explicit base class but
> > it
> > > does have all the old-style class machinery which is built in to
> > Python.
> > >
> > > I don't know why new-style classes are smaller though. My guess is
> > that
> > > it is because there was an opportunity to streamline the class
> > structure
> > > based on experience.
> > >
> > > Kent
> > >
> > >
> > >
> > >
> > > --
> > > www.fsrtechnologies.com < http://www.fsrtechnologies.com>
> >
> >
>
>
> --
> www.fsrtechnologies.com




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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Referring to the original post:

> >>> dir(B)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
>

On Nov 15, 2007 6:50 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> OK, the analogy is cute, but I really don't know what it means in
> Python. Can you give an example? What are the parts of an old-style
> class that have to be 'ordered' separately? How do you 'order' them
> concisely with a new-style class?
>
> Thanks,
> Kent
>
> Marc Tompkins wrote:
> > I thought of an analogy I like better than my sign-painting one:
> > ordering a sandwich.
> > Imagine: you're at the deli, and your waitron asks what you want.
> > (Granted, this is a silly example.)
> >   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> > Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> > grilled."
> >   "New-style" order: "Reuben, please."
> >
> > Now, I speak not of the time and materials required to construct the
> > above-mentioned tasty treat - in my analogy, Python is the
> > long-suffering waitron, not the cook - but I gotta figure that the
> > second option will take less space to write on the check.  Perhaps about
> > 134 bytes' worth.
>



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


Re: [Tutor] Memory consumption question

2007-11-15 Thread Marc Tompkins
Sorry, sloppy cutting and pasting.  Should be:

Referring to the original post:
>
> > >>> dir(A)
> > ['__doc__', '__module__']
> > >>> dir(B)
> > ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> > '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
> >
> >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Read-ahead for large fixed-width binary files?

2007-11-16 Thread Marc Tompkins
I've been writing a lot of utility programs for my clients who are
users of a certain legacy database application - exporting, reporting,
pretty label printing, etc.  The database is normalized into 45 files,
each of which contains fixed-length records (ranging from 80 bytes to
1024).  A few of those files contain relatively few records, while
others - depending how long the users have worked with the application
- may contain millions of records; the transaction file is generally
the largest and consists of 256-byte records.

(Before anybody asks, yes!  I know that the best way to do this would
be to use the database engine that created the files.  Unfortunately,
that's not really an option.)
I am NOT writing back to the data file.

I seem to have two alternatives - read the file one record at a time
(which means I spend a ridiculous amount of time waiting for the
disk), or read the whole thing at once and process it in memory
(which, depending on the user's machine, will probably choke on a
250MB transaction file.)

My question is this: does anybody know of an equivalent to
"readlines(sizehint)" for non-delimited, binary files?  I've Googled
and Googled until I'm groggy, but I don't seem to find what I want.

Thanks!

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


Re: [Tutor] Read-ahead for large fixed-width binary files?

2007-11-16 Thread Marc Tompkins
OK, I feel quite foolish... almost immediately after hitting 'send' I
realized I can implement this myself, using 'read(bigsize)' -
currently I'm using 'read(recordsize)'; I just need to add an extra
loop around my record reads.  Please disregard...

On Nov 16, 2007 11:10 AM, Marc Tompkins <[EMAIL PROTECTED]> wrote:
> I've been writing a lot of utility programs for my clients who are
> users of a certain legacy database application - exporting, reporting,
> pretty label printing, etc.  The database is normalized into 45 files,
> each of which contains fixed-length records (ranging from 80 bytes to
> 1024).  A few of those files contain relatively few records, while
> others - depending how long the users have worked with the application
> - may contain millions of records; the transaction file is generally
> the largest and consists of 256-byte records.
>
> (Before anybody asks, yes!  I know that the best way to do this would
> be to use the database engine that created the files.  Unfortunately,
> that's not really an option.)
> I am NOT writing back to the data file.
>
> I seem to have two alternatives - read the file one record at a time
> (which means I spend a ridiculous amount of time waiting for the
> disk), or read the whole thing at once and process it in memory
> (which, depending on the user's machine, will probably choke on a
> 250MB transaction file.)
>
> My question is this: does anybody know of an equivalent to
> "readlines(sizehint)" for non-delimited, binary files?  I've Googled
> and Googled until I'm groggy, but I don't seem to find what I want.
>
> Thanks!
>
> --
> www.fsrtechnologies.com
>



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


  1   2   3   4   5   >