Problems with running Python in Npp

2021-09-08 Thread Ricardo
   Hey Python and crew I'm having difficulties installing and running Python
   on my computer. I've seen plenty YouTube videos on how to set it up, but
   none of them have worked. Any help or guidance will be greatly
   appreciated.



   Sincerely,

   Ricardo



   Sent from [1]Mail for Windows



References

   Visible links
   1. https://go.microsoft.com/fwlink/?LinkId=550986
-- 
https://mail.python.org/mailman/listinfo/python-list


Embedding threaded Python

2005-04-12 Thread Ricardo
If I embed Python in a C app and the Python code is threaded, but the C
code isn't, do I need to call PyEval_InitThreads() ? - or do you only need
to do that if the C code is threaded ?
-- 
http://mail.python.org/mailman/listinfo/python-list


can't load an script from html...

2011-09-23 Thread Ricardo
Hi everyone
I'm trying to use the cgi library to create a python script and loading it from 
a web page. I have already done the necessary imports, and the default commands 
to receive data from "html" are written too. The final version is something 
like this:

#!/usr/bin/python

import subprocess
import cgi
import cgitb

cgitb.enable()

input = cgi.FieldStorage()

…. my code (do something with input)….


#printing the response

print "Content-Type: text/html"
print   
print "My title:"
print ""
print ""
print ….. bla bla …
print "%s"%theoutput
print ""

Besides, my call from my index.html is like this:

 


 

well, the thing is that when i do the call from the browser: 

http://localhost/index.html 
   |
  V
put the data and click on the "accept" button
   |
  V
http:/localhost/scripts/python_script.py

I only get the python_script.py as a plain test by response (the script printed 
on my browser). 
I have already changed the permissions for python_script.py. I have checked the 
import cgi,cgitb in the python shell (i am using v2.7) and they work fine. So, 
i don't know what it is going wrong here.

A little help please… any idea?
Thanks anyway for your time.


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


Building Python 2.5.6 on Ubuntu Natty

2011-07-12 Thread Ricardo Bánffy
Hi folks.

Has anyone succeeded in building Python 2.5.6 from sources in Ubuntu Natty?
I installed all the build dependencies and keep getting

running build_ext
/usr/include/sqlite3.h: version 3.7.4
Traceback (most recent call last):
  File "./setup.py", line 1545, in 
main()
  File "./setup.py", line 1540, in main
'Lib/smtpd.py']
  File "/tmp/Python-2.5.6/Lib/distutils/core.py", line 151, in setup
  File "/tmp/Python-2.5.6/Lib/distutils/dist.py", line 974, in run_commands
  File "/tmp/Python-2.5.6/Lib/distutils/dist.py", line 994, in run_command
  File "/tmp/Python-2.5.6/Lib/distutils/command/build.py", line 112, in run
  File "/root/Python-2.5.6/Lib/cmd.py", line 333, in run_command
del help[cmd]
  File "/tmp/Python-2.5.6/Lib/distutils/dist.py", line 994, in run_command
  File "/tmp/Python-2.5.6/Lib/distutils/command/build_ext.py", line 290, in
run
  File "./setup.py", line 97, in build_extensions
self.detect_modules()
  File "./setup.py", line 810, in detect_modules
sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
  File "/root/Python-2.5.6/Lib/posixpath.py", line 119, in dirname
return split(p)[0]
  File "/root/Python-2.5.6/Lib/posixpath.py", line 77, in split
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'
make: *** [sharedmods] Error 1

when I do "make test" and

Compiling /opt/python2.5/lib/python2.5/zipfile.py ...
make: *** [libinstall] Error 1

when I do "make install"

Any ideas?

-- 
Ricardo Bánffy
http://www.dieblinkenlights.com
http://twitter.com/rbanffy
-- 
http://mail.python.org/mailman/listinfo/python-list


dbf remove fields.

2016-04-22 Thread Ricardo Aguilar
Hi there i try to remove to fields in dbf table, how I can remove two
fields? 

 

I wanna to remove because I have this error "ValueError: could not convert
string to float: "  But I no need this field.

 

How I can remove this fields o ignore this ValueError? Any advice.

 

Ricardo Alfonso Aguilar Pineda - [email protected]
Depto. Sistemas 
867 711-5151 ext. 136

867 119 6506

 

 

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


Unicode conversion in 'print'

2005-01-13 Thread Ricardo Bugalho
Hello,
 I'm using Python 2.3.4 and I noticed that, when stdout is a terminal, the
'print' statement converts Unicode strings into the encoding defined by
the locales instead of the one returned by sys.getdefaultencoding().
However, I can't find any references to it. Anyone knows where it's
descrbed?

Example:

!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, locale

print 'Python encoding:', sys.getdefaultencoding()
print 'System encoding:', locale.getpreferredencoding()
print 'Test string: ', u'Olà mundo'


If stdout is a terminal, works fine
$ python x.py
Python encoding: ascii
System encoding: UTF-8
Test string:  Olà mundo

If I redirect the output to a file, raises an UnicodeEncodeError exception
$ python x.py > x.txt
Traceback (most recent call last):
  File "x.py", line 8, in ?
print 'Test string: ', u'Olà mundo'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: 
ordinal not in range(128)


-- 
Ricardo

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


Re: Unicode conversion in 'print'

2005-01-13 Thread Ricardo Bugalho
Hi, 
 thanks for the information. But what I was really looking for was
informaion on when and why Python started doing it (previously, it always
used sys.getdefaultencoding())) and why it was done only for 'print' when
stdout is a terminal instead of always.

On Thu, 13 Jan 2005 14:33:20 -0800, Serge Orlov wrote:

> Sure. It uses the encoding of you console. Here is explanation why it uses
> locale to get the encoding of console:
> http://www.python.org/moin/PrintFails
> 
-- 
Ricardo

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


Re: simultaneous multiple requests to very simple database

2005-01-18 Thread Ricardo Bugalho
On Tue, 18 Jan 2005 17:33:26 -0500, Eric S. Johansson wrote:

> When I look at databases, I see a bunch of very good solutions that are
> either overly complex or heavyweight on one hand and very nice and simple
> but unable to deal with concurrency on the other.  two sets of point
> solutions that try to stretch themselves and the developers to fit other
> application contexts.
> 

Have you considerded SQLite/pySQLite ?

-- 
Ricardo

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


Uploading images to imageshack.us with Python

2005-08-21 Thread Ricardo Sanchez
Hello,

I'm trying to upload images to http://imageshac.us via a Python script.


I have looked at the POST request with HTTPLiveHeaders Firefox
extension when I upload an image, but I can't figure what's wrong. (if
I disable the cookies in the browser, it still works, so it's not
that).

When I try to upload images with the script below, the server replies
with the following error:


Warning:  Division by zero in /home/image/www/index.php
on line 270

followed with the regular imageshack.us index.

Currently my code is the following one (I got it from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306):

# --
import urllib, httplib, mimetypes

def post_multipart(host, port, 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, port)

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 = '---13049614110900'

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'

params = [('MAX_FILE_SIZE', '3145728'), ('refer',
'http://reg.imageshack.us/v_images.php')]
files = [('fileupload', 'b.jpg', open('b.jpg').read())]

print open('a.jpg').read()

print post_multipart('proxy-a.mains.nitech.ac.jp', 8080,
'http://imageshack.us/index.php', params, files)
# --


Here is the HTTPLiveHeaders POST request:
# --
http://imageshack.us/index.php

POST http://imageshack.us/index.php HTTP/1.1
Host: imageshack.us
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10)
Gecko/20050716 Firefox/1.0.6
Accept:
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://imageshack.us/
Cookie: imgshck=4d590dbf69a8461ddff60153181b6c61;
img_gallery=e04663a565bc72348bfb2bdeec6d50a0%3Dp10100397vj.jpg%3Dimg185;
PHPSESSID=1bd06f468149071bd87f7f8e90142cff
Content-Type: multipart/form-data;
boundary=---114782935826962
Content-Length: 90772
-114782935826962
Content-Disposition: form-data; name="MAX_FILE_SIZE"

3145728
-114782935826962
Content-Disposition: form-data; name="refer"


-114782935826962
Content-Disposition: form-data; name="fileupload"; filename="a.jpg"
Content-Type: image/jpeg

ÿØÿà
HTTP/1.x 200 OK
Date: Mon, 22 Aug 2005 05:14:16 GMT
Server: Apache/2.0.54 (Unix)
X-Powered-By: PHP/4.4.0
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0,
pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html; charset=ISO-8859-1
# --


Any help would be appreciated.

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


Re: Uploading images to imageshack.us with Python

2005-08-21 Thread Ricardo Sanchez
I forgot to add that I'm behind a proxy, but I think that is
irrelevant.

If you are not behind a proxy replace this line:

print post_multipart('proxy-a.mains.nitech.ac.jp', 8080,
'http://imageshack.us/index.php', params, files)

with

print post_multipart('imageshack.us', 80, '/index.php', params, files)

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


Re: Uploading images to imageshack.us with Python

2005-08-22 Thread Ricardo Sanchez
Ok, I solved it with the unvaluable help of a nice guy in the #python
channel.

It is a studid as it gets, replaced

files = [('fileupload', 'b.jpg', open('b.jpg').read())]

by

files = [('fileupload', 'b.jpg', open('b.jpg', 'rb').read())]

because binary files are not opened correctly in Windows XP unless you
specify that they are so.

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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-12 Thread Ricardo Aráoz

El 12/11/13 01:46, Rick Johnson escribió:
No, Python modules can be poked, prodded, and violated by any pervert 
who can spell the word "import". Attribute values can be reassigned 
and state can be externally manipulated resulting in all types of 
undefined behaviors -- 


Nice!
My code, my responsibility, my business not yours.

that does not sound like an interface to me. So if python modules are 
importable everywhere, and mutable from everywhere, then python 
modules are merely addresses to a collection of global variables? And 
they're only interfaces "superficially"? So that leaves us with 
Python's current implementation of unofficial "global" variables 
implemented as "puesdo- interfaces" by module objects that are victims 
waiting to be violated. Interesting. IF IT WALKS LIKE A GLOBAL DUCK 
AND... 


Nice choice of words, "violated", "victims" Really conductive to a
balanced unprejudiced thought process.

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


Fwd: Re: Wrapping around a list

2013-11-28 Thread Ricardo Aráoz


El 27/11/13 07:46, [email protected] escribió:

Hello,
I am working on a problem (Bioinformatics domain) where all possible 
combinations of input string needs to be printed as sublist

For example:
Input string : "LEQN"
Output= "[L","E","Q","N"]["LE","EQ","QN","NL"] ["LEQ","EQN","QNE","NLE"]
["LEQN"]

The code i have written for this is as follows:

from itertools import chain, repeat, islice
from collections import deque

def sliding_window(iterable, n, fill=False, fillvalue=None):
 it = iter(iterable)
 if fill:
 it = chain(it, repeat(fillvalue, n - 1))
 w = deque(islice(it, n - 1))
 for x in it:
 w.append(x)
 yield w
 w.popleft()

input="LENQ"

lstinput= list(input)
lenlstinput=len(lstinput)
list1=[''.join(x) for x in sliding_window(lstinput, 2)]
list2= [''.join(x) for x  in sliding_window(lstinput, 3)]
list3= [''.join(x) for x in sliding_window(lstinput, 4)]



The output i get as follows:
List 1 is  ['LE', 'EN', 'NQ']   Should be ['LE','EN','NQ','QL']
  List 2 is  ['LEN', 'ENQ']  Should be ['LEN','ENQ','NQL','QLE']

So the question i am asking , how can i add wrapping around sublist in my 
sliding window function.

Thanks


Easy :

def getSlice(iterable, start, n):
lit = len(iterable)
end = start + n
return ''.join(iterable[i%lit] for i in range(start, end))


for n in range(1, len(inStr)+1):
[getSlice(inStr, i, n) for i in range(len(inStr))]


results :

['L', 'E', 'Q', 'N']
['LE', 'EQ', 'QN', 'NL']
['LEQ', 'EQN', 'QNL', 'NLE']
['LEQN', 'EQNL', 'QNLE', 'NLEQ']




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


Tree library - multiple children

2013-12-12 Thread Ricardo Aráoz

I need to use a tree structure. Is there a good and known library?
Doesn't have to be binary tree, I need to have multiple children per node.

Thanks

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


Re: Tree library - multiple children

2013-12-12 Thread Ricardo Aráoz

El 12/12/13 16:26, Neil Cerutti escribió:

On 2013-12-12, Ricardo Aráoz  wrote:

I need to use a tree structure. Is there a good and known library?
Doesn't have to be binary tree, I need to have multiple children per node.

Have you tried nested lists?

[[1, 2], [3, 4]

Can represent

  root
  /  \
   1-23-4

Python makes it very easy to manipulate such a structure. It
isn't clear that you need more than that yet.



And what if "2" has a couple of children? And one of those children has 
children of it's own?
You see, I will be needing multiple levels and will need to know if a 
node is already there at some level, and be able to add a child to that 
node on the fly, and to be able to traverse the tree in different ways, 
so I would eventually develop a tree library which is what I'm looking for.


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


Re: Tree library - multiple children

2013-12-12 Thread Ricardo Aráoz

El 12/12/13 15:56, Terry Reedy escribió:

On 12/12/2013 1:14 PM, Ricardo Aráoz wrote:

I need to use a tree structure. Is there a good and known library?


Search tools, both for the web and on pypi.python.org, are your friend.



I thought it was obvious that I've already looked around.
I'm using treelib right now but as my post says I was wondering if there 
was "a good and known library". I wanted to gather the previous 
experience of members of the list.


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


Re: Tree library - multiple children

2013-12-12 Thread Ricardo Aráoz

El 12/12/13 18:01, Mark Lawrence escribió:

On 12/12/2013 18:56, Terry Reedy wrote:

On 12/12/2013 1:14 PM, Ricardo Aráoz wrote:

I need to use a tree structure. Is there a good and known library?


Search tools, both for the web and on pypi.python.org, are your friend.



stackoverflow is another useful site to search and see also
http://kmike.ru/python-data-structures/.



Nice site, thanks. Unfortunately there are tries and all kind of search 
trees, but not simple unbalanced, multiple children trees.

Thanks.

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


Re: Tree library - multiple children

2013-12-13 Thread Ricardo Aráoz

El 13/12/13 18:05, [email protected] escribió:

I have this simple/stupid tree module:
https://github.com/abuchanan/bolts/blob/master/bolts/tree.py




Thanks, I'll check it.


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


Re: Editor for Python

2014-01-08 Thread Ricardo Aráoz

I use Spyder both in Windows as in Linux.
Pretty good programing environment, lots of features, simple enough, 
works on both platforms and it's free.



El 08/01/14 08:27, [email protected] escribió:

On Friday, 23 November 2001 04:13:40 UTC+5:30, MANUEL FERNANDEZ PEREZ  wrote:

Hello,
I'm looking for an editor for Python.I' m interested it works on Windows.Can
anybody help me?

Thank you

Manuel


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


Re: Python IDE.

2014-11-23 Thread Ricardo Aráoz


Spyder

El 20/11/14 a las 18:47, TP escibió:
On Thu, Nov 20, 2014 at 11:29 AM, Irmen de Jong 
mailto:[email protected]>> wrote:


PyCharm *is* free, if you fall in one of several categories.
See http://www.jetbrains.com/pycharm/buy/license-matrix.jsp

Even when you have to buy it, it is cheap (IMO) for what it offers.


"PyCharm Editions Comparison" [1] is a better comparison between the 
differences of the always free Community Edition and the Pro Edition 
of PyCharm.


[1] 
https://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html 







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


PyPI auth issues (Server response (401): basic auth failed)

2014-11-25 Thread Ricardo Bánffy
Hi folks.

I must be doing something wrong, but I (and the clever folks at the #python
channel) can't figure what.

I'm doing a:

python setup.py register -r pypitest

And getting the following in return

running register
running egg_info
writing Appengine_Fixture_Loader.egg-info/PKG-INFO
writing top-level names to Appengine_Fixture_Loader.egg-info/top_level.txt
writing dependency_links to
Appengine_Fixture_Loader.egg-info/dependency_links.txt
reading manifest file 'Appengine_Fixture_Loader.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no previously-included files matching '__pycache__' found under
directory '*'
warning: no previously-included files matching '*.py[co]' found under
directory '*'
writing manifest file 'Appengine_Fixture_Loader.egg-info/SOURCES.txt'
running check
Registering Appengine-Fixture-Loader to https://testpypi.python.org/pypi
Server response (401): basic auth failed

I've checked my auth credentials at the pypitest site, changed the password
to another value, changed the .pypirc file to reflect it and got the same
result.

~/.pypirc is as follows:

[distutils]
index-servers =
pypi
pypitest

[pypi]
repository: https://pypi.python.org/pypi
username: rbanffy

[pypitest]
repository: https://testpypi.python.org/pypi
username: rbanffy
password: [super-secret-password]

I then moved the .pypirc file and attempted to register the package at the
real PyPI site:

running register
running egg_info
writing Appengine_Fixture_Loader.egg-info/PKG-INFO
writing top-level names to Appengine_Fixture_Loader.egg-info/top_level.txt
writing dependency_links to
Appengine_Fixture_Loader.egg-info/dependency_links.txt
reading manifest file 'Appengine_Fixture_Loader.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no previously-included files matching '__pycache__' found under
directory '*'
warning: no previously-included files matching '*.py[co]' found under
directory '*'
writing manifest file 'Appengine_Fixture_Loader.egg-info/SOURCES.txt'
running check
We need to know who you are, so please choose either:
 1. use your existing login,
 2. register as a new user,
 3. have the server generate a new password for you (and email it to you),
or
 4. quit
Your selection [default 1]:
1
Username: rbanffy
Password:
Registering Appengine-Fixture-Loader to http://pypi.python.org/pypi
Server response (401): basic auth failed

So, what am I doing wrong?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyPI auth issues (Server response (401): basic auth failed)

2014-11-26 Thread Ricardo Bánffy
The second transcript was done without a .pypirc. That's why it asked for
credentials.

Can you post your .pypirc file (without password, of course) for comparison?

On Wed, Nov 26, 2014, 05:04 dieter  wrote:

> Ricardo Bánffy  writes:
> > I must be doing something wrong, but I (and the clever folks at the
> #python
> > channel) can't figure what.
> > ...
> > Registering Appengine-Fixture-Loader to http://pypi.python.org/pypi
> > Server response (401): basic auth failed
> >
> > So, what am I doing wrong?
>
> I find it strange that it says "http://pypi..."; rather
> than "https://pypi...";. The entries in your ".pypirc" have been
> for "https://pypi...";.
>
> The login entries in my ".pypirc" are in the section "[server-login]"
> (although, this is likely the easy case with only the production
> "PyPI" site).
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Restart the interactive python shell like in IDLE

2013-09-30 Thread Ricardo Abreu
On Thursday, June 11, 2009 1:48:42 AM UTC+2, Chris Rebert wrote:
> On Wed, Jun 10, 2009 at 12:01 PM, Matt Burson wrote:
> > Is there a way to reproduce the behavior of IDLE's restart shell ability by
> > using a function? I thought there would be since you can exit python by
> > executing the simple quit() function I thought there would be an equally
> > simple function name something like restart(). I'd prefer something like
> > this as opposed to having to exit the shell and then start it up again to
> > refresh it.
> 
> I believe IDLE itself implements the "restart" capability by killing
> and re-launching its Python interpreter subprocess, so it's not like
> it's using some hidden capability of Python to accomplish this.
> Is doing Ctrl+D, up-arrow, Enter really that hard? It's even fewer
> keystrokes than "restart()"...
> 
> Cheers,
> Chris
> -- 
> http://blog.rebertia.com

You might be launching python from something else other than a shell and it 
might be harder to re-launch it from there
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing: killing children when parent dies

2013-10-18 Thread Ricardo Aráoz

El 18/10/13 13:18, John Ladasky escribió:

What a lovely thread title!  And just in time for Halloween!  :^)


LOL
Couldn't that be construed as "sexism"?
Next we'll have a new long moronic thread about sexism and 
discrimination in mail subjects. Which will, as usual, leave a lot of 
satisfied egos and no result whatsoever.


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


Re: Python-list Digest, Vol 96, Issue 137

2011-09-24 Thread Ricardo Mansilla
On Saturday 24 September 2011 01:48:29 you wrote:
> Ricardo wrote:
> > Hi everyone
> > I'm trying to use the cgi library to create a python script and loading
> > it from a web page. I have already done the necessary imports, and the
> > default commands to receive data from "html" are written too. The final
> > version is something like this:
> > 
> > #!/usr/bin/python
> > 
> > import subprocess
> > import cgi
> > import cgitb
> > 
> > cgitb.enable()
> > 
> > input = cgi.FieldStorage()
> > 
> > …. my code (do something with input)….
> > 
> > 
> > #printing the response
> > 
> > print "Content-Type: text/html"
> > print
> > print "My title:"
> > print ""
> > print ""
> > print ….. bla bla …
> > print "%s"%theoutput
> > print ""
> > 
> > Besides, my call from my index.html is like this:
> >  
> >  
> >   
> >   
> > 
> >  
> >  
> > 
> > well, the thing is that when i do the call from the browser:
> > 
> > http://localhost/index.html
> > 
> >   V
> > 
> > put the data and click on the "accept" button
> > 
> >   V
> > 
> > http:/localhost/scripts/python_script.py
> > 
> > I only get the python_script.py as a plain test by response (the script
> > printed on my browser). I have already changed the permissions for
> > python_script.py. I have checked the import cgi,cgitb in the python shell
> > (i am using v2.7) and they work fine. So, i don't know what it is going
> > wrong here.
> > 
> > A little help please… any idea?
> 
> Is your webserver configured to allow cgi scripts? In the scripts
> directory? For Apache see
> 
> http://httpd.apache.org/docs/current/howto/cgi.html
> 
> Python also comes with a CGI Server. A quick-and-dirty setup goes like
> this:
> 
> $ cat cgi-bin/script.py
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> 
> import cgi
> import cgitb
> 
> cgitb.enable()
> 
> input = cgi.FieldStorage()
> 
> print "Content-Type: text/html"
> print
> print "My title:"
> print ""
> print ""
> print "Hello world"
> print ""
> $ chmod a+x cgi-bin/script.py
> $ python -m CGIHTTPServer
> Serving HTTP on 0.0.0.0 port 8000 ...
> 
> If you then point your browser to http://localhost:8000/cgi-bin/script.py
> you should see
> 
> Hello world
> 
> in the browser and (something like)
> 
> localhost - - [24/Sep/2011 08:41:27] "GET /cgi-bin/script.py HTTP/1.1" 200
> -
> 
> in the shell. Note that the script must be in cgi-bin (or htbin) unless you
> start the server with a custom script that modifies
> CGIHTTPRequestHandler.cgi_directories accordingly.


Thanks a lot, for your answer. Yes, i can run scripts from /cgi-bin/. Actually 
I follow you example and it works really well. I didn't know at all about this 
CGI server. 
I am doing the hole thing over python now, it's nice. 
Thanks again.

-- 
(...)Also, since that same law states that any system able to prove its 
consistency to itself must be inconsistent; any mind that believes it can 
prove its own sanity is, therefore, insane.(...) 
Kurt Gödel. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Motion Tracking with Python

2011-09-30 Thread Ricardo Mansilla
On Thursday 29 September 2011 21:16:52 you wrote:
> Hello,
> I have a neat Python project I'd like to share. It does real-time motion
> tracking, using the Python bindings to the OpenCV library:
> 
> http://derek.simkowiak.net/motion-tracking-with-python/
> 
> There is a YouTube video showing the script in action.
> 
> It's especially neat because my daughter and I worked together on this
> project. We used it to track her two pet gerbils, as part of her science
> fair project. She wrote her own (separate) Python script to read the
> motion tracking log files, compute distance and velocity, and then
> export those values in a CSV file. Like I say on the web page: "I’m
> convinced that Python is the best language currently available for
> teaching kids how to program."
> 
> I also use Python professionally, and it's worked out great every time.
> There's no job Python can't handle.
> 
> 
> Thanks,
> Derek Simkowiak
> http://derek.simkowiak.net

Hi, this is awesome!!
 I'm currently working in something similar, but I am having problems with 
getting data from the CCD (basically i don't know how to do it :), can you 
give me a tip for doing this? Or explain how you did it please?
I not a newbie at python but not as experienced as evidently you are.
Thanks a lot in advance.

-- 
(...)Also, since that same law states that any system able to prove its 
consistency to itself must be inconsistent; any mind that believes it can 
prove its own sanity is, therefore, insane.(...) 
Kurt Gödel. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Tweepy: Invalid arguments at function call (tweepy.Stream())

2011-10-31 Thread Ricardo Mansilla
Hi i'm trying to fetch realtime data from twitter using tweepy.Stream().
So I have tried the following...
After successfully authenticate using oauth:

auth = tweepy.OAuthHandler(...) (it works fine, i have my access_token.key
and secret)

i did:
streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(),
timeout='90')
and:
streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(),
timeout='90')

none of this works, it keeps giving me the same error:

Traceback (most recent call last):
File "", line 1, in
streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(),
timeout='60')
TypeError: *init*() takes at least 4 arguments (4 given)

then i have searched for the parameters of the function:

tweedy.streaming.Stream(login,password,Listener(),...etc)
but i thought this login and pass was the authentication method using in
the basic authentication not in the oauth case.
Now i'm really confused, a little help please?

pd: As you can see, i'm trying to get realtime data from twitter (and make
some further NLP with it), i have chose tweepy because the
dev.twitter.compage recommended it, but if you have any other
suggestion for doing this,
it will be welcomed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tweepy: Invalid arguments at function call (tweepy.Stream()) (Terry Reedy)

2011-10-31 Thread Ricardo Mansilla
Thanks a lot for your answer. I'm using python 2.7.2 and tweetpy 1.7

>>> help(tweepy)
Help on package tweepy:

NAME
tweepy - Tweepy Twitter API library

(...)

VERSION
1.7.1



and probably that is the problem, the link that you gave me refers to the
1.2 version page...
Anyway, i already have their IRC direction and i think it would be easier
to find support there.
Thanks again.

Ricardo Mansilla

ps: sometimes i get lazy about writing the whole link to a precise
direction which lacks of importance in my point; please, don't judge me for
my exquisite way of keep the attention in the correct place... :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Does py2app improves speed?

2011-11-23 Thread Ricardo Mansilla
Hi everyone..
My question is exactly as in the subject of This Mail. 
I have made a Python  script which is to slow and i have heard (and common 
sense also suggest) that if you use some libraries to "frozen" the script the 
performance improves substantially. So I need to know; is This a myth or it is 
a fact?
Thanks in advance for your time. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does py2app improves speed?

2011-11-24 Thread Ricardo Mansilla
Well, that's sad... I think Im gonna end getting back to C++ for This.  But 
anyway, thanks a lot for the quick answer... 
Bye.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does py2app improves speed?

2011-11-24 Thread Ricardo Mansilla
Most of méthods for improving the speed are related to efficient memory 
management and using specific structures for a specific tasks... But i have 
already optimized my code (which is very short actually) following all these 
rules and it is very slow yet. 
Do you think there is another way to do This? Probably i'm missing something 
here...

On 24/11/2011, at 07:38, Dave Angel  wrote:

> On 11/24/2011 08:26 AM, Ricardo Mansilla wrote:
>> Well, that's sad... I think Im gonna end getting back to C++ for This.  But 
>> anyway, thanks a lot for the quick answer...
>> Bye.
> Just because Py2app doesn't improve speed doesn't mean there aren't other 
> ways to gain speed, while still using the Python language for all or most of 
> the app. There have been lots of threads on the topic.
> 
> -- 
> 
> DaveA
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCon US 2012 sprints

2011-12-17 Thread Ricardo Bánffy
Hi folks.

Next March I'm planning to attend PyCon US (for the first time) and
stay for the sprints. I am not sure how they work, however. Are there
any "first-timer guide to PyCon sprints"?

-- 
Ricardo Bánffy
http://www.dieblinkenlights.com
http://twitter.com/rbanffy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on for loop

2013-03-04 Thread Ricardo Aráoz

El 04/03/13 09:18, newtopython escribió:

Hi all,

I'm super new to python, just fyi.

In the piece of code below, secretWord is a string and lettersGuessed is a 
list. I'm trying to find out if ALL the characters of secretWord are included 
in lettersGuessed, even if there are additional values in the lettersGuessed 
list that aren't in secretWord.

What this code is doing is only checking the first character of secretWord and 
then returning True or False. How do I get it to iterate through ALL of the 
characters of secretWord?

for character in secretWord:
 if character not in lettersGuessed:
 return True
return False

Thanks!

Ro


Indent the "return True" line so that it is inside the if clause.

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


Re: Determining if a file is locked in Windows

2006-10-20 Thread Ricardo Reyes
elake wrote:
> Larry Bates wrote:
> > elake wrote:
> > > I found this thread about a pst file in Windows being locked and I am
> > > having the same issue.
> > >
>

>
> The problem is that even though I catch the IOError it overwrites the
> dst file and makes it 0kb. This is going to be for backing these files
> up and it wont be good to overwrite the backup with a bad copy.
>

You can try to copy to a dst file that is not the backup file, but
instead it's in a temp location or with a temp name.

If the copy fails with IOError, just delete the new 0 bytes temp file.
If the copy doesn't fail, delete the old backup, rename the new temp
file to the destination name, and you are done. The rename part
shouldn't fail since you are operating in a new file that's not locked.
And for extra safety, don't erase the old backup before renaming the
new one, but rename to .bak.old or something like that.

Good luck.

Ricardo

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


Re: Determining if a file is locked in Windows

2006-10-20 Thread Ricardo Reyes
elake wrote:
> Larry Bates wrote:
> > elake wrote:
> > > I found this thread about a pst file in Windows being locked and I am
> > > having the same issue.
> > >
>

>
> The problem is that even though I catch the IOError it overwrites the
> dst file and makes it 0kb. This is going to be for backing these files
> up and it wont be good to overwrite the backup with a bad copy.
>

You can try to copy to a dst file that is not the backup file, but
instead it's in a temp location or with a temp name.

If the copy fails with IOError, just delete the new 0 bytes temp file.
If the copy doesn't fail, delete the old backup, rename the new temp
file to the destination name, and you are done. The rename part
shouldn't fail since you are operating in a new file that's not locked.
And for extra safety, don't erase the old backup before renaming the
new one, but rename to .bak.old or something like that.

Good luck.

Ricardo

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


a 32 bit number to integer

2006-01-24 Thread Ricardo Quesada
Hi,

  In python 2.0, this number was an integer:
0x88776655

  but in python 2.4 it is a long (every number > 0x7fff it is a long)

in python 2.4, is there a way to convert that number to a integer 
(notice that it only occupies 32 bits) ?


thanks,
riq.

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


Re: What is the "functional" way of doing this?

2007-07-30 Thread Ricardo Aráoz
> On Jul 30, 4:39 pm, Paul Rubin  wrote:
>> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
>>> Recursion is common in functional programming:
>>> def f(n, l=None):
>>> if l == None:
>>> l = []
>>> if n > 0:
>>> return f(n/26, l + [n%26])
>>> else:
>>> return l
>>> print f(1000)
>> Right, this is functional style, but quite painful in Python (no tail
>> recursion, and look at all that list copying).
> 

It might actually be :

def f(n):
if n > 0:
return ([n%26] + f(n/26))
else:
return []

Wouldn't that be ok?





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


Re: What is the "functional" way of doing this?

2007-07-31 Thread Ricardo Aráoz
Considering I am a beginner I did a little test. Funny results too. The
function I proposed (lists1.py) took 11.4529998302 seconds, while the
other one (lists2.py) took 16.141324 seconds, thats about 40% more.
They were run in IDLE from their own windows (F5).
Of course my little test may me wrong (just started with this language),
in which case I would appreciate any corrections, or comments.



lists1.py :
def f(n):
if n > 0:
return ([n%26] + f(n/26))
else:
return []

import time

start = time.time()
for x in range(1,100):
f(21)
end = time.time()

print end - start
---
lists2.py :
def f(n):
   def mseq(n):
  while n > 0:
 n,a = divmod(n, 26)
 yield a
   return list(mseq(n))

import time

start = time.time()
for x in range(1,100):
f(21)
end = time.time()

print end - start

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


Re: What is the "functional" way of doing this?

2007-07-31 Thread Ricardo Aráoz
Kept testing (just in case).
There was this other version of lists2.py (see below). So I created
lists3.py and lists4.py.
The resulting times are
lists1.py : 11.4529998302
lists2.py : 16.141324
lists3.py : 3.1713134
lists4.py : 20.983676

lists3.py is by far the better time, but it does not generate a list but
a generator object, as soon as you make it into a list (lists4.py) times
go up (I don't know why do they go up that much). Apparently the way you
use the conversion to a list, in the function(lists2.py) or in the loop
(lists4.py), makes a big difference. Anyway lists1.py is still the best
of the list generating times, and (in my view) the most elegant and easy
to understand expression of the algorithm.



lists1.py :
def f(n):
if n > 0:
return ([n%26] + f(n/26))
else:
return []

import time

start = time.time()
for x in range(1,100):
f(21)
end = time.time()

print end - start
---
lists2.py :
def f(n):
   def mseq(n):
  while n > 0:
 n,a = divmod(n, 26)
 yield a
   return list(mseq(n))

import time

start = time.time()
for x in range(1,100):
f(21)
end = time.time()

print end - start

lists3.py
def f(n):
if n>0:
yield n%26
for i in f(n/26):
yield i


import time

start = time.time()
for x in range(1,100):
f(21)
end = time.time()

print end - start

lists4.py
def f(n):
if n>0:
yield n%26
for i in f(n/26):
yield i


import time

start = time.time()
for x in range(1,100):
list(f(21))
end = time.time()

print end - start


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


Re: Encryption recommendation

2007-07-31 Thread Ricardo Aráoz
Azazello wrote:
> On Jul 31, 10:19 am, "JS" <[EMAIL PROTECTED]> wrote:
>> Can someone help me find the proper way to do AES encryption/decryption
>> using Python?
>>
>> Thanks!
> 
> I did a quick look around the internet and found this seemingly good
> link AES in general. Might be a good start.
> 
> http://msdn.microsoft.com/msdnmag/issues/03/11/AES/#S4
> 
> Looks like you'll need some matrix manipulations modules, and
> hopefully you'll be able to utilize Python's indexing and data
> strengths to keep things simple!
> 

Or you might use PyCrypto (http://python.codezoo.com/pub/component/5284)
which might be easier.



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


Re: What is the "functional" way of doing this?

2007-07-31 Thread Ricardo Aráoz
Steven D'Aprano wrote:
> On Tue, 31 Jul 2007 09:01:42 -0300, Ricardo Aráoz wrote:
> 
>> Considering I am a beginner I did a little test. Funny results too. The
>> function I proposed (lists1.py) took 11.4529998302 seconds, while the
>> other one (lists2.py) took 16.141324 seconds, thats about 40% more.
>> They were run in IDLE from their own windows (F5).
> 
> [snip code]
> 
> You may find that using the timeit module is better than rolling your own
> timer.
> 
>>>> def recursive_func(n):
> ... if n > 0:
> ... return [n % 26] + recursive_func(n/26)
> ... else:
> ... return []
> ...
>>>> def generator_func(n):
> ... def mseq(n):
> ... while n > 0:
> ... n, a = divmod(n, 26)
> ... yield a
> ... return list(mseq(n))
> ...
>>>> import timeit
>>>> N = 10**6+1
>>>> timeit.Timer("recursive_func(N)", 
> ... "from __main__ import N, recursive_func").repeat()
> [16.48972487449646, 17.000514984130859, 16.520529985427856]
>>>> timeit.Timer("generator_func(N)", 
> ... "from __main__ import N, generator_func").repeat()
> [27.938560009002686, 28.970781087875366, 23.977837085723877]
> 
> 
> If you're going to compare speeds, you should also test this one:
> 
>>>> def procedural_func(n):
> ... results = []
> ... while n > 0:
> ... n, a = divmod(n, 26)
> ... results.append(a)
> ... return results
> ...
>>>> timeit.Timer("procedural_func(N)", 
> ... "from __main__ import N, procedural_func").repeat()
> [15.577107906341553, 15.60145378112793, 15.345284938812256]
> 
> 
> I must admit that I'm surprised at how well the recursive version did, and
> how slow the generator-based version was. But I'd be careful about drawing
> grand conclusions about the general speed of recursion etc. in Python from
> this one single example. I think this is simply because the examples tried
> make so few recursive calls. Consider instead an example that makes a few
> more calls:
> 
>>>> N = 26**100 + 1
>>>>
>>>> timeit.Timer("recursive_func(N)", 
> ... "from __main__ import N, recursive_func").repeat(3, 1)
> [7.0015969276428223, 7.6065640449523926, 6.8495190143585205]
>>>> timeit.Timer("generator_func(N)", 
> ... "from __main__ import N, generator_func").repeat(3, 1)
> [3.5656340129, 3.1132731437683105, 3.8274538516998291]
>>>> timeit.Timer("procedural_func(N)", 
> ... "from __main__ import N, procedural_func").repeat(3, 1)
> [3.3509068489074707, 4.0872640609741211, 3.3742849826812744]
> 
> 

Yup! As soon as the size of the list increases the generator function
gets better (50% in my tests). But it's interesting to note that if the
list is within certain limits (I've tested integers (i.e. 2,100,000,000
=> 7 member list)) and you only vary the times the funct. is called then
the recursive one does better.


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


Re: Formatting Results so that They Can be Nicely Imported into a Spreadsheet.

2007-08-05 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> In a message dated 8/4/2007 11:50:05 PM Central Daylight Time,
> [EMAIL PROTECTED] writes:
> 
> [EMAIL PROTECTED] wrote:
> > On Aug 4, 6:35?pm, SMERSH009 <[EMAIL PROTECTED]> wrote:
> >> Hi All.
> >> Let's say I have some badly formatted text called doc:
> >>
> >> doc=
> >> """
> >> friendid
> >> Female
> >>
> >> 23 years old
> >>
> >> Los Gatos
> >>
> >> United States
> >> friendid
> >> Male
> >>
> >> 24 years old
> >>
> >> San Francisco, California
> >>
> >> United States
> >> """
> >>
> >> How would I get these results to be displayed in a format similar to:
> >> friendid;Female;23 years old;Los Gatos;United States
> >> friendid;Male; 24 years old;San Francisco, California;United States
> >>
> >> The latter is a lot easier to organize and can be quickly imported
> >> into Excel's column format.
> >>
> >> Thanks Much,
> >> Sam
> >
> > d = doc.split('\n')
> >
> > f = [i.split() for i in d if i]
> >
> > g = [' '.join(i) for i in f]
> >
> > rec = []
> > temprec = []
> > for i in g:
> > if i:
> > if i == 'friendid':
> > rec.append(temprec)
> > temprec = [i]
> > else:
> > temprec.append(i)
> > rec.append(temprec)
> >
> > output = [';'.join(i) for i in rec if i]
> >
> > for i in output: print i
> >
> > ##friendid;Female;23 years old;Los Gatos;United States
> > ##friendid;Male;24 years old;San Francisco, California;United
> > States
> >
> 
> Also :
> 
> docList = [ i.strip() for i in doc.split('\n') if i.strip()]
> 
> lines = [i for i in xrange(len(docList)) if docList[i] ==
> 'friendid']+[len(docList)]
> 
> docOut = ''
> for k in [docList[lines[j]:lines[j+1]] for j in xrange(len(lines)-1)]:
> docOut += '\n' + ';'.join(k)
> 
> docOut = docOut[1:]# Get rid of initial '\n'
> 
> Aren't you making an unwarranted assumption here?
> That doc ALWAYS starts with EXACTLY one blank line?

I guess you are referring to :
docList = [ i.strip() for i in doc.split('\n') if i.strip()]

Actually no, "doc.split('\n')" will split it a list member per line,
whether there are blank lines or not. Then "i.strip()" will take care of
redundant space, and "if i.strip()" will take care of blank lines. Try
it in your shell, play with "doc" and you'll see (I did try it without
the first blank line, and with a lot of blank lines and it's ok).

>  
> That's why I didn't use a list comprehension in that
> one section, to cover the possibility of any number
> (including none) of blank lines.

It works, didn't make a thorough testing but the cases you suggest were
tested.

>  
> By blindly coding [1:] you run the risk of data loss,
> and that's a poor example for the OP.

It is not "blindly". I guarantee the first byte will ALLWAYS be a '\n',
that's because I'm putting it there with "docOut += '\n' + ';'.join(k)"
(check the '\n' added at the beginning of each cycle), and I need to
strip the beginning '\n' which is not necessary.

Cheers

Ricardo


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


Re: Something in the function tutorial confused me.

2007-08-07 Thread Ricardo Aráoz
Lee Fleming wrote:
> Thanks for all the help, everyone. I guess I was confused with default
> arguments that were mutable and immutable. I will continue to look
> over these posts until I understand what is happening.
> 
> I cannot believe the number of helpful responses I got!
> 

Apparently he didn't understand.
Neither did I.

Either (i)y's initial value (None or []) is saved somewhere to be
retrieved every time the function is called without 2nd argument, or
(ii) y keeps the value it has when last exiting the function (if there
is a third option, please mention it).

(i) (a) whenever the function is called without 2nd argument the value
None is retrieved and assigned to y, thus causing [] to be assigned to y
by the 'if' statement.
(i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO
saved somewhere and when the function is called without 2nd argument it
should be retrieved and assigned to y, thus y would always be [] when
you enter the function without 2nd arg.

(ii) (b) if y keeps the value it has when last exiting the function that
would explain that the second time you call it the list returned will
have two members.
(ii) (a) But then if it is "def f(x, Y = None)" when the "if" is
evaluated the empty list is assigned to y. So y will NO LONGER be None.
The second time the function is called y is NOT None (remember it keeps
it's last value) and the function returns a list with two members.

So, as I see it, the behavior is not coherent, the function treats y
differently according to the value it has assigned.

Please correct me!




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


Re: Misleading wikipedia article on Python 3?

2007-08-09 Thread Ricardo Aráoz
Evan Klitzke wrote:
> On 8/8/07, greg <[EMAIL PROTECTED]> wrote:
>> Istvan Albert wrote:
>>> A solution would be writing the code with a logging function to begin
>>> with, alas many times that is out of one's hand.
>> If the code has been written with calls to a builtin
>> print function, the situation isn't much better. You
>> could monkeypatch the print function, but that's
>> probably worse than swapping sys.stdout.
> 
> You can easily modify print in a safe way. Here's an example, that
> will work in any recent version of Python:
> 
> import sys
> 
> def print_(s):
> print s
> 
> def logger(method):
> def wrapper(s):
> sys.stderr.write('Logging: %s\n' % s)
> method(s)
> return wrapper
> 
> print_ = logger(print_)
> 
> print_('hello')
> 
> 
> Running this code will do a regular print of 'hello', as well as
> "logging" it to stderr. As a function, you can convert print wholesale
> to another logging function, or wrap it transparently like this to
> provide additional logging functionality. What do you find wrong with
> this sort of "monkeypatching"?
> 

foolish question maybe.
Why wouldn't you do it this way ?

def print_(s):
print s

def logger(m):
sys.stderr.write('Logging: %s\n' % m)
method(m)

print_ = logger(print_)

print_('hello')




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


Re: python 2.5 bug

2007-08-13 Thread Ricardo Aráoz
Dustan wrote:
> On Aug 11, 12:32 am, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
>> 4. don't do something you don't fully understand (in this case
>>installing Python 2.5 and uninstalling Python 2.4)
> 
> If we were all limited by that rule, none of us would never have used
> a computer in the first place. Operating a computer is a learning
> experience, no matter what level you're at (although admittedly the
> lessons learned can sometimes be hurtful).
> 

Hi, I'm new to python. I'm male 48yo have a daughter, divorced. Live in
BA. Read Introduct me python and am at page 56 of shafting python the
right way. Have 220v alternate current (notice ! not 110v), my computer
is dirty, used to be whitish, got an epson printer (stylus c65). My
computer table is wood and some plastic. It's 16:05 and we are +4GMT
here, temp is 17Centigrades and no wind.
Ok. The question is... shit, I forgot the question! Get to you later.

;c)



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


Re: Finding gurus (was Re: Something in the function tutorial confused me.)

2007-08-13 Thread Ricardo Aráoz
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Alex Martelli <[EMAIL PROTECTED]> wrote:
>> Because of this, a Google search for
>>
>>  " " python
>>
>> may sometimes help; when you get 116,000 hits, as for "Steve Holden"
>> python, that may be a reasonable indication that the poster is one of
>> the world's Python Gurus (in fact, the winner of the 2007 Frank WIllison
>> Award -- congratulations, Steve!!!).
> 
> Sometimes that precise search pattern isn't appropriate, of course.  ;-)

Sorry, will answer as soon as I read the 52000 hits for "Aahz python".
Be patient ;c)


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


Hiding / encrypting source code

2007-08-17 Thread Ricardo Aráoz
Hi, I'm new to this python stuff so maybe I'm stating the obvious, or
worse, maybe I'm completely off track.

Not long ago someone was asking about a way to hide source code. I
stumbled upon zipimport standard module. It seems it lets you get your
imports from zip files. The docs say it is implicitly called, so you
could have your modules in a zipped file. That should make them a bit
more arcane.
Another idea would be to modify this module to use encrypted zip files,
or to use PyCrypto or some other module as a middle man in order to keep
the contents encrypted.

HTH


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


Re: IDE for Python

2007-08-21 Thread Ricardo Aráoz
king kikapu wrote:
> On Aug 21, 12:00 pm, Joel Andres Granados <[EMAIL PROTECTED]>
> wrote:
>> Hello list:
>>
>> I have tried various times to use an IDE for python put have always been
>> disapointed.
> 
> 
> I have also tried a lot of them (IDEs) in the last year. I was finally
> happy with Eclipse/Pydev but i was always wanted a more "true" IDE for
> Python.
> I think i found it in Eric4 http://www.die-offenbachs.de/eric/index.html
> You can download from here 
> http://www.riverbankcomputing.co.uk/pyqt/download.php
> (binary installer for Windows that contains Eric and PyQt)
> and have a look at it!
> 

Hi,
Do you know if for in-house development a GPL license applies? (Qt4
and/or Eric4).


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


Re: IDE for Python

2007-08-21 Thread Ricardo Aráoz
king kikapu wrote:
> On Aug 21, 12:00 pm, Joel Andres Granados <[EMAIL PROTECTED]>
> wrote:
>> Hello list:
>>
>> I have tried various times to use an IDE for python put have always been
>> disapointed.
> 
> 
> I have also tried a lot of them (IDEs) in the last year. I was finally
> happy with Eclipse/Pydev but i was always wanted a more "true" IDE for
> Python.
> I think i found it in Eric4 http://www.die-offenbachs.de/eric/index.html
> You can download from here 
> http://www.riverbankcomputing.co.uk/pyqt/download.php
> (binary installer for Windows that contains Eric and PyQt)
> and have a look at it!
> 

Hi again,
just installed from riverbank. Qt is ok but when I click Eric on the
start menu it does nothing (WinXP). If you have gone through this I'd
appreciate any tip, in other case I'll try figuring out tomorrow (it's
late and am tired today).

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


Re: introspection and functions

2007-08-23 Thread Ricardo Aráoz
Ayaz Ahmed Khan wrote:
> "James Stroud" typed:
>> py> def doit(a, b, c, x=14):
>> ...   pass
>> ...
>> py> doit.func_code.co_argcount
>> 4
>> py> doit.func_code.co_varnames
>> ('a', 'b', 'c', 'x')
>> py> doit.func_defaults
>> (14,)
> 
> Neat.
> 

How do you know the 14 corresponds to x ?


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


Re: IDE for Python

2007-08-23 Thread Ricardo Aráoz
I V wrote:
> On Tue, 21 Aug 2007 21:23:25 -0300, Ricardo Aráoz wrote:
>>  Do you know if for in-house development a GPL license applies? (Qt4
>> and/or Eric4).
> 
> (I'm not sure if I've understood your question right)
> 
> If you distribute an app that _uses_ PyQT, you have to comply with the GPL
> (or buy a license from Trolltech), but note that this doesn't really have
> anything to do with Eric4. Running Eric4 doesn't require a license (either
> the GPL or Trolltech), and code you write using Eric4 doesn't have to be
> licensed according to the GPL either.

I think they key word would be 'distribute'. I don't plan to distribute
the software. It will be used in-house for a commercial company which
pays for my time, they'll keep the source code but they won't be
distributing or selling it. Am I ok with QT4 ? (this is Windows).

TIA



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

Re: How can I use python for file processing

2007-08-26 Thread Ricardo Aráoz
Marc 'BlackJack' Rintsch wrote:
> On Sun, 26 Aug 2007 06:05:11 +, [EMAIL PROTECTED] wrote:
> 
>> I am trying to use python for file processing.
>> Suppose I have a file like this:
>> I want to build a Hashmap between the line "begin_QOS_statistics" and
>> "end_QOS_statistics"
>> and for each line I want to put the first text as the key of the hash
>> table and the second text as the value.
> 
> Work through the tutorial, experiment a little in the interactive
> interpreter and then just do it.  You need to `open()` the file, iterate
> over its lines in a ``for``-loop, decide to when it is time to start
> processing lines, and then `str.split()` the lines and put them into a
> `dict()`.  This is a neat little project to start learning the language.
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

Just posted this on Python Tutor, might give you a start :

nameFile = open(r'/path/to/file.txt', 'rU')
phonebook = {}

for line in nameFile :
phonebook.setdefault(line[0].upper(), []).append(line.strip('\n'))

for item, names in phonebook.iteritems() :
names.sort()

print phonebook

HTH

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


Re: Haskell like (c:cs) syntax

2007-08-28 Thread Ricardo Aráoz
Stefan Niemann wrote:
> Hi,
> 
> sorry that I'm relatively new to Python. But the syntax and semantics of 
> Python already fascinate me, because I'm familiar with functional languages 
> like Haskell.
> 
> Is there a pattern matching construct in Python like (head : tail), meaning 
> 'head' matches the first element of a list and 'tail' matches the rest? I 
> could not find this in the Python documentation.
> 
> Regards,
> Stefan
> 
> 
> 

L = ['one', 'two', 'three', 'four', 'five']

print L[0]# This would be 'head'
print L[1:]   # This would be 'tail'

Caution : L[0] and L[1:] are COPIES of the head and tail of the list.

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


Re: encoding problems

2007-08-29 Thread Ricardo Aráoz
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, tool69 wrote:
> 
>> p2.content = """Ce poste possède des accents : é à ê è"""
> 
> My guess is this is being encoded as a Latin-1 string, but when you try to
> output it it goes through the ASCII encoder, which doesn't understand the
> accents. Try this:
> 
> p2.content = u"""Ce poste possède des accents : é à ê è""".encode("utf8")
> 

is there a way to sort this string properly (sorted()?)
I mean first 'a' then 'à' then 'e' etc. (sorted puts accented letters at
the end). Or should I have to provide a comparison function to sorted?



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

Re: Haskell like (c:cs) syntax

2007-08-29 Thread Ricardo Aráoz
Marco Mariani wrote:
> Ricardo Aráoz ha scritto:
> 
>> L = ['one', 'two', 'three', 'four', 'five']
>>
>> print L[0]# This would be 'head'
>> print L[1:]   # This would be 'tail'
>>
>> Caution : L[0] and L[1:] are COPIES of the head and tail of the list.
> 
> This might surprise people who see L[1:] = [], since changing a copy is 
> not supposed to change the original.
> 

Sorry, should have written RETURN copies instead of ARE copies.

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


Re: copying files

2007-08-29 Thread Ricardo Aráoz
Brian McCann wrote:
> Hi,
>  
> with the code below I set a variable TEST_HOME to a path and the
> variable m to a path
> in my current dir.
> I have a symbolic link setting m>lib
> when I run the script I get no errors and the lib dir with its 20 files
> does not get copied to /v01/test_home
> any help would be greatly appreciated
>  
> --Brian
> 
> #!/usr/bin/python
> import string
> import os
> import sys
> import errno
> import shutil
> import tarfile
>  
> TEST_HOME = "/v01/test_home"
> m = "./lib"
> os.system("cp -r m TEST_HOME")
> #os.system("tar -cvf viziant-ingestion.tar /v01/")
>  

Maybe os.system("cp -r " + m + TEST_HOME) ?

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


Re: copying files

2007-08-29 Thread Ricardo Aráoz
Brian McCann wrote:
> Hi,
>  
> with the code below I set a variable TEST_HOME to a path and the
> variable m to a path
> in my current dir.
> I have a symbolic link setting m>lib
> when I run the script I get no errors and the lib dir with its 20 files
> does not get copied to /v01/test_home
> any help would be greatly appreciated
>  
> --Brian
> 
> #!/usr/bin/python
> import string
> import os
> import sys
> import errno
> import shutil
> import tarfile
>  
> TEST_HOME = "/v01/test_home"
> m = "./lib"
> os.system("cp -r m TEST_HOME")
> #os.system("tar -cvf viziant-ingestion.tar /v01/")
>  

Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME)


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


Re: copying files

2007-08-29 Thread Ricardo Aráoz
Brian McCann wrote:
>  
>  
> <mailto:[EMAIL PROTECTED]> 
> Hi Ricardo,
> 
> what do the + signs do?
>  

Add the different strings. You had 'm' and 'TEST_HOME' inside a string,
so they would be taken as characters and not variables.

>>> TEST_HOME = "/v01/test_home"
>>> m = "./lib"
>>> "cp -r " + m + " " + TEST_HOME
'cp -r ./lib /v01/test_home'   <- This is what you want.
>>> "cp -r m TEST_HOME"
'cp -r m TEST_HOME'<- This is NOT what you want.

> 
> 
> 
> From: Ricardo Aráoz [mailto:[EMAIL PROTECTED]
> Sent: Wed 8/29/2007 2:51 PM
> To: Brian McCann
> Cc: [email protected]
> Subject: Re: copying files
> 
> 
> 
> Brian McCann wrote:
>> Hi,
>>
>> with the code below I set a variable TEST_HOME to a path and the
>> variable m to a path
>> in my current dir.
>> I have a symbolic link setting m>lib
>> when I run the script I get no errors and the lib dir with its 20 files
>> does not get copied to /v01/test_home
>> any help would be greatly appreciated
>>
>> --Brian
>>
>> #!/usr/bin/python
>> import string
>> import os
>> import sys
>> import errno
>> import shutil
>> import tarfile
>>
>> TEST_HOME = "/v01/test_home"
>> m = "./lib"
>> os.system("cp -r m TEST_HOME")
>> #os.system("tar -cvf viziant-ingestion.tar /v01/")
>>
> 
> Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME)
> 
> 
> 
> 

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


Re: status of Programming by Contract (PEP 316)?

2007-08-30 Thread Ricardo Aráoz
Russ wrote:
> Paul Rubin wrote:
>> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>>> FWIW, the "Eiffel and SPARK Ada folks" also "brilliantly explained"
>>> why one can not hope to "write reliable programs" without strict
>>> static declarative type-checking.
>> I don't know about Eiffel but at least an important subset of SPARK
>> Ada's DBC stuff is done using static analysis tools (not actually
>> built into the compiler as it happens) to verify statically
>> (i.e. without actually running the code) that the code fulfills the
>> DBC conditions.  I don't see any way to do that with Python
>> decorators.
> 
> Yes, thanks for reminding me about that. With SPARK Ada, it is
> possible for some real
> (non-trivial) applications to formally (i.e., mathematically) *prove*
> correctness by static
> analysis. I doubt that is possible without "static declarative type-
> checking."
> 
> SPARK Ada is for applications that really *must* be correct or people
> could die.

I've always wondered... Are the compilers (or interpreters), which take
these programs to machine code, also formally proven correct? And the OS
in which those programs operate, are they also formally proven correct?
And the hardware, microprocessor, electric supply, etc. are they also
'proven correct'?

> With all
> due respect, most (not all, but most) Python programmers never get
> near such programs
> and have no idea about how stringent the requirements are. Nor do most
> programmers
> in general, for that matter. (It's not an insult)
> 

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


Re: list index()

2007-08-30 Thread Ricardo Aráoz
Alex Martelli wrote:
> <[EMAIL PROTECTED]> wrote:
>...
>> In my case of have done os.listdir() on two directories. I want to see
>> what files are in directory A that are not in directory B.
> 
> So why would you care about WHERE, in the listdir of B, are to be found
> the files that are in A but not B?!  You should call .index only if you
> CARE about the position.
> 
> def inAnotB(A, B):
> inA = os.listdir(A)
> inBs = set(os.listdir(B))
> return [f for f in inA if f not in inBs]
> 
> is the "one obvious way to do it" (the set(...) is just a simple and
> powerful optimization -- checking membership in a set is roughly O(1),
> while checking membership in a list of N items is O(N)...).

And what is the order of passing a list into a set? O(N)+?

> 
> 
> Alex

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


Re: status of Programming by Contract (PEP 316)?

2007-08-31 Thread Ricardo Aráoz
Russ wrote:
>> I've always wondered... Are the compilers (or interpreters), which take
>> these programs to machine code, also formally proven correct?
> 
> No, they are not formally proven correct (too complicated for that),
> but I believe they are certified to a higher level than your "typical"
> compiler. I think that Ada compilers used for certain safety-critical
> applications must meet higher standards than, say, GNU Ada, for
> example.
> 
> And the OS
>> in which those programs operate, are they also formally proven correct?
> 
> Same as above, if I am not mistaken.
> 
>> And the hardware, microprocessor, electric supply, etc. are they also
>> 'proven correct'?
> 
> I think the microprocessors used for flight control, for example, are
> certified to a higher level than standard microprocessors.
> 
> How would you prove a power supply to be "correct"? I'm sure they meet
> higher reliability standards too.
> 
> 

In that case why don't we just 'certify to a higher level' the programs
and get done with this formal proofs? We should remember that the level
of security of a 'System' is the same as the level of security of it's
weakest component, so either we formally prove all those other very
important components (OS gets MUCH more use than the program (the
program uses it for almost every other action)) or get done with the
whole fuss.


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


Re: status of Programming by Contract (PEP 316)?

2007-08-31 Thread Ricardo Aráoz
Neil Cerutti wrote:
> On 2007-08-31, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Russ wrote:
>>> Yes, thanks for reminding me about that. With SPARK Ada, it is
>>> possible for some real (non-trivial) applications to formally
>>> (i.e., mathematically) *prove* correctness by static analysis.
>>> I doubt that is possible without "static declarative type-
>>> checking."
>>>
>>> SPARK Ada is for applications that really *must* be correct or
>>> people could die.
>> I've always wondered... Are the compilers (or interpreters),
>> which take these programs to machine code, also formally proven
>> correct? And the OS in which those programs operate, are they
>> also formally proven correct? And the hardware, microprocessor,
>> electric supply, etc. are they also 'proven correct'?
> 
> Who watches the watchmen? The contracts are composed by the
> programmers writing the code. Is it likely that the same person
> who wrote a buggy function will know the right contract?
> 

Actually my point was that if a program is to be trusted in a critical
situation (critical as in catastrophe if it goes wrong) then the OS, the
 compiler/interpreter etc should abide by the same rules. That is
obviously not possible, so there's not much case in making the time
investment necessary for correctness proof of a little program (or
usually a little function inside a program) when the possibilities for
failure are all around it and even in the code that will run that
function. And we should resort to other more sensible answers to the
safety problem.


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


Re: list index() (OT)

2007-09-01 Thread Ricardo Aráoz
Paddy wrote:
> On Sep 1, 7:57 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>> "Richie Hindle"  wrote:
>>> But - the word for someone who posts to the internet with the intention of
>>> stirring up trouble derives from the word for what fishermen do, not from
>>> the word for something that lives under a bridge.  It derives from "trolling
>>> for suckers" or "trolling for newbies".
>> So am I right in asserting that there is a difference in pronunciation
>> of the noun and the verb?
>>
>> He is a Troll - like the excellent frolic example
>> He likes to Troll - rhymes with roll?
>>
>> - Hendrik
> 
> No difference. A troll is a troll is a troll.
> 
> :-)
> 
> - Paddy.


BTW people , the word for what fishermen do is  T R A W L  and not troll
(Ha! and I'm not a native English speaker).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: status of Programming by Contract (PEP 316)?

2007-09-01 Thread Ricardo Aráoz
Hendrik van Rooyen wrote:
>  "Carl Banks"  wrote:
> 
>> This is starting to sound silly, people.  Critical is a relative term, 
>> and one project's critical may be anothers mundane.  Sure a flaw in your 
>> flagship product is a critical problem *for your company*, but are you 
>> really trying to say that the criticalness of a bad web search is even 
>> comparable to the most important systems on airplanes, nuclear reactors, 
>> dams, and so on?  Come on.
> 
> This really intrigues me - how do you program a dam?  - and why is it
> critical?
> 
> Most dams just hold water back.
> 
> Dam design software - well yes that I would agree is critical.
> Is that what you mean?
> 
> - Hendrik
> 

Yup! He was referring to that Damn design software. Just as almost
everyone has at one time or another.  ;c)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Ricardo Aráoz
Steve Holden wrote:
> Ricardo Aráoz wrote:
>> Paddy wrote:
>>> On Sep 1, 7:57 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>>>> "Richie Hindle"  wrote:
>>>>> But - the word for someone who posts to the internet with the intention of
>>>>> stirring up trouble derives from the word for what fishermen do, not from
>>>>> the word for something that lives under a bridge.  It derives from 
>>>>> "trolling
>>>>> for suckers" or "trolling for newbies".
>>>> So am I right in asserting that there is a difference in pronunciation
>>>> of the noun and the verb?
>>>>
>>>> He is a Troll - like the excellent frolic example
>>>> He likes to Troll - rhymes with roll?
>>>>
>>>> - Hendrik
>>> No difference. A troll is a troll is a troll.
>>>
>>> :-)
>>>
>>> - Paddy.
>>
>> BTW people , the word for what fishermen do is  T R A W L  and not troll
>> (Ha! and I'm not a native English speaker).
> 
> Just read the whole thread, or use a dictionary: in fishing, trolling 
> and trawling are two different things; the first is done with a net, the 
> second with a line.
> 
> regards
>   Steve

Damn Wikipedia! It always gets things upside down, specially when I
'read the whole thread' :

"Trolling for fish" is a form of angling where lines with hook-rigged
lures are dragged behind a boat to entice fish to bite. Compare the term
"Trawling for fish," which involves dragging a net behind a boat to
catch large numbers of fish.

;c)

(Don't mind me. Just trolling...)




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


localizing a sort

2007-09-01 Thread Ricardo Aráoz
Hi, I've been working on sorting out some words.

My locale is :
>>> import locale
>>> locale.getdefaultlocale()
('es_AR', 'cp1252')

I do :
>>> a = 'áéíóúäëïöüàèìòù'
>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y)))
aeiouàáäèéëìíïòóöùúü

This is not what I am expecting. I was expecting :
aáàäeéèëiíìï.etc.

The reason is that if you want to order some words (say for a dictionary
(paper dict, where you look up words)) this is what happens :
>>> a = 'palàbra de pàlabra de pblabra'
>>> print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y)))
de de palàbra pblabra pàlabra

While any human being would expect :

de de palàbra pàlabra pblabra

Does anybody know a way in which I could get the desired output?

TIA




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


Re: status of Programming by Contract (PEP 316)?

2007-09-01 Thread Ricardo Aráoz
Alex Martelli wrote:
> Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>...
>> We should remember that the level
>> of security of a 'System' is the same as the level of security of it's
>> weakest component,
> 
> Not true (not even for security, much less for reliability which is
> what's being discussed here).
> 
> It's easy to see how this assertion of yours is totally wrong in many
> ways...
> 
> Example 1: a toy system made up of subsystem A (which has a probability
> of 90% of working right) whose output feeds into subsystem B (which has
> a probability of 80% of working right).  A's failures and B's faliures
> are statistically independent (no common-mode failures, &c).
> 
> The ``level of goodness'' (probability of working right) of the weakest
> component, B, is 80%; but the whole system has a ``level of goodness''
> (probability of working right) of just 72%, since BOTH subsystems must
> work right for the whole system to do so.  72 != 80 and thus your
> assertion is false.
> 
> More generally: subsystems "in series" with independent failures can
> produce a system that's weaker than its weakest component.
> 
> 
> Example 2: another toy system made up of subsystems A1, A2 and A3, each
> trying to transform the same input supplied to all of them into a 1 bit
> result; each of these systems works right 80% of the time, statistically
> independently (no common-mode failures, &c).  The three subsystems'
> results are reconciled by a simple majority-voting component M which
> emits as the system's result the bit value that's given by two out of
> three of the Ai subsystems (or, of course, the value given unanimously
> by all) and has extremely high reliability thanks to its utter
> simplicity (say 99.9%, high enough that we can ignore M's contribution
> to system failures in a first-order analysis).
> 
> The whole system will fail when all Ai fail together (probability
> 0.2**3) or when 2 out of them fail while the hird one is working
> (probability 3*0.8*0.2**2):
> 
>>>> 0.2**3+3*0.2**2*0.8
> 0.10404
> 
> So, the system as a whole has a "level of goodness" (probability of
> working right) of almost 90% -- again different from the "weakest
> component" (each of the three Ai's), in this case higher.
> 
> More generally: subsystems "in parallel" (arranged so as to be able to
> survive the failure of some subset) with indipendent failures can
> produce a system that's stronger than its weakest component.
> 
> 
> Even in the field of security, which (changing the subject...) you
> specifically refer to, similar considerations apply.  If your assertion
> was correct, then removing one component would never WEAKEN a system's
> security -- it might increase it if it was the weakest, otherwise it
> would leave it intact.  And yet, a strong and sound tradition in
> security is to require MULTIPLE components to be all satisfied e.g. for
> access to secret information: e.g. the one wanting access must prove
> their identity (say by retinal scan), possess a physical token (say a
> key) AND know a certain secret (say a password).  Do you really think
> that, e.g., removing the need for the retinal scan would make the
> system's security *STRONGER*...?  It would clearly weaken it, as a
> would-be breaker would now need only to purloin the key and trick the
> secret password out of the individual knowing it, without the further
> problem of falsifying a retinal scan successfully.  Again, such security
> systems exist and are traditional exactly because they're STRONGER than
> their weakest component!
> 
> 
> So, the implication accompanying your assertion, that strenghtening a
> component that's not the weakest one is useless, is also false.  It may
> indeed have extremely low returns on investment, depending on system's
> structure and exact circumstances, but then again, it may not; nothing
> can be inferred about this ROI issue from the consideration in question.
> 
> 
> Alex

You win the argument, and thanks you prove my point. You typically
concerned yourself with the technical part of the matter, yet you
completely ignored the point I was trying to make.
That is that in real world applications formally proving the application
is not only an enormous resource waster but it also pays very little if
at all. I think most cases will fall under point (1) of your post, and
as so many other not formally proven subsystems are at work at the same
time there will be hardly any gain in doing it.
Point (2) of your post would be my preferred solution, and what is
usually done in hardware.
In the third part of your post, regarding security, I think you went off
the road. The weakest component would not be one of the requisites of
access, the weakest component I was referring to would be an actual
APPLICATION, e.g. an ftp server. In that case, if you have several
applications running your security will be the security of the weakest
of them.






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


Re: status of Programming by Contract (PEP 316)?

2007-09-02 Thread Ricardo Aráoz
Alex Martelli wrote:
> Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>...
>>>> We should remember that the level
>>>> of security of a 'System' is the same as the level of security of it's
>>>> weakest component,
>...
>> You win the argument, and thanks you prove my point. You typically
>> concerned yourself with the technical part of the matter, yet you
>> completely ignored the point I was trying to make.
> 
> That's because I don't particularly care about "the point you were
> trying to make" (either for or against -- as I said, it's a case of ROI
> for different investments [in either security, or, more germanely to
> this thread, reliability] rather than of useful/useless classification
> of the investments), while I care deeply about proper system thinking
> (which you keep failing badly on, even in this post).

And here you start, followed by 'F- at system thinking', 'glib and false
assertions', 'falsities', etc.
I don't think you meant anything personal, how could you, we don't know
each other. But the outcome feels like a personal attack instead of an
attack on the ideas exposed.
If that's not what you intended, you should check your communication
abilities and see what is wrong. If that is what you meant well...

So I will not answer your post. I'll let it rest for a while till I
don't feel the sting, then I'll re-read it and try to learn as much as I
can from your thoughts (thank you for them). And even though some of
your thinking process I find objectionable I will not comment on it as
I'm sure it will start some new flame exchange which will have a lot to
do with ego and nothing to do with python.

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


Re: localizing a sort

2007-09-02 Thread Ricardo Aráoz
Peter Otten wrote:
> Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Aráoz:
> 
>> Hi, I've been working on sorting out some words.
>>
>> My locale is :
>>>>> import locale
>>>>> locale.getdefaultlocale()
>> ('es_AR', 'cp1252')
>>
>> I do :
>>>>> a = 'áéíóúäëïöüàèìòù'
>>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y)))
>> aeiouàáäèéëìíïòóöùúü
> 
> The lambda is superfluous. Just write cmp=locale.strcoll instead.

No it is not :
>>> print ''.join(sorted(a, cmp=locale.strcoll(x,y)))
Traceback (most recent call last):
  File "", line 1, in 
TypeError: strcoll expected 2 arguments, got 0

You need the lambda to assign both arguments.

>  
>> This is not what I am expecting. I was expecting :
>> aáàäeéèëiíìï.etc.
>>
>> The reason is that if you want to order some words (say for a dictionary
>> (paper dict, where you look up words)) this is what happens :
>>>>> a = 'palàbra de pàlabra de pblabra'
>>>>> print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y)))
>> de de palàbra pblabra pàlabra
>>
>> While any human being would expect :
>>
>> de de palàbra pàlabra pblabra
>>
>> Does anybody know a way in which I could get the desired output?
> 
> I suppose it would work on your machine if you set the locale first with
> 
>>>> locale.setlocale(locale.LC_ALL, "")

This works. Thanks Peter.

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

Re: localizing a sort

2007-09-02 Thread Ricardo Aráoz
Alex Martelli wrote:
> Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Peter Otten wrote:
>...
>>>>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y)))
>>>> aeiouàáäèéëìíïòóöùúü
>>> The lambda is superfluous. Just write cmp=locale.strcoll instead.
>> No it is not :
>>>>> print ''.join(sorted(a, cmp=locale.strcoll(x,y)))
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> TypeError: strcoll expected 2 arguments, got 0
>>
>> You need the lambda to assign both arguments.
> 
> No, your mistake is that you're CALLING locale.strcoll, while as Peter
> suggested you should just PASS it as the cmp argument.  I.e.,
> 
> ''.join(sorted('ciao', cmp=locale.strcoll))
> 
> Using key=locale.strxfrm should be faster (at least when you're sorting
> long-enough lists of strings), which is why strxfrm (and key=...:-)
> exist in the first place, but cmp=locale.strcoll, while usually slower,
> is entirely correct.  That lambda _IS_ superfluous, as Peter said.
> 
> 
> Alex

Got it! And it is MUCH more elegant than my code. Thanks.


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


Re: advice about `correct' use of decorator

2007-09-03 Thread Ricardo Aráoz
Gabriel Genellina wrote:
> En Wed, 29 Aug 2007 07:32:21 -0300, BJörn Lindqvist <[EMAIL PROTECTED]>  
> escribi�:
> 
>> On 8/24/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>>> En Thu, 23 Aug 2007 09:20:21 -0300, BJörn Lindqvist <[EMAIL PROTECTED]>
>>> escribi�:
>>>
 def check_user_logged_in(func):
 def f(*args, **kwargs):
 if global_state.the_user.is_logged_in:
 return func(*args, **kwargs)
 return show_login_page()
 return f
>>> I think there is a semantic problem, perhaps we are not talking
>>> about the same thing. I'm considering the software complexity AS
>>> PERCEIVED BY THE PROGRAMMER, looking at the interactions between a
>>> program and a programmer who is working on some task; some people
>>> would say "cognitive complexity" to make it clear.
>> There is no semantic problem. You are just mistaken in your belief
>> that the complexity that the user of the decorator has to deal with is
>> different from the complexity in implementing the decorator.
> 
> But they ARE different. That's the whole point of abstractions, code  
> reuse, layered design... Designing a simple interfase on top of a complex  
> system is very common. Nobody writes X-Window code, as nobody writes a raw  
> event loop for Windows anymore: there are very good GUI toolkits, even  
> portable frameworks, that put an abstract layer on top of that so the  
> programmer has a much simple and coherent view. The complexity is behind  
> the scenes.
> 
>>> Which API is more complex: one in which you can play a movie with
>>> just a single call like PlayMovie(Title), or one on which you must
>>> call a zillion functions to firtly initialize the stream format,
>>> configure the display, disable undesired user interfase elements,
>>> locate the movie file, load it in chunks, etc.? The first one is
>>> certainly much simpler to use (simpler = less complex), and maybe
>>> internally it calls the same functions as the second one, but nobody
>>> cares.
>> "nobody cares" is your guess. I'd bet that the caller of the PlayMovie
>> function cares a lot: Is the movie played full screened? Which
>> encodings are supported? Can you set the title of the movie window? Is
>> streaming supported? Does it even work on windows? Which URI schemes
>> does it support?  And so on and so on.
>>
>> That is why no video decoding API:s have a PlayMovie(Title) function
>> and why I haven't seen a single 3d engine with a
>> MakeReallyCoolDoomCloneFPSGame() function.
> 
> (yet!). What about urlopen? Using a single call one can be authenticated  
> and retrieve any file in the other side of the planet. I consider it a  
> simple interfase, altough it does complex things. Would you say it is  
> better to use plain sockets everywhere? Or, since sockets are abstractions  
> themselves, would you say it is better to use lower level primitives  
> instead? Each time you descend a level, you have to use many simpler  
> functions - but their combination is more complex.
> 
>> "hiding details" only works if the client programmer really doesn't
>> care about the details.
> 
> Why should he care? Isn't "hiding implementation details" a good design  
> principle?
> When I use urlopen, I don't even care of the underlying socket  
> implementation. I don't care which interfase the request is sent thru. I  
> don't care if the answer got fragmented and some packets had to be  
> reassembled. urlopen gives me something that looks like a file, and I just  
> read() from it.
> 
>>> Back to your example, the fact that a decorator builds a higher order
>>> function, does NOT make it more complex - because the programmer does  
>>> not
>>> see that. In fact, hiding the details makes it simpler.
>> Yes, the programmer does see that. The example decorator I posted
>> requires about a zillion preconditions to work correctly and will fail
>> in weird ways when those preconditions are not satisfied. The
>> programmer is interested in the crazy failures he or she will
>> experience. I dare you to try and implementing the code both as a
>> decorator and as a function, then write the unit tests and
>> documentation. The complexity of those three items together
>> (implementation + tests + documentation) will be much higher for the
>> decorator choice because the complexity of the decorator
>> implementation is a bit higher than using a plain old function.
> 
> Testing the decorator is as hard as testing any other function. Testing  
> the decorated functions might involve *only* checking if the decorator is  
> actually used for those functions.
> Going to your posted example, I don't see the difference - I should say, I  
> don't see the advantage. Using a decorator hides some implementation  
> details and reduces coupling between modules, both good things on "my"  
> book; your function with no decorator does quite the opposite, and doesn't  
> look like good coding style (on "my" book, of course).
> 
>> Note also that it is e

Re: REGULAR EXPRESSION

2007-09-04 Thread Ricardo Aráoz
Steve Holden wrote:
> AniNair wrote:
>> hi.. I am trying to match '+ %&/-' etc using regular expression  in
>> expressions like 879+34343. I tried \W+   but it matches only in the
>> beginning of the string Plz help Thanking you in advance...
>>
> Perhaps you could give a few example of strings that should and 
> shouldn't match? It isn't clear from your description what pattern you 
> are trying to find.
> 
> regards
>   Steve


If it's operations between two numbers try :
r'([\d.]+?)\s*([-+/*%&])([\d.]+)'
It will give you 3 groups, first number, operation and second number
(caveat emptor).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REGULAR EXPRESSION

2007-09-05 Thread Ricardo Aráoz
AniNair wrote:
> On Sep 5, 4:35 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Steve Holden wrote:
>>> AniNair wrote:
>>>> hi.. I am trying to match '+ %&/-' etc using regular expression  in
>>>> expressions like 879+34343. I tried \W+   but it matches only in the
>>>> beginning of the string Plz help Thanking you in advance...
>>> Perhaps you could give a few example of strings that should and
>>> shouldn't match? It isn't clear from your description what pattern you
>>> are trying to find.
>>> regards
>>>   Steve
>> If it's operations between two numbers try :
>> r'([\d.]+?)\s*([-+/*%&])([\d.]+)'
>> It will give you 3 groups, first number, operation and second number
>> (caveat emptor).
> 
> 
> Hi.. Thanks alot for finding time to help a beginner like me. What I
> am trying to do is validate the input i get. I just want to take
> numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or
> 7/0 , I want to find it using reg exp. I know there are other ways to
> do this... but i thought i will try this as i need to learn reg exp. I
> tried \D+   ,   \W+,  and \D+|\W+ .. Thanks once again...
> 

Well \d will match a number and '.' inside [] will match a dot ;) so if
you want only integer numbers ([\d.]*) should be replaced with  (\d+)
Only problem with the expression I sent is that it will match a number
with more than one dot.

HTH


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


Re: Looping through File Question

2007-09-06 Thread Ricardo Aráoz
John Machin wrote:
> On Sep 5, 10:26 pm, planetmatt <[EMAIL PROTECTED]> wrote:
>> On 5 Sep, 12:34, John Machin <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> On Sep 5, 8:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
 I am a Python beginner.  I am trying to loop through a CSV file which
 I can do.  What I want to change though is for the loop to start at
 row 2 in the file thus excluding column headers.
 At present I am using this statement to initiate a loop though the
 records:
 for line in f.readlines():
 How do I start this at row 2?
>>> The quick answer to your literal question is:
>>>   for line in f.readlines()[1:]:
>>> or, with extreme loss of elegance, this:
>>>   for lino, line in enumerate(f.readlines()):
>>>   if not lino:
>>>   continue
>>> But readline and readlines are old hat, and you wouldn't want to read
>>> a file of a few million lines into a big list, so a better answer is:
>>> _unused = f.next()
>>> for line in f:
>>> But you did say you were reading a CSV file, and you don't really want
>>> to do your own CSV parsing, even if you think you know how to get it
>>> right, so best is:
>>> import csv
>>> rdr = csv.reader(f)
>>> heading_row = rdr.next()
>>> for data_row in rdr:
>>> HTH,
>>> John
>> Thanks so much for the quick response.  All working now.
>>
>> I had looked at the CSV module but when I ran into another problem of
>> trying to loop through all columns, I was given a solution in another
>> forum which used the readlines() method.
> 
> Antique advice which still left you doing the CSV parsing :-)
> 
>> I have looked at the CSV documentation but didn't see any mention of
>> heading_row or data_row.
> 
> Ummm ... 'heading_row' and 'data_row' are identifiers of the kind that
> you or I would need to make up in any language; why did you expect to
> find them in the documentation?
> 
>> Is there a definitive Python documentation
>> site with code examples like MS's MSDN?
> 
> The definitive Python documentation site is (I suppose) 
> http://www.python.org/doc/
> 
> I don't know what "code examples like MS's MSDN" means. I avoid MSDN
> like I'd avoid a nurse carrying a bottle of Dettol and a wire
> brush :-)
> 
> Here's an example of sucking your data into a list of lists and
> accessing it columnwise:
> 
> rdr = csv.reader(f)
> whatever_you_want_to_call_the_heading_row = rdr.next()
> data = list(rdr)
> sum_col_5 = sum(float(row[5]) for row in data)
> print "The value in row 3, column 4 is", data[3][4]
> 
> HTH,
> John
> 

Given that you have a header row you could also do (untested):

rdr = csv.DictReader(f)
data = list(rdr)
sum_Value = sum(float(row['Value']) for row in data)
print "The value in row 3, column 'ColName' is", data[3]['ColName']

DictReader generates a list of dictionaries which take the keys from
your header row.


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


Re: Text processing and file creation

2007-09-06 Thread Ricardo Aráoz
Shawn Milochik wrote:
> On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> I have a text source file of about 20.000 lines.
>> >From this file, I like to write the first 5 lines to a new file. Close
>> that file, grab the next 5 lines write these to a new file... grabbing
>> 5 lines and creating new files until processing of all 20.000 lines is
>> done.
>> Is there an efficient way to do this in Python?
>> In advance, thanks for your help.
>>

Maybe (untested):

def read5Lines(f):
L = f.readline()
while L :
yield (L,f.readline(),f.readline(),f.readline(),f.readline())
L = f.readline()

in = open('C:\YourFile','rb')
for fileNo, fiveLines in enumerate(read5Lines(in)) :
out = open('c:\OutFile'+str(fileNo), 'wb')
out.writelines(fiveLines)
out.close()

or something similar? (notice that in the last output file you may have
a few (4 at most) blank lines)




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


Re: Finding specific date ranges

2007-09-07 Thread Ricardo Aráoz
Tim Golden wrote:
> [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I am working on a timesheet application in which I need to to find the
>> first pay period in a month that is entirely contained in that month
>> to calculate vacation time. Below are some example date ranges:
>>
>>
>> December 31, 2006January 13, 2007 # doesn't earn
>> January 14, 2007 January 27, 2007 # does earn
>> January 28, 2007 February 10, 2007 # doesn't
>> February 11, 2007February 24, 2007 # does
>>

What about (untested) :
import datetime

def itEarns(fromDate, toDate) :
return (fromDate.year == toDate.year and fromDate.month == toDate.month)

periods = [
(datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)),
(datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)),
(datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)),
(datetime.date(2007, 2, 11), datetime.date(2007, 2, 24))
]

candidatePeriods = [(frm, to) for frm, to in periods if itEarns(frm, to)]

??

>>
>> So far, the best approach I've come up with is to create a list of
>> tuples that contain the pay period date ranges for the year and
>> iterate through the tuples looking for the first occurrence of the
>> month names matching. Then I'd add that date range to a separate list
>> and somehow ignore any other matches in that month. This seems like a
>> hack. Does anyone have a better idea?
> 
> 
> Well, I can come up with a solution which basically reflects the
> way I'd do it in SQL (since this kind of thing is my bread-and-butter
> there) but I'm not convinced it's really any better than your proposal.
> However, for the purposes of illustration:
> 
> 
> import calendar
> import datetime
> 
> YEAR = 2007
> 
> months = [
>(datetime.date (YEAR, n, 1), datetime.date (YEAR, n, calendar.monthrange 
> (YEAR, n)[1]))
>for n in range (1, 13)
> ]
> 
> periods = [
>(datetime.date(2006, 12, 31), datetime.date(2007, 1, 13)),
>(datetime.date(2007, 1, 14), datetime.date(2007, 1, 27)),
>(datetime.date(2007, 1, 28), datetime.date(2007, 2, 10)),
>(datetime.date(2007, 2, 11), datetime.date(2007, 2, 24))
> ]
> 
> for m in months:
>candidate_periods = [p for p in periods if m[0] <= p[0] and p[1] <= m[1]]
>if candidate_periods:
>  print m[0], "=>", min (candidate_periods)
>else:
>  print m[0], "=>", "no period matches"
> 
> 
> 
> TJG


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


Re: why should I learn python

2007-09-07 Thread Ricardo Aráoz
Tom Brown wrote:
> On Thursday 06 September 2007 15:44, Torsten Bronger wrote:
>> Hallöchen!
>>
>> Tom Brown writes:
>>> [...] Python has been by far the easiest to develop in.  Some
>>> people might say it is not "real programming" because it is so
>>> easy.
>> I can't believe this.  Have you really heard such a statement?
> 
> Yes. I was told this by a C programmer. Something about doing it all yourself 
> and not using provided packages. I countered with something about reinventing 
> the wheel. :)
> 

You should have asked if he used the OS or did he control the devices
(HD, screen) himself.


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


Re: How to determine the bool between the strings and ints?

2007-09-08 Thread Ricardo Aráoz
Zentrader wrote:
> On Sep 7, 11:30 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Fri, 07 Sep 2007 18:49:12 +0200, Jorgen Bodde wrote:
>>> As for why caring if they are bools or not, I write True and False to
>>> the properties, the internal mechanism works like this so I need to
>>> make that distinction.
>> Really?  Can't you just apply the `int()` function?
>>
>> In [52]: map(int, [1, 0, True, False])
>> Out[52]: [1, 0, 1, 0]
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> Blackjack's solution would take care of the problem, so this is just
> for general info.  Looks like a "feature" of isinstance() is to
> consider both True and 1 as booleans, but type() distinguishes between
> the two.
 x=True
> ... if type(x) == type(1):
> ...print "int"
> ... else:
> ...print "not int"
> ...
> not int
> 
>  if type(x) == type(True):
> ...print "bool"
> ...
> bool
> 

Or just :

>>> a = True
>>> type(a) == int
False
>>> type(a) == bool
True
>>> a = 'True'
>>> type(a) == bool
False
>>> type(a) == str
True
>>> a = 5
>>> type(a) == bool
False
>>> type(a) == str
False
>>> type(a) == int
True
>>> a = 4.323
>>> type(a) == int
False
>>> type(a) == float
True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating really big lists

2007-09-08 Thread Ricardo Aráoz
Dr Mephesto wrote:
> On Sep 8, 3:33 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>> En Fri, 07 Sep 2007 16:16:46 -0300, Dr Mephesto <[EMAIL PROTECTED]>
>> escribi?:
>>
>>> hey, that defaultdict thing looks pretty cool...
>>> whats the overhead like for using a dictionary in python?
>> Dictionaries are heavily optimized in Python. Access time is O(1),
>> adding/removing elements is amortized O(1) (that is, constant time unless
>> it has to grow/shrink some internal structures.)
>>
>> --
>> Gabriel Genellina
> 
> well, I want to (maybe) have a dictionary where the value is a list of
> 5 lists. And I want to add a LOT of data to these lists. 10´s of
> millions of pieces of data. Will this be a big problem? I can just try
> it out in practice on monday too :)
> 
> thanks
> 
> 

targetList = myDict[someKey]# This takes normal dict access time
for j in xrange(5) :
for i in xrange(5000) :# Add a LOT of data to targetList
targetList[j].append(i)# This takes normal list access time



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


Re: How to determine the bool between the strings and ints?

2007-09-08 Thread Ricardo Aráoz
Steven D'Aprano wrote:
...
..
.
> You know, one or two examples was probably plenty. The other six or seven 
> didn't add anything to your post except length.
> 
> Also, type testing by equality is generally not a good idea. For example:
> 
> class HexInt(int):
> """Like built-in ints, but print in hex by default."""
> def __str__(self):
> return hex(self)
> __repr__ = __str__
> 
> You should be able to use a HexInt anywhere you can use an int. But not 
> if your code includes something like this:
> 
> if type(value) == int:
> do_something()
> else:
> print "Not an int!"
> 
> (What do you mean my HexInt is not an int? Of course it is.)
> 
> Better is to use isinstance(value, int). Better still is to do duck-
> typing, and avoid type() and isinstance() as much as possible.

>>> type(a) == HexInt
True

That's what I wanted (though I don't know if that's what the OP wanted).
BTW, sorry for the wasted bandwidth, didn't realize you might have such
a small bandwidth that seven lines would be a hassle. We should also
tell the blokes of the 'music' thread to stop it, I can imagine how mad
that must get you.



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


Re: Spell-checking Python source code

2007-09-08 Thread Ricardo Aráoz
John Zenger wrote:
> To my horror, someone pointed out to me yesterday that a web app I
> wrote has been prominently displaying a misspelled word.  The word was
> buried in my code.
> 
> Is there a utility out there that will help spell-check literal
> strings entered into Python source code?  I don't mean spell-check
> strings entered by the user; I mean, go through the .py file, isolate
> strings, and tell me when the strings contain misspelled words.  In an
> ideal world, my IDE would do this with a red wavy line.
> 
> I guess a second-best thing would be an easy technique to open a .py
> file and isolate all strings in it.
> 
> (I know that the better practice is to isolate user-displayed strings
> from the code, but in this case that just didn't happen.)
> 

Use the re module, identify the strings and write them to another file,
then open the file with your spell checker. Program shouldn't be more
than 10 lines.



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


Re: Spell-checking Python source code

2007-09-08 Thread Ricardo Aráoz
David wrote:
>>> (I know that the better practice is to isolate user-displayed strings
>>> from the code, but in this case that just didn't happen.)
>>>
>> Use the re module, identify the strings and write them to another file,
>> then open the file with your spell checker. Program shouldn't be more
>> than 10 lines.
>>
>>
> 
> Have a look at the tokenize python module for the regular expressions
> for extracting strings (for all possible Python string formats). On a
> Debian box you can find it here: /usr/lib/python2.4/tokenize.py
> 
> It would probably be simpler to hack a copy of that script so it
> writes all the strings in your source to a text file, which you then
> spellcheck.
> 
> Another method would be to log all the strings your web app writes, to
> a text file, then run through your entire site, and then spellcheck
> your logfile.
> 

Nice module :

import tokenize

def processStrings(type, token, (srow, scol), (erow, ecol), line):
if tokenize.tok_name[type] == 'STRING' :
print tokenize.tok_name[type], token, \
  (srow, scol), (erow, ecol), line

file = open("myprogram.py")

tokenize.tokenize(
file.readline,
processStrings
)

How would you go about writing the output to a file? I mean, I would
like to open the file at main level and pass a handle to the file to
processStrings to write to it, finally close output file at main level.
Probably a class with a processString method?


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


include myVar

2007-09-08 Thread Ricardo Aráoz
Is there a way to import a module whose name is in a variable (read from
a configuration file for example)?

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


Re: Modul (%) in python not like in C?

2007-09-09 Thread Ricardo Aráoz
John Machin wrote:
> On Sep 10, 8:05 am, Lee Harr <[EMAIL PROTECTED]> wrote:
 Python will always yield a number x = m%n such that 0 <= x < n, but
 Turbo C will always yield a number such that if x = m%n -x = -m%n.  That
 is, since 111 % 10 = 1, -111 % 10 = -1.  The two values will always
 differ by n (as used above).
>> Maybe it is an order-of-operations thing
>>
>> -111 % 10 = -1
>> (-111) % 10 = 9
>> ?
> 
> and on the other hand, maybe it's not. Try to think of any language
> where unary minus binds so loosely.

Why the theoretical argument when you can TEST your assumptions?

>>> -111 % 10
9
>>> (-111) % 10
9


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


Mac OSX sqlite problem. Missing?

2007-09-10 Thread ricardo . turpino
Hi,

I've installed Mac Python 2.5.  I'm running Mac OS X 10.4.10 on a
Macbook 1.83GHz.  I though that the python sqlite library was
installed by default as part of Mac Python 2.5, however, I still have
a problem.

Sqlite does not appear to be my system:

>>> import sqlite
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named sqlite

I ran 'sudo easy_install pysqlite' which gave me the file
'pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg', but no working pysqlite.

I then downloaded the source files and ran 'python ez_setup.py
pysqlite==2.3.5', which told me 'Using /Library/Frameworks/
Python.framework/Versions/2.5/lib/python2.5/site-packages/
pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg'

Still no working version of pysqlite.

Tried installing from source.  No problems appeared, but I still can't
use pysqlite.

The reason I am trying to install pysqlite, is to use turbogears,
which initially failed when I ran 'tg-admin sql create', it failed
with 'import sqlite.  ImportError: No module named sqlite'.

Any ideas gratefully received.

Thanks.

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


Re: Mac OSX sqlite problem. Missing?

2007-09-10 Thread ricardo . turpino
Diez B. Roggisch wrote:

>
> Are you by any chance using the python 2.3 when issuing that import
> statement?
>
> Diez

Unfortunately not :(

ibook:~/project1$ python -V
Python 2.5
ibook:~/project1$ python
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named sqlite
>>>

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


Re: Python 3K or Python 2.9?

2007-09-14 Thread Ricardo Aráoz
Bruno Desthuilliers wrote:
> TheFlyingDutchman a écrit :
>> Well I'm with Bruce Eckel - there shouldn't be any argument for the
>> object in the class method parameter list.
> 
> def fun(obj, *args, **kw):
># generic code here that do something with obj
> 
> import some_module
> some_module.SomeClass.fun = fun
> 
> This is why uniformity is important.
> 
> But anyway, I think it's quite clear that Python won't drop the explicit 
> self, so it looks like you have to live with it or choose another language.
> 
>> Bruce said that no other mainstream OO language is explicitly passing
>> the object as a parameter to class methods.
> 
> to methods. class methods gets the class as first parameter.
> 
> Anyway, there are a lot of things that Python doesn't do like "other 
> mainstream OO languages", and that's a GoodThing.
> 
> 
>> What I would like to have seen added to class definitions was the
>> forced declaration of all object variables in the class outside of
>> methods. I don't like the fact that they have to be, and can be
>> created in any method on the fly.
> 
> I definitively think you'd be happier with some other language.



Hi, I'm new to Python, I don't even fully know the language, never done
a full project in Python. What's more, probably I'll never will.
But that's not the point, the point is I want YOU people to modify the
language you know in and out, the program with which you've done many
systems, I want you to change it to suit my whims, so that I'll be
comfortable with the 3 ten liners I'll write.
TIA





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


Pseudo-Private Class Attributes

2007-09-18 Thread Ricardo Aráoz
That is self.__attributes

Been reading about the reasons to introduce them and am a little
concerned. As far as I understand it if you have a class that inherits
from two other classes which have both the same name for an attribute
then you will have a name clash because all instance attributes "wind up
in the single instance object at the bottom of the class tree".

Now I guess this means that in any real OOP project you'd better use
__attr for all your attributes, because classes are usually meant to be
subclassed and you can never know when you'll be subclassing from two
classes with attributes with the same name, and I guess you can't take
the risk of this happening because when it happens it will be hell to
find out what's going on.

Is this right?


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


Re: re question

2007-09-20 Thread Ricardo Aráoz
Dan Bar Dov wrote:
> I'm trying to construct a regular expression to match valid IP address,
> without leading zeroes (i.e
> 1.2.3.4 , 254.10.0.0 , but not
> 324.1.1.1, nor 010.10.10.1 )
> 
> This is what I come up with, and it does not work.
> 
> r'(^[12]?\d{0,2}\.){3,3}[12]?\d{0,2}'
> 
> What am I doing wrong?
> Any common knowledge IP matching RE?
> 
> Thanks,
> Dan
> 

r'^[12]\d?\d?.\d{1,3}.\d{1,3}.\d{1,3}$'

HTH

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


Counting method calls

2007-09-21 Thread Ricardo Aráoz
Hi, I know I'm being dumb but, why does it not work?

>>> class MyList(list):
... def __init__(self):
... self.calls = 0
... def __getattr__(self, name):
... self.calls += 1
... return list.__getattribute__(self, name)

>>> a = MyList()
>>> a
[]
>>> a.append(1)
>>> a
[1]
>>> a.calls
88
>>> a.append(3)
>>> a.calls
88
>>> a.sort()
>>> a
[1, 3]
>>> a.calls
176


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


Re: scope, modyfing outside object from inside the method

2007-09-24 Thread Ricardo Aráoz
Marcin Stępnicki wrote:
> Hello.
> 
> I thought I understand this, but apparently I don't :(. I'm missing
> something very basic and fundamental here, so redirecting me to the
> related documentation is welcomed as well as providing working code :).
> 
> Trivial example which works as expected:
> 
 x = {'a':123, 'b': 456}
 y = x 
 x['a']=890
 y
> {'a': 890, 'b': 456}
> 
> Now, let's try something more sophisticated (it's not real world example,
> I've made up the problem which I think illustrates my issue). Let's say
> I've got such a structure:
> 
> results = [ {'a': 12, 'b': 30 },
> {'a': 13, 'b': 40 } ]
> 
> I'd like to have each row and column in separate object of self-made
> classes.:
> 
> class mycolumn():
>   def __init__(self, resultset, row, col):
>   self.value = resultset[row][col]
>   def __str__(self):
>   return 'Column value: %s' % self.value
> 
> class myrow():
>   def __init__(self):
>   self.container = {}
>   def __str__ (self):
>   return self.container
> 
> results = [
>   {'a': 12, 'b' :30 },
> {'a': 13, 'b' :40 } 
> ]
> 
> mystruct = []
> 
> for row in results:
>   mystruct.append ( myrow() )
>   for col in row:
>   mystruct [len(mystruct)-1].container[col] = \
>mycolumn(results, results.index(row), col)
> 
> print mystruct[0].container['b'] # 12
> results[0]['b'] = 50 # 
> print mystruct[0].container['b'] # also 12 :/
> 
> In other words, I'd like to "map" the results to myrow and mycolumn
> objects, and have these new objects' values changed when I change "results".
> 
> I hope I explained it well enough :). Thank you for your time.
> 

Would this work for you?

class myrow():
  def __init__(self, idict = {}):
self.container = idict
  def __str__ (self):
return self.container.__str__()

results = [
{'a': 12, 'b' :30 },
{'a': 13, 'b' :40 }
]

mystruct = []

for row in results:
mystruct.append(myrow(row))

results[1]['b'] = 444

print results  # [{'a': 12, 'b': 30}, {'a': 13, 'b': 444}]

print mystruct # does not work ok , you should probably define
   # mystruct's __str__ method properly

# But, save for the __str__ thingy, the rest is ok.

for row in mystruct:
print row

# {'a': 12, 'b': 30}
# {'a': 13, 'b': 444}

HTH






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

Re: Delete values from a string using the index

2007-09-26 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> How do I delete or remove values from a list or string using the
> index.
> 
> If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would I do
> that?
> 
> Thanks.
> 

del a[1]
del a[-5]

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


Re: Delete values from a string using the index

2007-09-26 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> How do I delete or remove values from a list or string using the
> index.
> 
> If a = [1,2,3,4,5,6,7,8] and I want to get rid of 1 -5, how would I do
> that?
> 
> Thanks.
> 

If you want to do it all at once :

del a[1:4:2]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you please give me some advice?

2007-09-30 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
>> Hello World in Ruby (and a few other 
>> languages):http://www.oreillynet.com/ruby/blog/2005/12/hello_world.html
> 
>> Hello World in 
>> Python:http://python.about.com/od/gettingstarted/ss/helloworld.htm
> 
> I know nothing of Ruby, but just the fact that in Ruby the Hello World
> program is
> 
> puts 'Hello, World!'
> 
> whereas the Python Hello World program is
> 
> print 'Hello, World!'
> 
> suggests to me that Python is more intuitive because the word "print"
> has a meaning in English that makes sense given what you want to do,
> but "puts" just doesn't.  And, as someone who has been learning Python
> from almost no knowledge of programming, I've found it is not too bad
> in trying to keep as reasonably close to a natural language like
> English
> as possible.
> 
> I also think the mandatory indenting of Python is helpful in forcing
> new programmers to be neat and see code blocks quickly.  Plus I doubt
> the Ruby community has such a large group of helpful people and
> libraries
> and such (but I could be wrong about that, just assuming it based on
> the
> fact that Python has been around longer).
> 
> On the other hand, perhaps because Ruby is newer it has been able to
> freshly start with advantages learned from the difficulties of other
> languages.  Byung-Hee Hwang ought to go the Ruby group and see what
> they are saying.
> 
> As far as English goes, Byung-Hee, you have to admit English grammar
> is easy (though spelling is not so easy).  That anyone can speak and
> write Chinese is impressive to me, as the language looks completely
> impossible!  Good luck!
> 
> 

Errhhh. guys.. I think .kr means Korea so he would speak
Korean, not Chinese


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


Re: readline() - problem

2007-10-02 Thread Ricardo Aráoz
Paul Hankin wrote:
> On Oct 2, 12:25 pm, [EMAIL PROTECTED] wrote:
>> Hi!
>> I'm a new user of python, and have problem.
>> I have a plain ascii file:
>> 11..1
>> 12..1
>> 11..1
>> I want to create a new file which contains only lines with '1' on 15th
>> position.
>> I've tried this:
>>
>> import string
>> f=open('/test/test.asc','r')
>> o=open('/test/out.asc','w')
>> for line in f:
>> s= f.readline()
>> if s[15]=='1' :
>>o.write(s)
>> o.close()
>> f.close()
>>
>> Why it doesn't work ('s' contains ' ' )?
> 
> You're iterating over the lines in f already, so no need to call
> readline.
> 
> for line in f:
>   if line[15] == '1':
> o.write(line)
> 
> --
> Paul Hankin
> 

Be aware also that the 15th position in your line would be line[14].

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


Re: Convert on uppercase unaccentent unicode character

2007-10-05 Thread Ricardo Aráoz
Wildemar Wildenburger wrote:
> Steve Holden wrote:
>> Malheureusement, I see that absence of accented capitals is a modern 
>> phenomenon that is regarded as an impediment to the language mostly 
>> stemming from laziness of individual authors and inadequacy of low-end 
>> typesetting software. I hadn't realised I was so up-to-date ;-)
>>
>> So I will have to stop propagating this misinformation.
>>
> 
> Thats really weird, because I was taught in school that caps are not to 
> be accented. In school! Big Brother is an idiot.
> 
> I'm equally ammused by the part of JBJ's link where it says that a 
> missing acccent "fait hésiter sur la prononciation". Yeah, AS IF written 
> French had anything to do with the way it is pronounced. Not that I 
> don't like french, mind you. Everywhere outside action movies its pretty 
> cool.
> 
> /W

Then you never saw Taxi. Or some of Depardieu's ones. Or Les
adventuriers (sp?) (that's a rally old one), or I comme Icarus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] Top Programming Languages of 2013

2007-10-07 Thread Ricardo Aráoz
Alan Gauld wrote:
> "Dick Moores" <[EMAIL PROTECTED]> wrote 
> 
>> 
>>
> 
> Interesting, but I'm not sure what the criteria for "top" is.
> Is it a measure of power, popularity, usage?
> 
> Scary that HTML/CSS should be so high though 
> given its not a programming language at all!
> 
> Alan G.
> 

Besides all that, we are programmers not fashion models. Who cares which
is the "top" language, leave that for the "top models" and such. Our
trade is code, not fashion.


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


Re: How to create a file on users XP desktop

2007-10-07 Thread Ricardo Aráoz
Matimus wrote:
> On Oct 6, 8:31 pm, goldtech <[EMAIL PROTECTED]> wrote:
>> Can anyone link me or explain the following:
>>
>> I open a file in a python script. I want the new file's location to be
>> on the user's desktop in a Windows XP environment.  fileHandle = open
>> (., 'w' )  what I guess I'm looking for is an environmental
>> variable that will usually be correct on most XP desktops and will
>> work in the open statement. Or is there another way?
>>
>> Thanks
> 
> I've always used 'USERPROFILE'. I'm not sure how standard it is, but I
> have never run into any issues.
> 
> Code for your perusal:
> [code]
> import os, os.path
> prof_path = os.environ['USERPROFILE']
> filename = os.path.join(prof_path,'Desktop','filename.txt')
> f = open(filename,'w')
> try:
> # do stuff with f
> finally:
> f.close()
> [/code]
> 
> Matt
> 

You are assuming the system is not localized, that won't work if you
distribute your applications internationally. In my system it is not
"Desktop", it is "Escritorio", and I guess it will vary with every
locale. Does someone know a way to find out what name does the desktop
have?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Really basic problem

2007-10-10 Thread Ricardo Aráoz
tomamil wrote:
> i know this example is stupid and useless, but that's not the answer
> to my question.
> here it goes:
> 
> status = 0.0
> for i in range(10):
>status = status + 0.1
> 
>if status == 0.1:
>print status
>elif status == 0.2:
>print status
>elif status == 0.3:
>print status
>elif status == 0.4:
>print status
>elif status == 0.5:
>print status
>elif status == 0.6:
>print status
>elif status == 0.7:
>print status
>elif status == 0.8:
>print status
>elif status == 0.9:
>print status
>elif status == 1.0:
>print status
> 
> the expected output:
> 0.1
> 0.2
> 0.3
> 0.4
> 0.5
> 0.6
> 0.7
> 0.8
> 0.9
> 1.0
> 
> but it gives me instead:
> 0.1
> 0.2
> 0.4
> 0.5
> 0.6
> 0.7
> 
> why?
> 
> thanks,
> 
> m.
> 

Replace : status = status + 0.1
with: status = round(status + 0.1, 1)


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


Re: sorting data

2007-10-29 Thread Ricardo Aráoz
Beema shafreen wrote:
> hi all,
>I have problem to sort the data.. the file includes data as
> follow.
> file:
> chrX:123343123123343182A_16_P41787782
> chrX:123343417123343476A_16_P03762840
> chrX:123343460123343519A_16_P41787783
> chrX:1233433612334395A_16_P03655927
> chrX:123343756123343815A_16_P03762841
> chrX:123343807123343866A_16_P41787784
> chrX:123343966123344024A_16_P21578670
> chrX:123344059123344118A_16_P21578671
> chrX:1233443812334497A_16_P21384637
> chrX:123344776123344828A_16_P21578672
> chrX:123344811123344870A_16_P03762842
> chrX:123345165123345224A_16_P41787789
> chrX:123345360123345419A_16_P41787790
> chrX:123345380123345439A_16_P03762843
> chrX:123345481123345540A_16_P41787792
> chrX:123345873123345928A_16_P41787793
> chrX:123345891123345950A_16_P03762844
> 
> 
> how do is sort the file based on the column 1 and 2 with values..
> using sort option works for only one column and not for the other how do
> is sort both 1 and 2nd column so that the third column does not change.
> my script:#sorting the file
> start_lis = []
> end_lis = []
> fh = open('chromosome_location_346010.bed','r')
> for line in fh.readlines():
> data = line.strip().split('\t')
> start = data[1].strip()
> end = data[2].strip()
> probe_id  = data[3].strip()
> start_lis.append(start)
>end_lis.append(end)
> start_lis.sort()
> end_lis.sort()
> for k in start_lis:
>  for i in end_lis
>print k , i , probe_id(this doesnot worK)
>   result = start#end#probe_id --->this doesnot work...
> print result
>  
> What is the error and how do is sort a file based on the two column  to
> get the fourth column also with that.
> regards
> shafreen
> 

Don't know if this is what you are looking for :

dataList = []

for line in open('chromosome_location_346010.bed','r') :
data = line.strip().split('\t')
start = data[1].strip()
end = data[2].strip()
probe_id  = data[3].strip()
dataList.append((start, end, probe_id))

dataList.sort(key=lambda x: x[1].rjust(20) + x[2].rjust(20))

for item in dataList:
print 'Start :', item[0].rjust(11) \
  , '  - End :', item[1].rjust(11) \
  , '  - Probe :', item[2]


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


  1   2   >