webbrowser failing

2005-09-20 Thread Thomas Thomas



Hi All,
 
import 
webbrowserurl=''webbrowser.open(url)
 
giving the error
 
Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC 
v.1200 32 bit (Intel)] on win32Type "help", "copyright", "credits" or 
"license" for more information.>>> ## working on region in file 
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py...Traceback (most 
recent call last):  File "", line 1, in ?  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py", line 3, in 
?    webbrowser.open(url)  File 
"C:\Python23\lib\webbrowser.py", line 43, in open    
get().open(url, new, autoraise)  File "C:\Python23\lib\webbrowser.py", 
line 250, in open    os.startfile(url)WindowsError: 
[Errno 2] The system cannot find the file specified: 
'http://www.cnn.com'>>> 
 
any help
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list

special charater in file causing trouble

2006-08-01 Thread Thomas Thomas



Hi All,
 
I need to process a file to create a hash.. the 
file contain a section
similar to 

string MetaDataPrompt = "Discovery No";
string MetaDataFieldName = "Discovery No";
string MetaDataType = "string";
string MetaDataValue = "£500";
 
everything was working fine until recently I got an error 
and found that it is due to "£" character 
and 
the error generated when processing the hash
ascii' codec can't decode byte 0xa3 in position 0: ordinal 
not in range(128)
I assume that this happening because the hash values I have 
are asciii encoded and I need to convert to unicode somehow..
i tried some googling and found http://www.jorendorff.com/articles/unicode/python.html
with not much luck in getting it work in my case.
metaValue=unicode('fieldValues[1], 
errors='ignore')
this will make the code work but i looses the "£" , I know that how it supposed to 
work
 
is there a way to 
handle such a situation  in python
code snippet
def _readXSTFilePoll(filename):    
metaHash={}    if 
exists(filename):   if 
isfile(filename):   
f = open(filename, "rb") 
   #infile = 
codecs.open(filename, "rb", 
encoding="utf-16")   
#text = 
infile.read()   
for line in 
f:  
if (line.find("string MetaData") 
>1): 
metaSubHash={} 
while(line.find("string 
MetaData")>1):    
fieldValues=line.split('"')    
extendedMetaKey=fieldValues[0].strip();    
metaValue=fieldValues[1]    
print 
metaValue    
metaKeySplit=extendedMetaKey.split(' 
')    
metaKeyList=metaKeySplit[1].split('MetaData')    
metaKey=metaKeyList[1]    
metaSubHash[metaKey]=metaValue    
if 
(metaKey=='Prompt'):   
hashKey=metaValue   
hashKey=hashKey.upper()    
line=f.next() 
metaHash[hashKey]=metaSubHash   
 
print "one section 
over"   print 
filename,metaHash 
   return 
metaHash     
else:   return 
{}   print "I 
cannot see a file of this name"     
else:    return {}
 
Thanks
-Thomas 
Thomas[EMAIL PROTECTED]Phone.  +64 
7 855 8478Fax.  +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

Zipping files/zipfile module

2006-08-01 Thread Thomas Thomas



Hi Stephen,
 
some code that I have been using for a similar purpose. 

 
def 
addFolderToZip(myZipFile,folder):    folder = 
folder.encode('ascii') #convert path to ascii for ZipFile 
Method    for file in 
glob.glob(folder+"/*"):    
if 
os.path.isfile(file):    
print 
file    
myZipFile.write(file, os.path.basename(file), 
zipfile.ZIP_DEFLATED)    
elif 
os.path.isdir(file):    
addFolderToZip(myZipFile,file)    
def createZipFile(filename,files,folders):    
curTime=strftime("__%Y_%m_%d", time.localtime())    
filename=filename+curTime;    print 
filename    zipFilename=utils.getFileName("files", 
filename+".zip")    myZipFile = zipfile.ZipFile( zipFilename, 
"w" ) # Open the zip file for writing     for file in 
files:    file = file.encode('ascii') 
#convert path to ascii for ZipFile 
Method    if 
os.path.isfile(file):    
(filepath, filename) = 
os.path.split(file)    
myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )    
    for folder in  folders:   
    
addFolderToZip(myZipFile,folder)      
myZipFile.close()    return (1,zipFilename)
 
 
 
(success,filename)=createZipFile(planName,files,folders);
 
 
hope it helps..
 
cheers
-Thomas 
Thomas[EMAIL PROTECTED]Phone.  +64 
7 855 8478Fax.  +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

Get age of a file/dir

2006-08-01 Thread Thomas Thomas



what abt 
 
os.path.getmtime or may be 
os.stat(filename)[ST_MTIME];
 
 cheers
-Thomas 
Thomas[EMAIL PROTECTED]Phone.  +64 
7 855 8478Fax.  +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

python unicode how to

2006-08-02 Thread Thomas Thomas



Hi all,
 
I have a file with special characters such as 
"£" etc.  I need to read the file into a list as unicode 
strings..
How can I do this.. I tried codecs 
 
import 
codecsfilename='d:/poll/test.XST'metaHash={}infile = 
codecs.open(filename, "r", encoding='utf-16')text = 
infile.read().split('\n')print text
 
I am getting the error
 
Traceback (most recent call last):  File 
"", line 1, in ?  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1928Lij.py", line 9, in 
?    text = infile.read().split('\n')  File 
"C:\Python23\lib\codecs.py", line 380, in read    return 
self.reader.read(size)  File "C:\Python23\lib\encodings\utf_16.py", 
line 48, in read    raise UnicodeError,"UTF-16 stream does 
not start with BOM"UnicodeError: UTF-16 stream does not start with 
BOM
 
also a sample file content will be

string MetaDataPrompt = "Discovery No";
string MetaDataFieldName = "Discovery No";
string MetaDataType = "string";
string MetaDataValue = "£500";
}
3{
string MetaDataPrompt = "comments";
string MetaDataFieldName = "Comments";
string MetaDataType = "string";
string MetaDataValue = "Energy Scope £500";
 
Thanks
Thomas
 
 
 
 
-Thomas 
Thomas[EMAIL PROTECTED]Phone.  +64 
7 855 8478Fax.  +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

encoding of a file

2006-08-03 Thread Thomas Thomas



Hi All,
 
how can I find the encoding to use to open a file.. 
I have a file with "£" chararcter..
is there some utility function in python that I can 
use
 
how can I know which encoding to use
 
f=codecs.open(filename, "r", 
encoding='iso-8859-1')
or
f=codecs.open(filename, "r", 
encoding='latin-1')
or
f=codecs.open(filename, "r", 
encoding='utf-8')
 
sys.defaultencoding gives ascii and I know that's 
not the one to use 
 
cheers
-Thomas 
Thomas[EMAIL PROTECTED]Phone.  +64 
7 855 8478Fax.  +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

Outlook Addin and py2exe: 2 problems

2006-09-25 Thread Thomas Thomas



I recenlty had the same issue, but clearing the 
build directory and rebuilding again fixed the issue for 
me
-- 
http://mail.python.org/mailman/listinfo/python-list

mapped drive missing when run as a service

2006-12-04 Thread Thomas Thomas
Hi All,

I have a python application which i run as a service.. 

 import win32api,string
drives=win32api.GetLogicalDriveStrings()
drives=string.splitfields(drives,'\000')
print drives

in the list of drives my mapped network drive is not showing when i run the 
application as a service.
I tried running the service as an administrator but with similar results..

any work around for this situation..

All i want is to access network files when run the application as a service..


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

UnicodeDecodeError

2005-05-04 Thread Thomas Thomas



Hi all 
 
 
import httplib, mimetypesimport 
os;
 
def 
get_content_type(filename):    return 
mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 
 
 
filepath= 'c:/Documents and 
Settings/Administrator/Desktop/tmp/test.pdf';f = open(filepath, 
"rb")data = "">f.close()
 
(filedir, filename) = 
os.path.split(filepath)filename=unicode(filename);#file = ('file', 
filename, data)  #This won't work will give a UnicodeDecodeError: 'ascii' 
codec can't decode byte 0xc7 in position 10: ordinal not in 
range(128)file = ('file', filename, 
'data'*100) #this will work fine#file = ('file', 'test.pdf', data) #This 
also works finefiles = [file]CRLF = '\r\n'L = []for (key, 
filename, value) in files:    L.append('Content-Disposition: 
form-data; name="%s"; filename="%s"' % (key, filename))    
L.append(value)body = CRLF.join(L)
 
print "ok"
 
can anyone put some light.. whats going 
behind..
 
cheers
Thomas
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

UnicodeDecodeError

2005-05-04 Thread Thomas Thomas
Hi all,

Forgot to mention I am using python 2.3 on windows.

I got the same error in mac panther .

if I remove the line
filename=unicode(filename);
it works fine sometimes

and if I encode the filename to ascii it works fine

Thanks
Thomas

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


urllib open error

2005-05-08 Thread Thomas Thomas




Hi all,
trying to download a file using urllib. Working fine on most 
machines.. failing in one..
 
Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC v.1200 
32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for 
more information.>>> import urllib;>>> 
url='';>>> 
f=urllib.urlopen(url);>>> 
f.read()'\nERROR: The requested URL 
could not be 
retrieved\n\nERROR\nThe 
requested URL could not be retrieved\n\n\nWhile 
trying to retrieve the URL:\nhttp://192.168.100.233/app/Assets/AssetDownload\n\nThe 
following error was 
encountered:\n\n\n\nConnection 
Failed\n\n\n\n\nThe system 
returned:\n    (110) Connection timed 
out\n\n\nThe remote host or network may be 
down.  Please try the request again.\nYour cache administrator is 
root. \n\n\n\nGenerated Mon, 09 May 2005 04:00:56 GMT by ipcop 
(Squid/2.4.STABLE6)\n\n'
if I copy the url to a browser it works fine.
suggest any debug techiniques so I can figure out whats 
going wrong.
Note: I have tried the same stuff and it's working fine on 
(windows 2000, XP and on mac)  not this particular windows 2000 
machine
 
Thanks in advance 
Thomas
 
-- 
http://mail.python.org/mailman/listinfo/python-list

urllib open error

2005-05-08 Thread Thomas Thomas



Hi 
 
It's seem to me that it works fine if I use 
hostname instead of ip address.
 
Note: Can anyone tell me how i reply to a question 
in thread, rather than starting a new one"
 
regards
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list

store data for search using python

2005-05-22 Thread Thomas Thomas
Hi all,

I have files & text associated with that files as data. what will be the best 
way to store them(like xml..), So that i can search in the text and get a 
list of files as result from a python application..

what kind of factors do i have to take into account if 
my prime concern is effective search.

Another suggestion was btree.. any more tips on that

regards
Thomas


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


python socket error

2005-06-01 Thread Thomas Thomas



Is there any getaround for the following error 
..
This happens when uploading large files 
say>50MB..
 
Python version 
Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC 
v.1200 32 bit (Intel)] on win32Type "help", "copyright", "credits" or 
"license" for more information.
 
Traceback (most recent call last):  File 
"", line 1, in ?  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 87, in 
?    
httpResult=httpUploadAsset('XX',filename,fileData)  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 12, in 
httpUploadAsset    
results=post_multipart(theURL,"/UploaderHttp/",fields,files);  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 30, in 
post_multipart    h.send(body)  File 
"C:\Python23\lib\httplib.py", line 579, in send    
self.sock.sendall(str)  File "", line 1, in 
sendallsocket.error: (10055, 'No buffer space available')
 
Any help
Thomas
 
 
--below the code sample that i am 
using
import osimport httplib, mimetypesimport 
os;def httpUploadAsset(serial,filename,data):    
_sessionID='xxx';    
_baseURL='http://xx.com'    fields = 
[('serial',serial),('sessionID',_sessionID)]    file = 
('file', filename, data)    files = 
[file]    
protocol,theURL=_baseURL.split('http://');    
results=post_multipart(theURL,"/UploaderHttp/",fields,files);    
print results;    return results;
 
def post_multipart(host, selector, fields, 
files):    """    Post fields and files to 
an http host as multipart/form-data.    fields is a sequence 
of (name, value) elements for regular form fields.    files 
is a sequence of (name, filename, value) elements for data to be uploaded as 
files    Return the server's response 
page.    """    content_type, body = 
encode_multipart_formdata(fields, files)    h = 
httplib.HTTP(host)    
h.set_debuglevel(0)    h.putrequest('POST', 
selector)    h.putheader('content-type', 
content_type)    h.putheader('content-length', 
str(len(body)))    h.endheaders()    
h.send(body)    errcode, errmsg, headers = 
h.getreply()    return h.file.read()
 
def encode_multipart_formdata(fields, 
files):    """    fields is a sequence of 
(name, value) elements for regular form fields.    files is a 
sequence of (name, filename, value) elements for data to be uploaded as 
files    Return (content_type, body) ready for httplib.HTTP 
instance    """     BOUNDARY = 
'--ThIs_Is_tHe_bouNdaRY_$'    CRLF = 
'\r\n'    L = []    for (key, value) in 
fields:    L.append('--' + 
BOUNDARY)    
L.append('Content-Disposition: form-data; name="%s"' % 
key)    
L.append('')    
L.append(value)    for (key, filename, value) in 
files:    L.append('--' + 
BOUNDARY)    
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, 
filename))    L.append('Content-Type: 
%s' % get_content_type(filename))    
L.append('')    
L.append(value)    L.append('--' + BOUNDARY + 
'--')    L.append('')    body = 
CRLF.join(L)
 
    content_type = 
'multipart/form-data; boundary=%s' % BOUNDARY    return 
content_type, body  def 
get_content_type(filename):    return 
mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 
def getFileData(filename):    
try:    f = file(filename, 
"rb")    data = 
"">    
f.close()    except 
IOError:    return['ERR']
 
    return ['OK',data]
 
filepath="c:/Documents and 
Settings/Administrator/Desktop/tmp/TM_A5_Bulk.pdf"  #file with size 
>50MBfileResult=getFileData(filepath)filename='TM_A5_Bulk.pdf'fileData=Noneif 
(fileResult[0]=='OK'): 
fileData=fileResult[1];httpResult=httpUploadAsset('XX',filename,fileData)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reading XST file

2006-05-02 Thread Thomas Thomas



Hi All,
 
I need extract the content of an XST file to 
dictionary object..
 
 
below is content of that file 

from work centre XST
 
[description 
XRX_DSCRPT_METADATA] field_0{ string 
MetaDataFieldName = "title"; string MetaDataPrompt = 
"Title"; string MetaDataType = 
"string"; string MetaDataValue = "Student 
Letter"; } field_1{ string 
MetaDataFieldName = "collectionname"; string 
MetaDataPrompt = "CollectionName"; string 
MetaDataType = "string"; string MetaDataValue = 
"999888777666"; } field_2{ string 
MetaDataFieldName = "summary"; string MetaDataPrompt 
= "Summary"; string MetaDataType = 
"string"; string MetaDataValue = 
"newman"; }
 
[description 
xrx_dscrpt_metadata]entry_1{  string 
MetaDataFieldName = "Job Reference";  string 
MetaDataPrompt = "Job Reference";  string 
MetaDataDefaultValue = "";  string 
MetaDataValue = 
"jgutbcfrvewf"; }entry_2{  string 
MetaDataFieldName = "Price Text";  string 
MetaDataPrompt = "Price Text";  string 
MetaDataDefaultValue = "";  string 
MetaDataValue = 
"758bf6"; }---
 
I want a hash to be build based on the content like resulthash 
={1:{"MetaDataFieldName" :"Price Text","MetaDataPrompt":"Price 
Text","MetaDataDefaultValue" :"","MetaDataValue":"758bf6",}, and so on for 
all ocuurences..}
 
 
I started using file objects  ..and was thinking is a better way to 
approach this scenario
 
from os.path import *filename="c:\sxtfile.xst";if 
exists(filename):   if 
isfile(filename):   f = open(filename, 
"rb")   for line in 
f.readlines():   
print line   else:   print 
"I cannot see a file of this name"   
 
 
 
 
cheers
 
-Thomas 
Thomas
 
phone  +64 7 855 
8478fax    +64 7 855 
8871
-- 
http://mail.python.org/mailman/listinfo/python-list

Reading Soap struct type

2006-05-09 Thread Thomas Thomas
Hi All,

I am receiving a hash below from my Soap Interface

: {'Field12value': ':C
F3Value', 'Field8': 'Price Text:price_text', 'Field9': 'Text with
File:file_text
', 'Field11value': ':CF2Value', 'Field7': 'Product Code:product_code',
'Field7va
lue': ':product_values', 'Field2': 'Job Reference:job_reference', 'Field3':
'Job
 Description:job_description', 'Field6': 'Campaign Name:campaign_name',
'Field10
value': ':CF1Value', 'Field6value': ':campaign_values', 'Field5':
'Keywords:keyw
ords', 'Field10': 'CF1Title:custom_field1', 'Field11':
'CF2Title:custom_field2',
 'Field12': 'CF3Title:custom_field3', 'Field13': 'CF4Title:custom_field4',
'Fiel
d14': 'Name:meta_filename', 'Field4': 'Display Name:display_name',
'Field13value
': ':CF4Value'}

How can i iterarte through it bcz when do try do something like
myHash.values()
I am getting the error
AttributeError: structType instance has no attribute 'values'

any help

Thomas

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


os listdir access denied when run as a service

2006-05-24 Thread Thomas Thomas
Hi All,

I am trying to access a mapped network drive folder. everything works fine
normally. But when i run the application as service I am getting the error

Traceback (most recent call last):
  File "docBoxApp.py", line 129, in ?
  File "core\PollFiles.pyc", line 332, in doPoll
  File "core\PollFiles.pyc", line 47, in createFileList
  File "core\PollFiles.pyc", line 25, in addFolderFiles
WindowsError: [Errno 5] Access is denied: 'G:\\DT Hot Folder test/*.*'


below is my code


def addFolderFiles(folder,filelist=[]):
logger=ServerInterface.getErrorLogger()
folder = folder.encode('ascii') #convert path to ascii for  File Method
for filename in os.listdir(folder):#line 25
file=os.path.join(folder,filename)
logger.error("loop file :"+file);
if os.path.isfile(file):
logger.error("is file :"+file);
if ((not (file.find(".tmp")>=0)) and (not
(file.find("~")>=0))):
filelist.append(file)
elif os.path.isdir(file):
logger.error("file is a directory :"+file);
addFolderFiles(file,filelist)

def createFileList(files,folders,filelist=[]):
logger=ServerInterface.getErrorLogger()
for file in files:
file = file.encode('ascii') #convert path to ascii for  File Method
if os.path.isfile(file):
   if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))):
filelist.append(file)

for folder in  folders:
logger.error("got a folder :"+folder);
logger.error("it was in the list :"+folders.__str__());
addFolderFiles(folder,filelist)
return (1,filelist)

anything I can do about this..


-
Thomas Thomas

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


Request opinion on web application framework

2005-12-04 Thread Thomas
Hello,

I am new to web programming but have some experience in technical 
programming in Python and other languages.  I need to build a networked 
program which I would like to first deploy on an intranet and later on the 
web which provides access to a few technical applications, two document 
management systems (simple types), a database search tool and maybe in the 
future a groupware client.  All data will be stored in a database.  I want a 
common portal for all of these functions.

Can anyone recommend a web framework for such an application?  I have looked 
a little and most seem to focus on CMS type applications instead of 
technical programs.

Any suggestions would be appreciated.

Regards. 


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


$6 into $1000ands this actually works!

2005-07-01 Thread Thomas
PAYPAL VERIFIES THAT THIS $6 INVESTMENT SCHEME IS 100% LEGAL AND IS A
BIG HIT THIS YEAR SEE THEIR NOTE BELOW OR ASK THEM DIRECTLY... THIS
SCHEME MIGHT TAKE 15-30 MINUTES AND JUST $6, BUT IT IS 100% WORTH IT TO
MAKE THOUSANDS SO QUICKLY. THIS IS NOT ANOTHER SCAM THAT
TAKES LOTS OF YOUR HARD EARNED MONEY; THIS IS A NO RISK INVESTMENT THAT
WILL MAKE YOU THOUSANDS OF DOLLARS VERY EASILY AND QUICKLY.

>From PayPal:

"Dear Member, it has come to our attention that there
is a paypal scheme floating around at the moment you
may have heard or seen the $6 scheme. You may have
even taken part in it well we have been asked a lot of
questions about this scheme the answer is yes it does
work and yes it is safe to use providing you follow the
rules it is legal and has made a big hit on the internet
this year. If you would like to take part in this scheme
or would like a bit more information then please see the
attached file that was kindly donated to us. Thank you for
using PayPal!"

TURN $6 INTO $15,000 IN ONLY 30 DAYS...HERES HOW!

You have most likely seen or heard about this project
on TV programs such as 20/20 and Oprah, or you may
have read about it in the Wall Street Journal. If not,
here it is below - revealed to you in step-by-step
detail. This program is by no means new. It has been
in existence in many forms for at least a decade. But
in the early days, it required a lot more time and
effort, as well as an investment of a few hundred
dollars. However, thanks to PayPal and the Internet,
the investment is now virtually ZERO! And what's more,
the entire process is FASTER, EASIER, and MORE
LUCRATIVE than it has EVER been! Below is the email
sent to me:

How to Turn $6 into $15,000 in 30 Days with PayPal
I WAS SHOCKED WHEN I SAW HOW MUCH MONEY CAME FLOODING INTO MY PAYPAL
ACCOUNT I turned $6 into $14,706 within the first 30 days of operating
the business plan that I am about to reveal to you free of charge. If
you decide to take action on the following instructions, I will
GUARANTEE that you will enjoy a similar return! STILL NEED PROOF? Here
are just 3 testimonials from the countless individuals who decided to
invest nothing more than $6 and half an hour of their time to
participate in this program:

"What an amazing plan! I followed your instructions
just 3 weeks ago, and although I haven't made 15 grand
yet, I'm already up to $9,135. I'm absolutely gob
smacked." -Pam Whittemore , Ohio

"Well, what can I say?... THANK YOU SO MUCH! I sent 40 e-mail's out
like you said and then I just forgot about the whole thing. To be
honest, I didn't really think anything would come of it. But when I
checked my paypal account a week later, there was over $5,000 in it!
After 30 days I now have over $11,000 to spend! I can't thank you
enough!"-Juan Tovar, NY, NY

"I was shocked when I saw how much money came
flooding into my paypal account. Within 3 weeks my
account balance has ballooned to $12,449. At first I
thought there had been some sort of error with my
account!" -Richard Barrie, Boulder, CO

The only things you will need are: An email address. A
Business PayPal account with at least $6 deposited in
it, and just 15 to 30 minutes of your time. This
program takes just half an hour to set up. After that,
there is absolutely no work whatsoever to do on your
part. You have absolutely NOTHING to lose, and there
is NO LIMIT to the amount of income you can generate
from this one single business program.

Let's get started, just follow the instructions exactly
as set out below and then prepare yourself for a HUGE
influx of cash over the next 30 days! Here's what you
need to do. . .

REQUIREMENTS

#1) an email address
#2) a Premier or Business PayPal account

STEP #1 - Setting up your FREE PayPal Account

It's extremely safe and very easy to set up a FREE
PayPal account! Copy and paste this to the address bar
https://www.paypal.com (notice the secure "https" within the link)

Be sure to sign up for a free PREMIER or BUSINESS
account (and not just a PERSONAL account) otherwise
you won't be able to receive credit card payments from
other people.

STEP #2 - Sending PayPal money "It is an undeniable
law of the universe that we must first give in order to receive."

Now all you have to do is send $1.00 by way of PayPal
to each of the six email addresses listed below.

Make sure the subject of the payment says... *PLEASE
PUT ME ON YOUR EMAIL LIST* (this keeps the program
100% legal.. so please don't forget!)

Note: (If you do not see the full email address for the 6 members, just
hit reply To this email and they will show up.)

(Just in case you still haven't opened your PayPal
account yet, use this link to open one in your name),
https://www.paypal.com

#1) [EMAIL PROTECTED]
#2) [EMAIL PROTECTED]
#3) [EMAIL PROTECTED]
#4) [EMAIL PROTECTED]
#5) [EMAIL PROTECTED]
#6) [EMAIL PROTECTED]

Remember, all of this is ABSOLUTELY LEGAL! You are
creating a service!

If you have any doubts, please refer to Title 18 Sec.
1302 & 1241 of the United States

Convert all images to JPEG

2004-12-28 Thread Thomas
Hi,

I got a bunch of different images of different types ( bmp, gif, png,
tiff etc ) and I want to convert them all to JPEGs using PIL. Is this
possible? When I try I get all sorts of errors, doing something like :

im = Image.open(srcImage) # might be png, gif etc, for instance
test1.png
im.thumbnail(size, Image.ANTIALIAS) # size is 640x480
im.save(targetName, "JPEG") # targetname is test1.jpg

produces an exception. Any clues?

Best regards,
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib2 file upload error

2005-04-27 Thread Thomas








 

 

import urllib2

URL = ''

FILE= 'c:/Documents and
Settings/Administrator/Desktop/Vousleve 1 .pps';

d = [ ('cmd', 'add-item'),

  ('protocol_version', '2.1'),

  ('userfile', open(FILE)),

    ]

req = urllib2.Request(URL, d)

try:

    u = urllib2.urlopen(req)

except urllib2.HTTPError, errobj:

    print "HTTPError:", errobj.code

else:

 buf = u.read()

 print "OK"

 

 

 

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32

Type "help", "copyright",
"credits" or "license" for more information.

>>> ## working on region in file
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1396n5Q.py...

Traceback (most recent call last):

  File "", line 1, in ?

  File
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1396n5Q.py", line 11, in ?

    u = urllib2.urlopen(req)

  File "c:\Python23\lib\urllib2.py", line
129, in urlopen

    return _opener.open(url, data)

  File "c:\Python23\lib\urllib2.py", line
326, in open

    '_open', req)

  File "c:\Python23\lib\urllib2.py", line
306, in _call_chain

    result = func(*args)

  File "c:\Python23\lib\urllib2.py", line
901, in http_open

    return self.do_open(httplib.HTTP, req)

  File "c:\Python23\lib\urllib2.py", line
888, in do_open

    h.send(data)

  File "C:\Python23\lib\httplib.py", line
576, in send

    self.sock.sendall(str)

  File "", line 1, in sendall

TypeError: sendall() argument 1 must be string or read-only
buffer, not list

 

 

 

 

Tried the script from http://fabien.seisen.org/python/urllib2_multipart.html
 also

 

Getting similar error..

 

Cheers

Thomas

 






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

uploading large file 100mb

2005-04-28 Thread Thomas








Hi I am getting the following error when uploading large
files…

 

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32

Type "help", "copyright",
"credits" or "license" for more information.

>>> ## working on region in file
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py...

Traceback (most recent call last):

  File "", line 1, in ?

  File
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py", line 79, in ?

   
post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FILE1','TM_A5_Bulk.pdf',data)]);

  File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py",
line 17, in post_multipart

    h.send(body)

  File "C:\Python23\lib\httplib.py", line 576, in
send

    self.sock.sendall(str)

  File "", line 1, in sendall

socket.error: (10055, 'No buffer space available')

>>> 

 

 

Thanks

Thomas

 

 

 

The code that I am using

--

import httplib, mimetypes

 

def post_multipart(host, selector, fields, files):

    """

    Post fields and files to an http host as
multipart/form-data.

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return the server's response page.

    """

    content_type, body = encode_multipart_formdata(fields,
files)

    h = httplib.HTTP(host)

    h.putrequest('POST', selector)

    h.putheader('content-type', content_type)

    h.putheader('content-length', str(len(body)))

    h.endheaders()

    #print body;

    h.send(body)

    errcode, errmsg, headers = h.getreply()

    return h.file.read()

 

def encode_multipart_formdata(fields, files):

    """

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return (content_type, body) ready for httplib.HTTP
instance

    """

    BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'

    CRLF = '\r\n'

    L = []

    for (key, value) in fields:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"' % key)

    L.append('')

    L.append(value)

    for (key, filename, value) in files:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"; filename="%s"' % (key, filename))

    L.append('Content-Type: %s' %
get_content_type(filename))

    L.append('')

    L.append(value)

    L.append('--' + BOUNDARY + '--')

    L.append('')

    body = CRLF.join(L)

    content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY

    return content_type, body

 

def get_content_type(filename):

    return mimetypes.guess_type(filename)[0] or
'application/octet-stream'

 

FILE= 'c:/Documents and
Settings/Administrator/Desktop/TM_A5_Bulk.pdf';

f = file(FILE, "rb")

data = "">

f.close()

post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FILE1','TM_A5_Bulk.pdf',data)]);






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

Logging data from Arduino using PySerial

2014-02-03 Thread Thomas
I've written a script to log data from my Arduino to a csv file. The script 
works well enough but it's very, very slow. I'm quite new to Python and I just 
wanted to put this out there to see if any Python experts could help optimise 
my code. Here it is:

import serial
import re
import csv
import numpy as np
import matplotlib.pyplot as plt

portPath = "/dev/ttyACM0"
baud = 9600
sample_time = 0.5
sim_time = 30


# Initializing Lists
# Data Collection
data_log = []
line_data = []

def map(x, in_min, in_max, out_min, out_max):
return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + 
out_min

# Establishing Serial Connection
connection = serial.Serial(portPath,baud)

# Calculating the length of data to collect based on the
# sample time and simulation time (set by user)
max_length = sim_time/sample_time

# Collecting the data from the serial port
while True:
data_log.append(connection.readline())
if len(data_log) > max_length - 1:
break

# Cleaning the data_log and storing it in data.csv
with open('data.csv','wb') as csvfile:
for line in data_log:
line_data = re.findall('\d*\.\d*',line) # Find all digits
line_data = filter(None,line_data)# Filter out empty strings
line_data = [float(x) for x in line_data] # Convert Strings to float

for i in range(1,len(line_data)):
line_data[i]=map(line_data[i],0,1023,0,5)

csvwrite = csv.writer(csvfile)
csvwrite.writerow(line_data)



plt.clf()
plt.close()
plt.plotfile('data.csv',(0,1,2),names=['time (s)','voltage2 (V)','voltage1 
(V)'],newfig=True)
plt.show()


I'd appreciate any help/tips you can offer.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logging data from Arduino using PySerial

2014-02-03 Thread Thomas
Wow...Thanks Chris! I really appreciate your suggestions (including the 
stylistic ones). I'll definitely be revising my code as soon as I find the 
time. As far as profiling goes, I've used timeit in the past but it's quite a 
pain going through any program block by block. I wish there were a program in 
which you could just toss in a script and it would spit out the bottlenecks in 
your code (with suggested performance improvements perhaps)...
-- 
https://mail.python.org/mailman/listinfo/python-list


webbrowser open failing

2006-07-25 Thread Thomas
Hi all,

I am getting an error using webbrowser open on mac 10.3 using python  
2.3.5

 >>> test=open("/Volumes/TINTZ;P3/DT Hot Folder  
test/Justin_Test.pDF","r")
 >>> type(test)

 >>> webbrowser.open("/Volumes/TINTZ;P3/DT Hot Folder  
test/Justin_Test.pDF","r")
Traceback (most recent call last):
   File "", line 1, in ?
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/webbrowser.py", line 43, in open
 get().open(url, new, autoraise)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/webbrowser.py", line 314, in open
 ic.launchurl(url)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/plat-mac/ic.py", line 235, in launchurl
 return _dft_ic.launchurl(url, hint)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/plat-mac/ic.py", line 202, in launchurl
 self.ic.ICLaunchURL(hint, url, 0, len(url))
MacOS.Error: (-673, 'no URL found')


cheers
Thomas

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


Re: webbrowser open failing

2006-07-26 Thread Thomas
HI

Thanks for the help.

I tried that , now getting a different error

 >>> test=open("/Volumes/TINTZ;P3/DT Hot Folder  
test/Justin_Test.pDF","r")
 >>> type(test)

 >>> webbrowser.open("file://Volumes/TINTZ;P3/DT Hot Folder  
test/Justin_Test.pDF")
Traceback (most recent call last):
   File "", line 1, in ?
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/webbrowser.py", line 43, in open
 get().open(url, new, autoraise)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/webbrowser.py", line 314, in open
 ic.launchurl(url)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/plat-mac/ic.py", line 235, in launchurl
 return _dft_ic.launchurl(url, hint)
   File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/plat-mac/ic.py", line 202, in launchurl
 self.ic.ICLaunchURL(hint, url, 0, len(url))
MacOS.Error: (-43, 'File not found')


it on shared network.. I found that its working fine on the files n the  
local hard drive..

cheers
Thomas

On 26/07/2006, at 6:39 PM, John McMonagle wrote:

> On Wed, 2006-07-26 at 17:09 +1200, Thomas wrote:
>> Hi all,
>>
>> I am getting an error using webbrowser open on mac 10.3 using python
>> 2.3.5
>>
>>>>> test=open("/Volumes/TINTZ;P3/DT Hot Folder
>> test/Justin_Test.pDF","r")
>>>>> type(test)
>> 
>>>>> webbrowser.open("/Volumes/TINTZ;P3/DT Hot Folder
>> test/Justin_Test.pDF","r")
>> Traceback (most recent call last):
>>File "", line 1, in ?
>>File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/webbrowser.py", line 43, in open
>>  get().open(url, new, autoraise)
>>File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/webbrowser.py", line 314, in open
>>  ic.launchurl(url)
>>File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/plat-mac/ic.py", line 235, in launchurl
>>  return _dft_ic.launchurl(url, hint)
>>File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/plat-mac/ic.py", line 202, in launchurl
>>  self.ic.ICLaunchURL(hint, url, 0, len(url))
>> MacOS.Error: (-673, 'no URL found')
>
> Try opening a file-type URL:
>
> eg:
> webbrowser.open("file://Volumes/TINTZ;P3/DT")
>
> No need for the 'r' argument to open.
>
> Syntax is:
>
>  webbrowser.open(url [, new])
>
> If new is True a new browser window is opened.
>
>
>
> -- 
> This message has been scanned for viruses and
> dangerous content by MailScanner, and is
> believed to be clean.
>
>

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


sorted

2006-08-18 Thread thomas
Hi NG

I what to used the sorted function, and im getting this error

Traceback (most recent call last):
   File "F:\home\thomas\src\guisample\test1.py", line 59, in ?
 main()
   File "F:\home\thomas\src\guisample\test1.py", line 31, in main
 sorted(cords, key=operator.itemgetter(1))
NameError: global name 'sorted' is not defined

what do I needs to import, to use this function ?

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


Re: sorted

2006-08-18 Thread thomas
Dennis Lee Bieber skrev:
> On Fri, 18 Aug 2006 09:31:54 +0200, thomas <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
> 
>> I what to used the sorted function, and im getting this error
>>
>   
>> what do I needs to import, to use this function ?
>>
>   Uhm... the entire 2.4 version of Python?
> 
>   You don't mention what version you have, but sorted() is new with
> 2.4

Sorry

I am using 2.3.
So now I know what to do :)


Thanks for the quick answer

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


socket error on windows, working fine on mac

2005-05-01 Thread Thomas








I am getting socket error for large file transfer on windows
(100MB+) 

Working fine for files <50MB.

 

Everything is working fine on mac..

 

File "C:\Python23\lib\httplib.py", line 576, in
send

    self.sock.sendall(str)

  File "", line 1, in sendall

socket.error: (10055, 'No buffer space available')

 

 

cheers

Thomas

 

 

 

import httplib, mimetypes

 

def post_multipart(host, selector, fields, files):

    """

    Post fields and files to an http host as
multipart/form-data.

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return the server's response page.

    """

    content_type, body = encode_multipart_formdata(fields,
files)

    h = httplib.HTTP(host)

    h.set_debuglevel(0)

    h.putrequest('POST', selector)

    h.putheader('content-type', content_type)

    h.putheader('content-length', str(len(body)))

    h.endheaders()

    #print body;

    h.send(body)

    errcode, errmsg, headers = h.getreply()

    return h.file.read()

 

def encode_multipart_formdata(fields, files):

    """

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return (content_type, body) ready for httplib.HTTP
instance

    """

    BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'

    CRLF = '\r\n'

    L = []

    for (key, value) in fields:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"' % key)

    L.append('')

    L.append(value)

    for (key, filename, value) in files:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"; filename="%s"' % (key, filename))

    L.append('Content-Type: %s' %
get_content_type(filename))

    L.append('')

    L.append(value)

    L.append('--' + BOUNDARY + '--')

    L.append('')

    body = CRLF.join(L)

    content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY

    return content_type, body

 

def get_content_type(filename):

    return mimetypes.guess_type(filename)[0] or
'application/octet-stream'

 

 

import urllib2

import urllib2_file 

#URL = ''

FILE= 'c:/Documents and
Settings/Administrator/Desktop/TM_A5_Bulk.pdf';

f = file(FILE, "rb")

data = "">

f.close()

 

post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FILE1','TM_A5_Bulk.pdf',data)]);






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

UnicodeDecodeError

2005-05-05 Thread Thomas








Thanks a lot.. Fredrik..

 

That’s says it all..

 

Cheers

Thomas






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

urllib open error

2005-05-11 Thread Thomas








Hi All,

 

Just an update on my urllib open error..  It’s the proxy
setup on my machine which was causing the problem.

 

Note: soappy doesn’t use the proxy by default while
the urllib do..

 

 

Cheers

Thomas






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

source file for kalab's pycron & makezip

2005-05-18 Thread Thomas








Hi All,

 

I am trying to get the source files for pycron &makezip.

 

http://www.kalab.com/freeware/pycron/pycron.htm

 

I tried mailing a request to [EMAIL PROTECTED]
but no joy yet.

 

Cheers

Thomas






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

need help with win32com

2007-07-02 Thread Thomas
I want to be able to access an excel file and extract the code from
the macro that is in the file.  How can I do this?

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


XL-RPC Recipe

2007-07-18 Thread Thomas
Hi list!

I'm struggling with a recipe from the Python Cookbook (2nd ed.)
concerning XML-RPC. It's recipe 15.2 "Serving XML-RPC Requests", and
since I thought it's a popular book some other folks might have
discovered (and probably solved) the same issue.

The recipe provides server and client code, and I get an
error when trying the following client request:

print server.python_string.join(['I', 'like it!'], " don't ")

(In the server code the string name space is mapped into the
'python_string' member with "import string; self.python_string = string").

The error report says:

xmlrpclib.Fault: :method
"python_string.join" is not supported'>

This happens with all the string methods in
StringFunctions.python_string. Is there a general issue with mapping
name spaces into an RPC object? Or am I missing a major point here?

I tried all of this on a fairly up-to-date Linux with a stock
Python 2.5 (also tried with WinXP/cygwin/Python2.5.1 and with a
Stackless 2.5.1, always with same outcome, so I don't believe it's an
issue of a local installation).

Any hints?

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


Re: XL-RPC Recipe

2007-07-18 Thread Thomas
Ah, sorry, found the answer myself (not that I wasn't looking for it for
days...): I was aware that the recipe is online at ActiveState's site
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549), but I
didn't read all of the comments carefully:

KAMOSAWA Masao wrote on 2006/04/29 that the use of dotted functions is
disabled by default in the server (from Python 2.4 onwards). But it can
be enabled with:

server.register_instance(StringFunctions(), allow_dotted_names = True)

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


Can't install Turbogears (with pysqlite) on Windows

2007-01-31 Thread Thomas
Hi there!

Installing TurboGears out-of-the-box (egg-based) on Windows doesn't
work because I can't
compile the extensions needed for the required pysqlite (also egg-
based):

Installed c:\programme\python24\lib\site-packages\turbogears-1.0.1-
py2.4.egg
Processing dependencies for TurboGears[standard,testtools]>=1.0
Searching for pysqlite
Reading http://www.python.org/pypi/pysqlite/
Reading http://pysqlite.org/
Reading http://www.python.org/pypi/pysqlite/2.3.3
Best match: pysqlite 2.3.3
Downloading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/
pysqlite-2.3.3.tar.gz
Processing pysqlite-2.3.3.tar.gz
Running pysqlite-2.3.3\setup.py -q bdist_egg --dist-dir c:\temp
\easy_install-ovrxv0\pysqlite-2.3.3\egg-dist-tmp-0ynhfx
warning: no files found matching 'doc\*.html'
error: Setup script exited with error: Python was built with version
7.1 of Visual Studio, and extensions need to be built with the same
version of the compiler, but it isn't installed.

To get away without the need to compile the pysqltite extensions I
tried  to install the Windows-binary package of pysqlite manually
before installing TG this also doesn't work, because easy_install
doesn't know anything of my fresh installed pysqlite and tries to
install the egg from cheeseshop (with the above error . . .).

Any suggestions to get beyond this?
Is it possible to "tweak" the TG egg-installation so that it won't try
to "easy_install pysqlite"?
For the application I'm intending to build with TurboGears I don't
even need pysqlite :(

Thomas

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


Re: Can't install Turbogears (with pysqlite) on Windows

2007-01-31 Thread Thomas
The solution can be found here:
http://groups.google.com/group/turbogears/browse_thread/thread/2dc72464a48fde94

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


SWIG: C++ and Python/ vector

2008-11-14 Thread Thomas
Hi,

I have a C++-Class "compiled" with SWIG into a Python-Modul. It works
fine. But there's is a problem with the C++-Returntype vector.
If I call in my compiled Python-Module a certain method (from the C++-
Class) there is no vector as result - although the C++-Counterpart
returns a vector. The Python-Counterpart (the method) returns
only a string like this:

_15436785_p_vector (alike this)

What can I do?

Thanks for help.

o-o

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


Manipulating sys.path

2008-07-09 Thread Thomas

Hi all,

I want to manipulate sys.path outside of PYTHONPATH (environment) and 
sys.path.append() (programmatically).


A bit of background:
We're maintaining a small application that includes a couple of Python 
scripts. Over time, a decent amount of code has been forked into 
modules, so the overall file system layout of our kit looks like this:


tool/
  bin/
prog1.py
prog2.py
...
  lib/
pack1/
  mod1.py
  mod2.py
  ...

The issue I have is that I want to add the 'lib' directory to the module 
search path so that our programs prog1.py, prog2.py,... can find the 
modules pack1.mod1, pack1.mod2, ... But I want to keep this out of the 
program's source code which rules out statements like 
'sys.path.insert(0, "../lib")'. We also want to be minimal-invasive for 
the hosting environment, so no copying of 'lib' into the standard Python 
lib directories (like /usr/local/lib/python2.5/site-packages etc.), nor 
forcing the user to change his PYTHONPATH shell environment. It should 
be solved locally in our kit's directory tree.


I was thinking about putting code into a 'bin/__init__.py' file but 
that's only working for modules and not for executable scripts, right?! 
Then I came across the '.pth' files, but unfortunately they only seem to 
work in some standard paths (like the before mentioned 
/usr/local/lib/python2.5/site-packages), and not in the script directory 
(like 'bin' in my case) which is automatically added to sys.path.


Can anybody think of something that could be of help here?

Thanks,
Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relative Package Import

2008-07-09 Thread Thomas

Robert Hancock wrote:

mypackage/
  __init__.py
  push/
__init__.py
 dest.py
 feed/
   __init__py
subject.py

In subject.py I have
 from ..push import dest


There is no such thing as relative package imports. See 
http://www.python.org/doc/essays/packages.html


Thomas



But i receive the error:
  Caught exception importing module subject:
File "/usr/local/python/lib/python2.5/site-packages/pychecker/
checker.py", line 621, in setupMainCode()
  module = imp.load_module(self.moduleName, file, filename, smt)
File "subject.py", line 1, in ()
  from ..feed import dest
  ValueError: Attempted relative import in non-package

What am I missing?




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


Re: Relative Package Import

2008-07-10 Thread Thomas

Peter Otten wrote:

Thomas wrote:


Robert Hancock wrote:

mypackage/
  __init__.py
  push/
__init__.py
 dest.py
 feed/
   __init__py
subject.py

In subject.py I have
 from ..push import dest

There is no such thing as relative package imports. See
http://www.python.org/doc/essays/packages.html


Unless you are using Python 1.5 the following document is a bit more
relevant:

http://www.python.org/dev/peps/pep-0328/


Oups, thanks for the pointer. I thought the old doc was still valid... 
(gee, there should be forward references).


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


Re: a splitting headache

2009-10-16 Thread Thomas
On Oct 15, 9:18 pm, Mensanator  wrote:
> All I wanted to do is split a binary number into two lists,
> a list of blocks of consecutive ones and another list of
> blocks of consecutive zeroes.
>
> But no, you can't do that.
>
> >>> c = '001110'
> >>> c.split('0')
>
> ['', '', '1', '', '', '', '11', '']
>
> Ok, the consecutive delimiters appear as empty strings for
> reasons unknown (except for the first one). Except when they
> start or end the string in which case the first one is included.
>
> Maybe there's a reason for this inconsistent behaviour but you
> won't find it in the documentation.
>
> And the re module doesn't help.
>
> >>> f = '  1 2  3   4    '
> >>> re.split(' ',f)
>
> ['', '', '1', '2', '', '3', '', '', '4', '', '', '', '']
>
> OTOH, if my digits were seperated by whitespace, I could use
> str.split(), which behaves differently (but not re.split()
> because it requires a string argument).
>
> >>> ' 1  11   111 11    '.split()
>
> ['1', '11', '111', '11']
>
> That means I can use re to solve my problem after all.
>
> >>> c = '001110'
> >>> re.sub('0',' ',c).split()
> ['1', '11']
> >>> re.sub('1',' ',c).split()
>
> ['00', '', '0']
>
> Would it have been that difficult to show in the documentation
> how to do this?


PythonWin 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin'
for further copyright information.
>>> list('00101000101')
['0', '0', '1', '0', '1', '0', '1', '1', '1', '1', '0', '0', '1', '0',
'1']
>>>

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


Re: help to convert c++ fonction in python

2009-10-18 Thread Thomas
If you change your last line from:

print s

to:

print u

you'll get different results :)


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


Re: How convert string '1e7' to an integer?

2009-11-08 Thread Thomas
Just a curiosity, why does Python do this?

>>> l = [(base, int('1e7', base=base)) for base in range(15,37)]
>>> l
[(15, 442), (16, 487), (17, 534), (18, 583), (19, 634), (20, 687),
(21, 742), (22, 799), (23, 858), (24, 919), (25, 982), (26, 1047),
(27, 1114), (28, 1183), (29, 1254), (30, 1327), (31, 1402), (32,
1479), (33, 1558), (34, 1639), (35, 1722), (36, 1807)]
>>> l = ([base, int('1e7', base=base)] for base in range(15,37))
>>> l

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


Re: How to transmit a crash report ?

2010-02-23 Thread Thomas
On Feb 22, 9:27 pm, MRAB  wrote:
> Stef Mientki wrote:
> > hello,
>
> > in my python desktop applications,
> > I'ld like to implement a crash reporter.
> > By redirecting the sys.excepthook,
> > I can detect a crash and collect the necessary data.
> > Now I want that my users sends this information to me,
> > and I can't find a good way of doing this.
>
> > The following solutions came into my mind:
> > (most of my users are on Windows, and the programs are written in Python
> > 2.6)
>
> > 1. mailto:
> > doesn't work if the the user didn't install a default email client,
> > or if the user uses a portable email client (that isn't started yet)
> > Besides this limits the messages to small amounts of data.
>
> > 2.other mail options: smtp
> > AFAIK such a solution needs smtp authorization, and therefor I've to put
> > my username and password in the desktop application.
>
> Try reading the documentation for Python's smtplib module.
>
> You don't need to provide any password.
>
>
>
> > 3. http-post
> > Although post is also limited in size,
> > I could store information in cookies (don't know yet how), and cookies
> > are sent parallel to the post message.
> > On the server site I can use a small php script, that stores the
> > post-data, cookies and/or send's a (long) email.
>
> > are there better options ?- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

Try http://code.activestate.com/recipes/442459/
-- 
http://mail.python.org/mailman/listinfo/python-list


Updating values in a dictionary

2010-05-16 Thread Thomas
Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Updating values in a dictionary

2010-05-16 Thread Thomas

Chris

Wow, that was a very fast response.
Thank you, it works  (of course)...

Cheers

"Chris Rebert"  wrote in message 
news:mailman.264.1274032106.32709.python-l...@python.org...

On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])


All the columns refer to the very same row dict (`row` obviously).
Python doesn't do any copying unless you explicitly request it.

Try:
matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in 
range(-3,4,1)])


This way, the row-creation code gets called for each column and thus
fresh row dicts are created rather than all just referencing the exact
same one row dict.
Nested comprehensions may be hard to understand, so you may wish to
write it using a function instead:

def make_row():
   return dict([(x,0) for x in range(3)])

matrix = dict([(x,make_row()) for x in range(-3,4,1)])

See also 
http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list


Cheers,
Chris
--
http://blog.rebertia.com 


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


Find slope of function given empirical data.

2010-06-29 Thread Thomas
Hello all.

Trying to find slope of function using numpy.
Getting close, but results are a bit off. Hope someone out here can
help.

import numpy as np

def deriv(y):
x = list(range(len(y)))
x.reverse() # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = np.array(x) #to   [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
y = np.array(y) # x.reverse() is used to put point 0 at end of
list.
z = np.polyfit(x, y, 2)
print np.poly1d(z)
#  Returns:
# 2
#  3.142 x - 18.85 x + 35.13
#  2
# Should be closer to   3.142 x  - 6.283 +
10   
return [z[0] * 2, z[1]]

if __name__=='__main__':
# range(-6,5,1)
# y = 3.141592 * x ** 2 - 6.283184 * x + 10 for x in range(-6, 5,
1)
# 160.796416, 119.95572, 85.398208, 57.12388, 35.132736,
19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736
#
# y' = 6.283184 * x - 6.283184  for x in range(-6, 5, 1)
# -43.982288, -37.699104, -31.41592, -25.132736, -18.849552,
-12.566368, -6.283184, 0.0, 6.283184, 12.566368, 18.849552
#
z = deriv([160.796416, 119.95572, 85.398208, 57.12388, 35.132736,
19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736])
for x in range(-6,5,1):
print str(w(x)) + ',' ,
# Returns:
# -56.548656, -50.265472, -43.982288, -37.699104, -31.41592,
-25.132736, -18.849552, -12.566368, -6.283184, -1.06581410364e-14,
6.283184
# Should be:
# -43.982288, -37.699104, -31.41592, -25.132736, -18.849552,
-12.566368, -6.283184, 0.0, 6.283184, 12.566368, 18.849552
# Note that the range is offset by 2 positions




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


Re: Find slope of function given empirical data.

2010-06-30 Thread Thomas
On Jun 30, 3:28 am, Peter Otten <__pete...@web.de> wrote:
> Thomas wrote:
> > Trying to find slope of function using numpy.
> > Getting close, but results are a bit off. Hope someone out here can
> > help.
>
> You don't make it easy to understand your post. In the future please try to
> rely more on plain english than on lots of numbers and code that doesn't
> run.
>
>
>
>
>
> > import numpy as np
>
> > def deriv(y):
> >     x = list(range(len(y)))
> >     x.reverse()     # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> >     x = np.array(x) #        to   [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
> >     y = np.array(y) # x.reverse() is used to put point 0 at end of
> > list.
> >     z = np.polyfit(x, y, 2)
> >     print np.poly1d(z)
> >     #  Returns:
> >     #         2
> >     #  3.142 x - 18.85 x + 35.13
> >     #                              2
> >     # Should be closer to   3.142 x  - 6.283 +
> > 10   
>
> To add one more question mark: how did you find that alternative?
>
> Anyway, we can put both polynomials to a test:
>
> >>> import numpy as np
> >>> y = np.array([160.796416, 119.95572, 85.398208, 57.12388,
>
> 35.132736,19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736])>>> x = 
> np.arange(len(y), dtype=float)[::-1]
> >>> p1 = np.poly1d(np.polyfit(x, y, 2))
> >>> print p1
>
>        2
> 3.142 x - 18.85 x + 35.13>>> p2 = np.poly1d([3.142, -6.283, 10.0])
> >>> print p2
>
>        2
> 3.142 x - 6.283 x + 10
>
> Now calculate the sum of the squares:
>
> >>> np.sum((p1(x)-y)**2)
>
> 5.0683524299544787e-26>>> np.sum((p2(x)-y)**2)
>
> 33028.342907811333
>
> Conclusion: numpy's result is much better than what you suggest.
>
> Peter

As usual, thanks to all for putting me on the right track.

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


infinite recursion in pickle.load()

2009-07-01 Thread Thomas
we regularly pickle and unpickle data from the same script (mostly 
dictionaries).


sometimes, a file written this way cannot be unpickled with 
pickle.load(), due to an infinite recursion with __getattr__ in 
codecs.py. here is a python2.5 stack trace excerpt:


/usr/local/lib/python2.5/pickle.py in load(file)
   1403
   1404 def load(file):
-> 1405 return Unpickler(file).load()
   1406
   1407 def loads(str):

/usr/local/lib/python2.5/pickle.py in load(self)
891 while 1:
892 key = read(1)
--> 893 dispatch[key](self)
894 except _Stop, stopinst:
895 return stopinst.value

/usr/local/lib/python2.5/pickle.py in load_build(self)
   1248 state = stack.pop()
   1249 inst = stack[-1]
-> 1250 setstate = getattr(inst, "__setstate__", None)
   1251 if setstate:
   1252 setstate(state)

/usr/local/lib/python2.5/codecs.py in __getattr__(self, name, getattr)
328 """ Inherit all other methods from the underlying stream.
329 """
--> 330 return getattr(self.stream, name)
331
332 def __enter__(self):

/usr/local/lib/python2.5/codecs.py in __getattr__(self, name, getattr)
328 """ Inherit all other methods from the underlying stream.
329 """
--> 330 return getattr(self.stream, name)
331
332 def __enter__(self):

...

The last frame repeats ad infinitum.

'inst' in the third frame is a 

The problem is the same with cPickle.

This looks somewhat related to this Python issue, which is only about 
the exception reporting:

http://bugs.python.org/issue5508
(The title of the issue is the error you get when running our code in 
python2.6).


Any idea how to go about that?

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


Re: Style question -- plural of class name?

2013-05-09 Thread Thomas Rachel

Am 09.05.2013 02:38 schrieb Colin J. Williams:

On 08/05/2013 4:20 PM, Roy Smith wrote:


"A list of FooEntry's"  +1


Go back to school. Both of you...

That is NOT the way to build a plural form...


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


Re: object.enable() anti-pattern

2013-05-10 Thread Thomas Rachel

Am 10.05.2013 15:22 schrieb Roy Smith:


That's correct.  But, as described above, the system makes certain
guarantees which allow me to reason about the existence or non-existence
os such entries.


Nevertheless, your 37 is not a FD yet.

Let's take your program:


#include 
#include 
#include 
#include 

int main(int argc, char** argv) {
 int max_files = getdtablesize();
 assert(max_files >= 4);


Until here, the numbers 3 toll max_files may or may not be FDs.


 for (int i = 3; i < max_files; ++i) {
 close(i);
 }


Now they are closed; they are definitely no longer FDs even if they 
were. If you would use them in a file operation, you'd get a EBADF which 
means "fd is not a valid file descriptor".



 dup(2);



From now on, 3 is a FD and you can use it as such.


 char* message = "hello, fd world\n";
 write(3, message, strlen(message));
}




No, what I've done is taken advantage of behaviors which are guaranteed
by POSIX.


Maybe, but the integer numbers get or los their property as a file 
descriptor with open() and close() and not by assigning them to an int.



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


Re: What was the project that made you feel skilled in Python?

2013-05-20 Thread Thomas Murphy
Hi Demian,

Can I ask what you mean by working through the stdlib? As in writing
code pieces utilizing each module from the stdlib? Also, you're
talking about "patches" in the stdlib? Is there a separate library of
patches? Forgive me if I'm google-failing hard over here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Prepending string "@" to usernames

2013-05-24 Thread Thomas Murphy
Hi beloved list,

I'm having a dumb and SO doesn't seem to have this one answered. I was
sent a long list of instagram usernames to tag for a nightlife
announcement in this format(not real names(i hope))

cookielover93
TheGermanHatesSaurkraut
WhatsThatBoy932834

I'd like to turn this raw text into a list and prepend the @ symbol to
the front of each one, so they're good to go for pasting without me
having to manually add the @ to each one.

Here's where I got to:


raw_address = "cookielover93 TheGermanHatesSaurkraut WhatsThatBoy932834"
address_library = [raw_address.split()]
print address_library

for address in address_library:
final_address = "@" + str(address)
print final_address


However my output is:

[['cookielover93', 'TheGermanHatesSaurkraut', 'WhatsThatBoy932834']]
@['cookielover93', 'TheGermanHatesSaurkraut', 'WhatsThatBoy932834']


I know I'm iterating wrong. May I ask how?

--
Sincerely,
Thomas Murphy
Code Ninja
646.957.6115
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prepending string "@" to usernames

2013-05-24 Thread Thomas Murphy
> Maybe this is what you're looking for?
>
> raw_address = "cookielover93 TheGermanHatesSaurkraut WhatsThatBoy932834"
> address_library = raw_address.split()
> print address_library
>
> final_address = []
> for address in address_library:
> final_address.append("@" + str(address))
> print final_address
>
Exactly it. Thank you so much Dan. Perfect!



--
Sincerely,
Thomas Murphy
Code Ninja
646.957.6115
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prepending string "@" to usernames

2013-05-24 Thread Thomas Murphy
> Which can be tidily written as a list comprehension:
>
>   final_address = ['@' + address for address in raw_address.split()]
>
> -tkc
>
>
Ah! Thanks Tim…that tidiness is something I'm trying to head towards
in my own code. I'm trying to transition from the need to visually
write every little step out and write in these more powerful chunks.


--
Sincerely,
Thomas Murphy
Code Ninja
646.957.6115
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Piping processes works with 'shell = True' but not otherwise.

2013-05-29 Thread Thomas Rachel

Am 27.05.2013 02:14 schrieb Carlos Nepomuceno:

pipes usually consumes disk storage at '/tmp'.


Good that my pipes don't know about that.

Why should that happen?


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


Re: I just wrote my first Python program a guessing game and it exits with an error I get this.

2013-06-05 Thread Thomas Murphy
Goldstick which seems Jewish to me. I would think as a Gentile Heathen
Jesus save us this would project a need for a good sex life

*WAT*
*
*
*
*
Armando, are you understanding that input and raw_input make Python do very
different things, and this is dependent of the version of Python you're
using? Folks aren't being pedantic, it's critical to giving you a good
answer.


On Wed, Jun 5, 2013 at 3:59 PM, Armando Montes De Oca <
armandomontesdeoca...@gmail.com> wrote:

> Well I am replying to To whom it may concern at this point I am a bit
> lost. I posted all my code. I am not taking classes on this nor do I have a
> book I followed a guy on You Tube. I am a student but I heard Python is a
> good language to learn in conjunction with C++ and Perl for example. I have
> taken Visual Basic 2010 last semester so keep thinking for me if you like
> if not when I can get a Python book or lesson. Joel Goldstick seems the
> more "professorly" so far by telling me the right thing of I have not
> learned something yet. Also with a name like Goldstick which seems Jewish
> to me. I would think as a Gentile Heathen Jesus save us this would project
> a need for a good sex life.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Sincerely,
Thomas Murphy
Code Ninja
646.957.6115
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrong website loaded when other requested

2013-06-13 Thread Thomas Murphy
Chris,

I had never encountered George before today, and now my life is a little
bit better.

This and "help vampires" in one morning, today's shaping up well! (now if
this JSON would serialize with this #*@$ing angularJS Controller, but
that's for another list)


On Thu, Jun 13, 2013 at 10:28 AM, Chris Angelico  wrote:

> On Fri, Jun 14, 2013 at 12:23 AM, Νικόλαος Κούρας 
> wrote:
> > Please suggest something of why this happnes.
>
> You remind me of George.
>
> http://www.chroniclesofgeorge.com/
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Sincerely,
Thomas Murphy
Code Ninja
646.957.6115
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-26 Thread Thomas Rachel

Am 12.06.2013 03:46 schrieb Rick Johnson:

On Tuesday, June 11, 2013 8:25:30 PM UTC-5, nagia@gmail.com wrote:


is there a shorter and more clear way to write this?
i didnt understood what Rick trie to told me.


My example included verbatim copies of interactive sessions within the Python 
command line. You might understand them better if you open the Python command 
line and type each command in one-by-one. Here is an algoritm that explains the 
process:

open_command_window()
whilst learning or debugging:
 type_command()
 press_enter()
 observe_output()
 if self.badder.is_full:
 take_potty_break()
close_command_window()


with command_window():
   whilst learning or debugging:
  type_command()
  press_enter()
  observe_output()
  if self.badder.is_full:
  take_potty_break()

looks nicer.

SCNR


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


Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

trying out the enum34 module.

What I want to create is a subclass of enum.Enum that is also
based on ctypes.c_int so that I can better use enum instances
in ctypes api calls.

When I do this, I get a metaclass conflict:


>>> class MyEnum(ctypes.c_int, enum.Enum):
...FOOBAR = 0
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a 
(non-strict) subclass of the metaclasses of all its bases

>>>



When I do this, it does not work either:

>>> class MyEnum_meta(type(ctypes.c_int), type(enum.Enum)):
... pass
...
>>> class MyEnum(ctypes.c_int, enum.Enum):
... FOOBAR = 42
... __metaclass__ = MyEnum_meta
...
>>> MyEnum.FOOBAR
42
>>>

It should have printed ''.

Any ideas?

Thanks,
Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

Am 28.06.2013 17:16, schrieb Ethan Furman:

On 06/28/2013 03:48 AM, Thomas Heller wrote:

trying out the enum34 module.

What I want to create is a subclass of enum.Enum that is also based
on ctypes.c_int so that I can better use enum instances in ctypes
api calls.


Have you tried using enum.IntEnum?  If you were able to pass ints in
 before, IntEnum should work.


I'm sure that IntEnum works as expected, but I need enums that are
subclasses of ctypes.c_int (so that argument type checking and return
value conversions in ctypes api calls work).

Robert Kern:



enum.EnumMeta uses super() in its __new__() implementation but
_ctypes.PyCSimpleType doesn't. Thus, only
_ctypes.PyCSimpleType.__new__() gets a chance to run. Switching the
order of the two might work.



Robert found the problem but I'm unsure if there is a solution.
Also I'm unsure whether this is a bug in ctypes or in enum or if
they are simply incompatible.

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


Re: Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

Am 28.06.2013 17:25, schrieb Thomas Heller:

Robert Kern:



enum.EnumMeta uses super() in its __new__() implementation but
_ctypes.PyCSimpleType doesn't. Thus, only
_ctypes.PyCSimpleType.__new__() gets a chance to run. Switching the
order of the two might work.



Robert found the problem but I'm unsure if there is a solution.
Also I'm unsure whether this is a bug in ctypes or in enum or if
they are simply incompatible.


I forgot to mention that switching the order of metaclasses didn't work.

Thomas

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


Re: Is that safe to use ramdom.random() for key to encrypt?

2012-06-19 Thread Thomas Rachel

Am 18.06.2012 01:48 schrieb Paul Rubin:

Steven D'Aprano  writes:

/dev/urandom isn't actually cryptographically secure; it promises not to
block, even if it has insufficient entropy. But in your instance...


Correct. /dev/random is meant to be used for long-lasting
cryptographically-significant uses, such as keys. urandom is not.


They are both ill-advised if you're doing anything really serious.


Hm?


> In practice if enough entropy has been in the system to make a key with

/dev/random, then urandom should also be ok.


Right.


> Unfortunately the sensible

interface is missing: block until there's enough entropy, then generate
data cryptographically, folding in new entropy when it's available.


What am I missing? You exactly describe /dev/random's interface.


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


Re: Generator vs functools.partial?

2012-06-21 Thread Thomas Rachel

Am 21.06.2012 13:25 schrieb John O'Hagan:


But what about a generator?


Yes, but...


def some_func():
 arg = big_calculation()
 while 1:
 i = yield
 (do_something with arg and i)

some_gen = some_func()
some_gen.send(None)
for i in lots_of_items:
 some_gen.send(i)


rather

def some_func(it):
arg = big_calculation()
for i in it:
do_something(arg, i)

some_func(lots_of_items)


HTH,

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


Re: Filenames started with _(underscore) in Modules/ why?

2012-06-23 Thread Thomas Jollans

On 06/24/2012 02:54 AM, gmspro wrote:

There are some files whose filename is started with _(underscore). Why
are they started with
a underscore?


By convention, a leading underscore means private/internal.

A module with a leading underscore is typically an implementation detail 
of another module with a public API, and should be ignored.


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


Executing Python Scripts on Mac using Python Launcher

2012-06-25 Thread David Thomas
Hello,
This is my first post so go easy on me.  I am just beginning to program using 
Python on Mac.  When I try to execute a file using Python Launcher my code 
seems to cause an error in terminal, when I execute the exact same piece of 
code and run it in windows it seems to execute as exactly intended.
 How can I make my python script to open up correctly using Python Launcher?  I 
am running 10.7 on my Mac.  I would upload a photo with the error I get but I 
can't seem to find the upload feature in this group.

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


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-26 Thread David Thomas
I have installed Python 2.7.3 from Python.org also in Terminal it states that I 
have 2.7.3.
How can I execute the script from Terminal?  I've tried typing python into the 
window and then dragging the file to terminal but I get a syntax error.  Sorry 
I am new to Python and just want to know how I can open such a file using 10.7.

Thanks

http://www.freeimagehosting.net/ilbqt
http://www.freeimagehosting.net/r5ars
On Monday, June 25, 2012 8:49:07 PM UTC+1, Benjamin Kaplan wrote:
> On Mon, Jun 25, 2012 at 11:19 AM, David Thomas  wrote:
> > Hello,
> > This is my first post so go easy on me.  I am just beginning to program 
> > using Python on Mac.  When I try to execute a file using Python Launcher my 
> > code seems to cause an error in terminal, when I execute the exact same 
> > piece of code and run it in windows it seems to execute as exactly intended.
> >  How can I make my python script to open up correctly using Python 
> > Launcher?  I am running 10.7 on my Mac.  I would upload a photo with the 
> > error I get but I can't seem to find the upload feature in this group.
> >
> > Thanks
> > --
> 
> You can't find the upload feature because this isn't a Google Group.
> It's a Usenet newsgroup that Google Groups provides access to that's
> also available as a mailing list. If you want to provide an image, use
> an image host and link to the image.
> 
> As to your question, I have a few questions of my own. What version of
> Python are you using? Is it the version included in Mac OS X,
> installed from a python.org binary, compiled by source, or installed
> through a package manager? What happens if you call the script from
> the command line instead of using the Launcher application?

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


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-26 Thread David Thomas
On Tuesday, June 26, 2012 6:37:42 PM UTC+1, Dave Angel wrote:
> On 06/26/2012 01:19 PM, David Thomas wrote:
> > I have installed Python 2.7.3 from Python.org also in Terminal it states 
> > that I have 2.7.3.
> > How can I execute the script from Terminal?  I've tried typing python into 
> > the window and then dragging the file to terminal but I get a syntax error. 
> >  Sorry I am new to Python and just want to know how I can open such a file 
> > using 10.7.
> >
> > Thanks
> 
> Assuming python is on your PATH within that terminal, you'd normally do
> something like:
> 
> cd  /fullpathtoscript  (the location of your script)
> python   myscript.py(or whatever your script is called)
> 
> 
> If that doesn't work for you, please be specific about what happens. 
> Best way to do that is to copy/paste the text (showing in terminal) 
> into your reply here.
> 
> Also, please don't top-post.  Put your new text AFTER the part you've
> quoted from earlier messages.
> 
> -- 
> 
> DaveA



On Tuesday, June 26, 2012 6:37:42 PM UTC+1, Dave Angel wrote:
> On 06/26/2012 01:19 PM, David Thomas wrote:
> > I have installed Python 2.7.3 from Python.org also in Terminal it states 
> > that I have 2.7.3.
> > How can I execute the script from Terminal?  I've tried typing python into 
> > the window and then dragging the file to terminal but I get a syntax error. 
> >  Sorry I am new to Python and just want to know how I can open such a file 
> > using 10.7.
> >
> > Thanks
> 
> Assuming python is on your PATH within that terminal, you'd normally do
> something like:
> 
> cd  /fullpathtoscript  (the location of your script)
> python   myscript.py(or whatever your script is called)
> 
> 
> If that doesn't work for you, please be specific about what happens. 
> Best way to do that is to copy/paste the text (showing in terminal) 
> into your reply here.
> 
> Also, please don't top-post.  Put your new text AFTER the part you've
> quoted from earlier messages.
> 
> -- 
> 
> DaveA



On Tuesday, June 26, 2012 6:37:42 PM UTC+1, Dave Angel wrote:
> On 06/26/2012 01:19 PM, David Thomas wrote:
> > I have installed Python 2.7.3 from Python.org also in Terminal it states 
> > that I have 2.7.3.
> > How can I execute the script from Terminal?  I've tried typing python into 
> > the window and then dragging the file to terminal but I get a syntax error. 
> >  Sorry I am new to Python and just want to know how I can open such a file 
> > using 10.7.
> >
> > Thanks
> 
> Assuming python is on your PATH within that terminal, you'd normally do
> something like:
> 
> cd  /fullpathtoscript  (the location of your script)
> python   myscript.py(or whatever your script is called)
> 
> 
> If that doesn't work for you, please be specific about what happens. 
> Best way to do that is to copy/paste the text (showing in terminal) 
> into your reply here.
> 
> Also, please don't top-post.  Put your new text AFTER the part you've
> quoted from earlier messages.
> 
> -- 
> 
> DaveA



On Tuesday, June 26, 2012 6:37:42 PM UTC+1, Dave Angel wrote:
> On 06/26/2012 01:19 PM, David Thomas wrote:
> > I have installed Python 2.7.3 from Python.org also in Terminal it states 
> > that I have 2.7.3.
> > How can I execute the script from Terminal?  I've tried typing python into 
> > the window and then dragging the file to terminal but I get a syntax error. 
> >  Sorry I am new to Python and just want to know how I can open such a file 
> > using 10.7.
> >
> > Thanks
> 
> Assuming python is on your PATH within that terminal, you'd normally do
> something like:
> 
> cd  /fullpathtoscript  (the location of your script)
> python   myscript.py(or whatever your script is called)
> 
> 
> If that doesn't work for you, please be specific about what happens. 
> Best way to do that is to copy/paste the text (showing in terminal) 
> into your reply here.
> 
> Also, please don't top-post.  Put your new text AFTER the part you've
> quoted from earlier messages.
> 
> -- 
> 
> DaveA

Hi 

On Tuesday, June 26, 2012 6:37:42 PM UTC+1, Dave Angel wrote:
> On 06/26/2012 01:19 PM, David Thomas wrote:
> > I have installed Python 2.7.3 from Python.org also in Terminal it states 
> > that I have 2.7.3.
> > How can I execute the script from Terminal?  I've tried typing python into 
> > the window and then dragging the file t

Re: Executing Python Scripts on Mac using Python Launcher

2012-06-26 Thread David Thomas
On Monday, June 25, 2012 7:19:54 PM UTC+1, David Thomas wrote:
> Hello,
> This is my first post so go easy on me.  I am just beginning to program using 
> Python on Mac.  When I try to execute a file using Python Launcher my code 
> seems to cause an error in terminal, when I execute the exact same piece of 
> code and run it in windows it seems to execute as exactly intended.
>  How can I make my python script to open up correctly using Python Launcher?  
> I am running 10.7 on my Mac.  I would upload a photo with the error I get but 
> I can't seem to find the upload feature in this group.
> 
> Thanks

Thank you for the fast response.  How can I tell if Python is in the same path 
as Terminal?  Is this located in the /usr folder?

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


2to6 ?

2012-06-27 Thread Thomas Heller

Is there a tool, similar to 2to3, which converts python2 code
to code using six.py, so that it runs unchanged with python2
*and* python 3?

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


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-27 Thread David Thomas
On Tuesday, June 26, 2012 10:48:22 PM UTC+1, Hans Mulder wrote:
> On 26/06/12 22:41:59, Dave Angel wrote:
> > On 06/26/2012 03:16 PM, Hans Mulder wrote:
> >> 
> >>
> >>  Python is an executable, and is
> >> typically located in a "bin" directory.  To find out where
> >> it is, type
> >>
> >> type python
> >>
> >> at the shell prompt (that's the first prompt you get if you
> >> open a Terminal window).
> >>
> >>
> > 
> > That's a typo.  You presumably meant:
> > 
> > which python
> > 
> 
> No, I meant:
> 
> $ type python
> python is /Library/Frameworks/Python.framework/Versions/2.7/bin/python
> 
> 'type' is a bash builtin that tells you how bash would interpret
> a command.  'which' is a separate program, which tells you how
> csh would interpret a command.  For a 'bash' user, 'type' is more
> accurate than 'which'.  For example, 'type' recognizes 'bash'
> builtins.
> 
> -- HansM

I have the following:

Is this why I keep getting an error using launcher?  Also to open the script in 
terminal do I need to put the following at the beginning of my script:  
#!/bin/python

On python.org it states to To run your script from the Terminal window you must 
make sure that /usr/local/bin is in your shell search path.

How can I make sure that the Python I have installed on my Mac is in my shell 
search path.

http://www.freeimagehosting.net/saskk

Thanks again and I am sorry for all the questions, I am just getting started on 
Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Python Scripts on Mac using Python Launcher

2012-06-27 Thread David Thomas
Thank you ever so much raw_input works fine.  Do you think I should stick with 
Python 2 before I go to 3?
I have a text book which is using 3 but I've been using an online tutorial 
which has been helping me lots, which uses version 2.
I found by just typing python then having a space and dragging the file from 
finder into terminal works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Recommend decent Computer Science books

2012-06-27 Thread David Thomas
Hi I know that this is a group about Python.  But I am just wondering if 
anybody can recommend any introductory/good books on Conputer Science.

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


Re: Recommend decent Computer Science books

2012-06-28 Thread David Thomas
Thanks everyone for the feedback really appreciate it especially the above post 
cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


Following syntax error in Mac OX10.7 Terminal

2012-06-28 Thread David Thomas
Hi,
I have the following error regarding a loop tutorial found on 
http://www.sthurlow.com/python/lesson04/

>>> a=0
>>> while a<10:
... a=a+1
  File "", line 2
a=a+1
^
IndentationError: expected an indented block

When I run Python IDE it seems to work fine.  The following code is:


a=0
while a<10:
a=a+1
print a 


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


Re: Following syntax error in Mac OX10.7 Terminal

2012-06-28 Thread David Thomas
Thank you very much I didn't realise that the indentation was important.  The 
IDE indents automatically whilst terminal doesn't. 
Thanks for pointing it out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re Following syntax error in Mac OX10.7 Terminal

2012-06-29 Thread David Thomas
On Thursday, June 28, 2012 6:30:42 PM UTC+1, Sergi Pasoev wrote:
> You just have to consider that indentation matters in Python, so you
> have to type the code in Python interpreter as you have written it
> below, that is, press Tab before each line when you are inside the
> 'while (or any other like for, if, with, etc.) block.
> 
> a=0
> while a<10:
> a=a+1
> print a 
> 
> I can guess from your message that you aren't aware of one very
> important Python feature, and maybe you also didn't willingly choose to
> learn Python2 instead of Python3 ? In this case I would advise you to
> consider both versions before choosing.

Hi yeah I'm currently learning python 2 at the moment and the tutorial that I 
am studying doesn't explain about indentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re Following syntax error in Mac OX10.7 Terminal

2012-06-29 Thread David Thomas
On Friday, June 29, 2012 4:21:56 PM UTC+1, MRAB wrote:
> On 29/06/2012 16:13, David Thomas wrote:
> > On Thursday, June 28, 2012 6:30:42 PM UTC+1, Sergi Pasoev wrote:
> >> You just have to consider that indentation matters in Python, so you
> >> have to type the code in Python interpreter as you have written it
> >> below, that is, press Tab before each line when you are inside the
> >> 'while (or any other like for, if, with, etc.) block.
> >>
> >> a=0
> >> while a<10:
> >> a=a+1
> >> print a
> >>
> >> I can guess from your message that you aren't aware of one very
> >> important Python feature, and maybe you also didn't willingly choose to
> >> learn Python2 instead of Python3 ? In this case I would advise you to
> >> consider both versions before choosing.
> >
> > Hi yeah I'm currently learning python 2 at the moment and the tutorial that
> > I am studying doesn't explain about indentation.
> >
> Really? Indentation is a basic feature of Python!

while {condition that the loop continues}:
{what to do in the loop}
{have it indented, usually four spaces}
{the code here is not looped}
{because it isn't indented}

Just discovered this in the tutorial further down.  I'm currently learning 
Python 2 because there seems to be a lot of tutorials out there covering Python 
2 rather than 3.

Thanks for the help this community is great for help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-06-30 Thread Thomas Jollans
On 06/30/2012 08:39 PM, Thomas 'PointedEars' Lahn wrote:
> Peter Otten wrote:
> 
>> If you spell it
>>
>> def is_valid_password(password):
>> return mud.minpass <= len(password) <= mud.maxpass
>>
>> it is even easier to see that you are performing an interval check.
> 
> This is probably a tautology around here, but *what* *a* *great* 
> *programming* *language*.
> 

Personally, I don't like this feature of the language. I find a ternary
operator that uses symbols that can also be binary operators confusing
and inconsistent with the way operators usually work/the way terms are
usually associated.

It has the charm of being something you'd "naturally" write in the
context of non-programming mathematics, at the cost of being very odd
indeed in the context of programming in general and Python in particular.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-06-30 Thread Thomas Jollans
On 06/30/2012 10:30 PM, Alister wrote:
> On Sat, 30 Jun 2012 21:38:58 +0200, Thomas Jollans wrote:
> 
>> On 06/30/2012 08:39 PM, Thomas 'PointedEars' Lahn wrote:
>>> Peter Otten wrote:
>>>
>>>> If you spell it
>>>>
>>>> def is_valid_password(password):
>>>> return mud.minpass <= len(password) <= mud.maxpass
>>>>
>>>> it is even easier to see that you are performing an interval check.
>>>
>>> This is probably a tautology around here, but *what* *a* *great*
>>> *programming* *language*.
>>>
>>>
>> Personally, I don't like this feature of the language. I find a ternary
>> operator that uses symbols that can also be binary operators confusing
>> and inconsistent with the way operators usually work/the way terms are
>> usually associated.
>>
>> It has the charm of being something you'd "naturally" write in the
>> context of non-programming mathematics, at the cost of being very odd
>> indeed in the context of programming in general and Python in
>> particular.
> 
> Surely this fits perfectly with the lines 1 & 7 in the zen of python 
> (import this)
> "Beautifull is better than ugly" and "Readability counts"
> 
> I find that construct both beautiful and readable, if it cannot be used 
> in the languages then that is their loss.

Are we quoting the Zen now?

Contra:

In re usual operator rules:
"Special cases aren't special enough to break the rules."

Which of the two comparisons is done first anyway?
"In the face of ambiguity, refuse the temptation to guess."

Speaking of two comparisons, no "and"!
"Explicit is better than implicit."

Then again, pro:

"Beautiful is better than ugly."
"Readability counts."
"[Although] practicality beats purity."


I can see the appeal. It's quite elegant in and of itself. However, I
find that in the context of the whole Python language, it's a bit of a
glitch and reduces elegance. (I'm probably in the minority on this one)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-06-30 Thread Thomas Jollans
On 06/30/2012 11:07 PM, Alain Ketterlin wrote:
> Thomas Jollans  writes:
> 
>>>>>> def is_valid_password(password):
>>>>>> return mud.minpass <= len(password) <= mud.maxpass
> 
>> Which of the two comparisons is done first anyway?
>> "In the face of ambiguity, refuse the temptation to guess."
> 
> There is no ambiguity. See the language reference:

Of course it's technically clearly defined, but the syntax isn't
explicit. To know what the order is (or whether there is an order!) one
has to consult the language reference (which shouldn't be necessary), or
make an educated guess, which would almost certainly be correct, but
we're supposed to refuse the temptation to guess, right?

> "Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN
> are comparison operators, then a op1 b op2 c ... y opN z is equivalent
> to a op1 b and b op2 c and ... y opN z, except that each expression is
> evaluated at most once."
> 
> The last restriction (single evaluation of involved expressions) makes
> this a bit more than raw syntactic sugar.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-06-30 Thread Thomas Jollans
On 06/30/2012 11:47 PM, Terry Reedy wrote:
> On 6/30/2012 5:35 PM, Thomas Jollans wrote:
>> On 06/30/2012 11:07 PM, Alain Ketterlin wrote:
>>> Thomas Jollans  writes:
>>>
>>>>>>>> def is_valid_password(password):
>>>>>>>>  return mud.minpass <= len(password) <= mud.maxpass
>>>
>>>> Which of the two comparisons is done first anyway?
>>>> "In the face of ambiguity, refuse the temptation to guess."
>>>
>>> There is no ambiguity. See the language reference:
>>
>> Of course it's technically clearly defined, but the syntax isn't
>> explicit. To know what the order is (or whether there is an order!) one
>> has to consult the language reference (which shouldn't be necessary), or
>> make an educated guess, which would almost certainly be correct, but
>> we're supposed to refuse the temptation to guess, right?
> 
> Python pretty consistently evaluates expressions and equal precedence
> operators left to right. 

Yes. My sole point, really, is that "normally", one would expect these
two expressions to be equivalent:

a < b < c
(a < b) < c

This is clearly not true. That's the inconsistency here with the rest of
the language. As soon as you read it as a ternary operator, the two
comparisons are logically simultaneous. Doing the left hand comparison
first is clearly the intuitive thing to do, but it's still, strictly
speaking, arbitrary. Intuitive, clearly defined, but arbitrary.

The ternary conditional operator is a different beast because its
sub-operators "if" and "else" aren't also binary operators, so it's
obvious that it's parsed differently.

> One really should learn that. No
> 'implementation defined' ambiguity.

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


Re: code review

2012-06-30 Thread Thomas Jollans
On 07/01/2012 01:25 AM, Chris Angelico wrote:
> On Sun, Jul 1, 2012 at 8:05 AM, Thomas Jollans  wrote:
>> Yes. My sole point, really, is that "normally", one would expect these
>> two expressions to be equivalent:
>>
>> a < b < c
>> (a < b) < c
>>
>> This is clearly not true.
> 
> Python has quite a few things like that, actually. The most noticeable
> for C programmers is:
> 
> a = b = c = d = e = 0
> 
> which in C is identical to
> 
> a = (b = (c = (d = (e = 0
> 
> because assignment is an expression, but in Python is equivalent to
> nothing because assignment is simply allowed to do multiple. Downside:
> *Only* simple assignment can be chained. Augmented assignment cannot:
> 
>>>> a+=10# That's fine.
>>>> a+=b+=10
>   File "", line 1
> a+=b+=10
>  ^
> SyntaxError: invalid syntax
>>>> a=b+=10
>   File "", line 1
> a=b+=10
> ^
> SyntaxError: invalid syntax
>>>> a+=b=10
>   File "", line 1
> a+=b=10
> ^
> SyntaxError: invalid syntax
> 
> 
> In C, these are all well-defined and valid, and are evaluated
> right-to-left, and do what you would expect. (And yes, it's handy at
> times to do this sort of thing.)
> 
> So it's not a special case for the comparison operators; it's a more
> general case that Python handles certain chains of operators as single
> entities, rather than breaking everything down into "OPERAND OPERATOR
> OPERAND" and evaluating one at a time. Is it better than/worse than C?
> Not really. It's a design choice and we code within it. (My personal
> preference is for the C style, as it makes for a more expressive
> language with less mental glitching, but as I say, that's personal
> preference.)

Nicely put. Of course it's not catastrophic, it's just a feature of
Python that I'm not particularly fond of.

Another operator with special chaining behaviour that occurred to me is
the tuple-building "," operator. This is a particularly interesting one
since the "," symbol is also used in other contexts where it is not an
operator, and the symbol can be considered an operator in the way it can
be in Python only in very few (if any) other programming languages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-01 Thread Thomas Jollans
On 07/01/2012 04:06 AM, Steven D'Aprano wrote:
> On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote:
> 
>> As soon as you read it as a ternary operator, 
> 
> Well that's your problem. Why are you reading it as a ternary operator? 
> It isn't one. It is a pair of chained binary operator.
> 
> How can you tell that it is a pair of binary operators, rather than a 
> single ternary operator?
> 
> 1) There are TWO operators, hence a pair, not a single ternary operator;
> 
> 2) each operator takes TWO arguments, not three.

This is simply wrong. The comparisons are not acting as binary operators.

> You can't just arbitrarily stick parentheses around parts of expressions
> and expect the result to remain unchanged. Order of evaluation matters:
>
> 2**3**4 != (2**3)**4
>
> Comparisons are no different. You can't just toss in some arbitrary
> brackets and expect the result to be the same. In the second case, the
> parentheses explicitly turn the comparison into the equivalent of this:

As Chris points out, 2**3**4 == 2**(3**4)

For any chain of actual binary operators, it is possible to place
brackets around binary sub-expressions such that the meaning of the
total expression stays the same. This is true of ALL infix-notated
strictly binary operators. This is not true of Python comparison operators.

If you're inclined to look at operators in terms of how many arguments
they take, then the inescapable conclusion is that a chain of N
comparison operators forms one single (N+1)-term operator because it
cannot be grouped into binary expressions without rephrasing the
expression using "and".

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


Re: code review

2012-07-01 Thread Thomas Jollans
On 07/01/2012 09:28 AM, Ben Finney wrote:
> Chris Angelico  writes:
> 
>> On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney  
>> wrote:
>>> Thomas Jollans  writes:
>>>
>>>> My sole point, really, is that "normally", one would expect these two
>>>> expressions to be equivalent:
>>>>
>>>> a < b < c
>>>> (a < b) < c
>>>
>>> What norm gives you that expectation? That's not how those operators
>>> work in mathematical notation. I know of no programming language
>>> that would give a newcomer to Python that expectation. So where is
>>> the norm you're referring to?
>>
>> C, SQL, REXX, and many other languages.
> 
> So, languages without strong typing then. In that case, I revise my
> statement: I know of no programming language with strong typing that
> would give a newcomer to Python the above expectation.
> 
> Since Python does have strong typing, norms about operations from
> weakly-typed languages should not be expected to apply.
> 
> (Incidentally, PostgreSQL was the SQL implementation I went to, and::
> 
> postgres=# SELECT (1 < 2) < 3;
> ERROR:  operator does not exist: boolean < integer
> LINE 1: SELECT (1 < 2) < 3;
>^
> HINT:  No operator matches the given name and argument type(s). You might 
> need to add explicit type casts.
> 
> So not all SQL implementations make the mistake of weak typing.)

I don't have PostgeSQL handy just now - what is the result of
(1 < 2 < 3) ? I bet it's the same error, which means the two are still
equivalent.

Look through the part of this thread about languages, and you will see
how unique Python is in this regard. You argument about strong typing
doesn't really hold: in Python, as in some other languages, bool is an
integer type, so it can actually be compared to numbers, so even if
Python used the same rules as Java, chaining comparison operators would
still be valid syntax (if a little silly in most cases)


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


Re: when "normal" parallel computations in CPython will be implemented at last?

2012-07-01 Thread Thomas Jollans
On 07/01/2012 07:51 PM, dmitrey wrote:
> hi all,
> are there any information about upcoming availability of parallel
> computations in CPython without modules like  multiprocessing? I mean
> something like parallel "for" loops, or, at least, something without
> forking with copying huge amounts of RAM each time and possibility to
> involve unpiclable data (vfork would be ok, but AFAIK it doesn't work
> with CPython due to GIL).
> 
> AFAIK in PyPy some progress have been done (
> http://morepypy.blogspot.com/2012/06/stm-with-threads.html )

As far as I can tell, there are no concrete plans to integrate
concurrency better, or get rid of the GIL, at the moment. To quote
http://wiki.python.org/moin/GlobalInterpreterLock

  """Getting rid of the GIL is an occasional topic on the python-dev
mailing list. No one has managed it yet."""

There are currently no open or accepted PEPs on the subject of concurrency.
http://www.python.org/dev/peps/

There is, of course, Stackless Python.
http://stackless.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when "normal" parallel computations in CPython will be implemented at last?

2012-07-01 Thread Thomas Jollans
On 07/01/2012 08:44 PM, Dan Stromberg wrote:
> IronPython, sadly, lacks a python standard library.


Beg pardon?

https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when "normal" parallel computations in CPython will be implemented at last?

2012-07-01 Thread Thomas Jollans
On 07/01/2012 09:28 PM, Dan Stromberg wrote:
> 
> 
> On Sun, Jul 1, 2012 at 11:58 AM, Thomas Jollans  <mailto:t...@jollybox.de>> wrote:
> 
> On 07/01/2012 08:44 PM, Dan Stromberg wrote:
> > IronPython, sadly, lacks a python standard library.
> 
> 
> Beg pardon?
> 
> 
> https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib
> 
> Perhaps things have changed.
> 
> When I last checked the situation, IronPython came with no standard
> library, but you could bolt one on that hadn't been tested well - IIRC,
> just a simple "import os" gave a traceback.  FePy was IronPython with a
> standard library and some degree of testing, but their emphasis was
> windows-only.
> 
> I'd be open to using FePy instead, and I might even call it IronPython,
> but I'm not in the habit of happily using software that is Windows only.
> 

That must have been quite a while ago?

I haven't tested it recently, but I'm fairly sure that IronPython
includes a Python standard library which works reasonably well, and it's
not Windows-only. (it works with Mono)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-02 Thread Thomas Jollans
On 07/02/2012 02:43 AM, Steven D'Aprano wrote:
> On Sun, 01 Jul 2012 09:35:40 +0200, Thomas Jollans wrote:
>> This is simply wrong. The comparisons are not acting as binary
>> operators.
> 
> Of course they are. Take this chained comparison:

Technically, yes - two-input operations are happening. Syntactically,
no. Read my post.

> 1) What is the operator in this expression? Is it < or == or something 
> else?

I think I've answered this - it's the combination.

> 2) What double-underscore special method does it call? Where is this 
> mysterious, secret, undocumented method implemented?
> 
> 3) Why do the Python docs lie that a < b == c is exactly equivalent to 
> the short-circuit expression (a < b) and (b == c) with b evaluated once?
> 
> 4) And how do you explain that the compiled byte code actually calls the 
> regular two-argument binary operators instead of your imaginary three-
> argument ternary operator?

In this context, I don't care what actually happens. I'm talking about
how the code can be parsed (by the generic reader, not necessarily the
python interpreter).


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


Re: code review

2012-07-02 Thread Thomas Jollans
On 07/02/2012 03:28 AM, Steven D'Aprano wrote:
> We *really did have* somebody arguing that chained comparisons are Bad 
> because you can't stick parentheses around bits of it without changing 
> the semantics. That was an actual argument, not a straw-man.

Ahem. It may have been sub-optimally phrased in a way that opened itself
up to attack, but I was arguing that Python comparisons operators are
anomalous because they're not associative.

(and, going back to the root of the argument, this makes them Bad
because "Special cases aren't special enough to break the rules.")


On Sun, 01 Jul 2012 21:50:29 -0400, Devin Jeanpierre wrote:

> On Sun, Jul 1, 2012 at 9:28 PM, Steven D'Aprano
>  wrote:
>> Technically, < in Python is left-associative: a < b < c first evaluates
>> a, not b or c. But it is left-associative under the rules of comparison
>> operator chaining, not arithmetic operator chaining.
>
> Left-associativity is when a < b < c is equivalent to (a < b) < c.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2to6 ?

2012-07-02 Thread Thomas Heller

Am 27.06.2012 20:06, schrieb Terry Reedy:

On 6/27/2012 10:36 AM, Thomas Heller wrote:

Is there a tool, similar to 2to3, which converts python2 code
to code using six.py, so that it runs unchanged with python2
*and* python 3?


Others have expressed a similar wish, but I do not know that anyone has
actually revised 2to3 to make a 2to6, or how feasible that would be.



Has nobody heard of, or even tried, modernize?

http://pypi.python.org/pypi/modernize


Thomas



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


Re: code review

2012-07-02 Thread Thomas Jollans
On 07/02/2012 08:22 PM, Rick Johnson wrote:
> Agreed. I wish we had one language. One which had syntactical
> directives for scoping, blocks, assignments, etc, etc...
> 
> BLOCK_INDENT_MARKER -> \t
> BLOCK_DEDENT_MARKER -> \n
> STATEMENT_TERMINATOR -> \n
> ASSIGNMENT_OPERATOR -> :=
> CONDITIONAL_IF_SPELLING -> IF
> CONDITIONAL_ELSE_SPELLING -> EL
> ...

You must be joking.

In C, for example, it is possible to "create your own language" by going

#define IF(cond) if (cond) {
#define ELSE } else {
#define ELIF(cond) } else if (cond) {
#define ENDIF }


and so on. There's a reason nobody does it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can i do python form post request?

2012-07-03 Thread Thomas Jollans
On 07/03/2012 07:08 AM, gmspro wrote:
> 
> form.html:
> 
>  
>  
> 
> 
> p.py:
> #!/usr/bin/python
> 
> #what to write here...
> 
> Both files are put in /var/www/ , now from http://localhost/form.html,
> if i click the submit button would i execute the p.py  and how can i get
> the value of textbox?
> 
> Any answer will be highly appreciated.
> Thanks in advanced.

First, you need to tell the web server to execute your Python script.
What you do next depends on how you've done that.

The simplest way is probably to pub p.py in your cgi-bin directory. This
could be in /var/www/cgi-bin or elsewhere, like /usr/lib/cgi-bin. You
may need to enable CGI, check the relevant documentation (or with the
admin).

When you've made sure the script is executed as a CGI script, you can
use the cgi module to get all the information you need.
http://docs.python.org/library/cgi.html

A better way to write web applications in Python is with WSGI. You can
run WSGI scripts in a number of ways, including CGI and other, more
efficient ways that integrate with the web server. Maybe somebody else
knows of a good tutorial on WSGI that they'll link here, otherwise, I'm
sure Google is your friend.

Thomas

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


Re: How can i do python form post request?

2012-07-03 Thread Thomas Jollans
On 07/03/2012 02:32 PM, gmspro wrote:
> @Thomas,
> 
>>First, you need to tell the web server to execute your Python script.
> What you do next depends on how you've done that.
> 
>>The simplest way is probably to pub p.py in your cgi-bin directory. This
> could be in /var/www/cgi-bin or elsewhere, like /usr/lib/cgi-bin. You
> may need to enable CGI, check the relevant documentation (or with the
> admin).
> 
>>When you've made sure the script is executed as a CGI script, you can
> use the cgi module to get all the information you need.
> http://docs.python.org/library/cgi.html
> 
>>A better way to write web applications in Python is with WSGI. You can
> run WSGI scripts in a number of ways, including CGI and other, more
> efficient ways that integrate with the web server. Maybe somebody else
> knows of a good tutorial on WSGI that they'll link here, otherwise, I'm
> sure Google is your friend.
> 
> I don't want to use CGI, i followed this example, this works fine,
> http://webpython.codepoint.net/wsgi_request_parsing_post
> 
> But the html is embeded there. But i want html form as a seperate file.
> How can i do it?

That makes absolutely no difference. Have you been able to run that
example script? They're using wsgi.simple_server, of course, but you
could start by removing that part and configuring mod_wsgi to run your
WSGI script. http://ubuntuforums.org/showthread.php?t=833766 could be
helpful, search the web for howtos on mod_wsgi to get started.

Once you have your web server running the WSGI code, the rest should be
trivial.

> 
> form.html:
> 
>  
>  
> 
> 
> Typing text when i click the submit button, browser prompts me to
> download the p.py file.
> That's not what i want. I want to execute the p.py file after click. Is
> it possible in WSGI.
> 
> I have installed: libapache2-mod-wsgi
> 
> Any answer will be highly appreciate.
> Thanks in advanced.
> 
> 
> 
> 


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


Re: Why site-packages?

2012-07-03 Thread Thomas Jollans
On 07/03/2012 11:34 PM, Dan Stromberg wrote:
> On Tue, Jul 3, 2012 at 9:04 PM, Ian Kelly  > wrote:
> 
> On Tue, Jul 3, 2012 at 2:40 PM, Dan Stromberg  > wrote:
> >
> > Why is it that so much 3rd party python code gets installed to
> > site-packages?
> 
> Because that's what site-packages is for?
> 
> 
> Agh.  But -why- is it because that's what it's for?
> 
> "Who made this rule"?

It's (reasonably) consistent with the way things are usually done on UNIX.

Libraries go in /usr/lib. That's all libraries, not just core system
libraries.

Similarly, Python modules go in /usr/lib/python. That's all Python
modules, not just the standard library. That means that you can use them
in scripts without faffing around because the interpreter will find
them, even if you're in a completely random directory.

The point of site-packages then is to make sure that user-installed
packages are cleanly separated from standard and distribution-installed
packages, similarly to the way /usr/local/ is used in general (and can
be used for Python packages, of course)

>  
> 
> > Even for things that are almost certainly going to be used by a single
> > application?
> >
> > Even for things you might only use once?
> >
> > Even for things that might require one version for one app, and
> another
> > version for another app?
> 
> For these types of uses, I suggest using virtualenv if you don't want
> to pollute your site-packages.  Or Python 3.3 with the new built-in
> virtual environment option.
> 
> Virtualenv is worth thinking about, but it kind of does the same thing,
> just less of it.
>  
> 
> > Why not stash an application's python modules in
> /usr/local/lib/[appname],
> > and stash a little frontend in /usr/local/bin that adds
> > /usr/local/lib/[appname] to sys.path?
> 
> What if you then write an application that you find needs two of these
> libraries?  You write yet another frontend that adds both of them to
> sys.path?
> 
> If it was intended to be reusable code, I'd think it -should- go in
> site-packages.
> 
> But so much code in site-packages isn't intended to be reusable.
> 
> And even for stuff that's reusable, there are advantages to just
> duplicating them for the purposes of each application, because you never
> know when one of them is going to need a different version from another.
> 
> If we weren't stashing so much stuff in site-packages, there probably
> wouldn't have been a desire for something like virtualenv.
>  
> 
> > Here's a thread on stackoverflow today asking why python starts up so
> > slowly, and making it clear that this is because so much stuff
> ends up in
> > site-packages:
> >
> 
> http://stackoverflow.com/questions/11318028/is-it-safe-to-use-pythons-s-option
> 
> I think you may be misunderstanding that thread.  They're saying that
> starting Python with the -S option (i.e. not automatically importing
> the site module) significantly cuts down on Python's startup time.
> 
> Yes...
>  
> 
> The site module has to process any .pth files in the site-packages,
> but apart from that, I think the actual amount of stuff in
> site-packages should be irrelevant.
> 
> Irrelevant to what?   More stuff in site slowing things down?  Are
> .pth's not correlated with more stuff in site-packages?  Aren't they
> actually a thing In site?
>  
> 
>  Nothing in site-packages is
> actually imported or otherwise processed until the application
> requests it.
> 
> Other than .pth's, apparently.
>  
> 
>  You could have a completely empty site-packages, or you
> could have 20 gigs of third-party packages, and the time to import
> site would be basically the same.
> 
> Well, I'd guess that a large directory would slow things down before
> causing filesystem complaints, but I see your point.
> 
> 
> 


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


Re: 2 + 2 = 5

2012-07-04 Thread Thomas Jollans
On 07/04/2012 09:37 PM, Paul Rubin wrote:
> I just came across this (https://gist.github.com/1208215):
> 
> import sys
> import ctypes
> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5))
> five = ctypes.cast(id(5), pyint_p)
> print(2 + 2 == 5) # False
> five.contents[five.contents[:].index(5)] = 4
> print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...)
> 
> Heh.  The author is apparently anonymous, I guess for good reason.
> 

I'm reminded of the swap(a,b) function I wrote a couple of years back.

http://blog.jollybox.de/archives/62-python-swap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import class from string

2012-07-04 Thread Thomas Jollans
On 07/04/2012 10:27 PM, Mariano DAngelo wrote:
> Hi I'm trying to create a class from a string 
> This is my code, but is not working

It would be helpful if you posted an error message. Then, we could know
what's actually going on.


> 'myshop.models.base'
> module_name, class_name = model.rsplit(".", 1)
> module = importlib.import_module(module_name)
> class_ = getattr(module, class_name)()

..^^

These brackets may be causing problems?

In principle, you're doing the right thing. This works for me:

Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> objname = 'os.path.join'
>>> module_name, member_name = objname.rsplit('.', 1)
>>> module = importlib.import_module(module_name)
>>> member = getattr(module, member_name)
>>> member

>>>

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


Re: Which way is best to execute a Python script in Excel?

2012-07-05 Thread Thomas Jollans
On 07/05/2012 09:26 AM, Karim wrote:
> Look at PyUNO from OpenOffice very large API:
> http://www.openoffice.org/api/docs
> 
> I use to create all my documention (Excell, Writer, etc...) on this API.

Note that this API is for OpenOffice, not Microsoft Excel. However, as
you probably know, you can open most Excel files in OpenOffice's Calc.

I urge you to consider LibreOffice, a fork of OpenOffice that is now
broadly considered its successor. Its API can also be used in Python
http://api.libreoffice.org/

If you want to program Microsoft Office, your only option is, as far as
I know, VBA, but it may be possible to call Python from VBA using the
Windows Script Host. I assume that the Windows Script Control uses this,
but I doubt that's much easier to use than the standard WScript API.
(then again, I wouldn't know)

All in all, if you're going to script Microsoft office, by far the
easiest way is to simply stick to VBA and forget about Python in this
particular environment. If it's an option, try LibreOffice.

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


Re: stuck in files!!

2012-07-06 Thread Thomas Jollans
On 07/06/2012 01:53 PM, Chirag B wrote:
> i want to kno how to link two applications using python for eg:notepad
> txt file and some docx file. like i wat to kno how to take path of
> those to files and run them simultaneously.like if i type something in
> notepad it has to come in wordpad whenever i run that code.
> 

Not possible.

(okay, within certain restrictions it might not be completely impossible)

What are you trying to achieve?

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


  1   2   3   4   5   6   7   8   9   10   >