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:irmen.nos...@xs4all.nl>> 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


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, ayushpokha...@gmail.com 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: Tree library - multiple children

2013-12-13 Thread Ricardo Aráoz

El 13/12/13 18:05, bucha...@gmail.com 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: 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-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 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


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


Fwd: Re: Wrapping around a list

2013-11-28 Thread Ricardo Aráoz


El 27/11/13 07:46, amjad...@gmail.com 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


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


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: 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: Best way to gain root privileges

2011-02-18 Thread Ricardo Aráoz

On 17/02/2011 06:46 p.m., Steven D'Aprano wrote:

On Thu, 17 Feb 2011 19:44:20 +, Katie T wrote:


Running any kind of script sudo'd is a bad idea, it's very very hard (in
many cases impossible) to do securely. Root permissions in general
should only be used for what they're needed for and nothing else (that
means getting the permission, doing the stuff that needs to be done as
root, and then returning back to normal privs), anything else is just
asking for trouble.

I agree with your general point, but the specific point to avoid running
scripts with sudo? Are you sure you're not conflating sudo with setuid?
By my reading, sudo is far preferred over running scripts setuid root.

Linux, for example, simply will not run scripts setuid root because of
the security risk, while running things using sudo is considered best
practice, and much preferred over logging in as root. The idea of sudo is
to do exactly what you say: doing the stuff needed as root with elevated
permission, then returning to normal.


Maybe this is a bit OT, as it involves the OS and security system, but 
considering the general knowledge assembled in this list and that it is 
related to the thread...


I've always asked myself why can't a program be used by users of a 
certain group but run with the privileges of some other user, not 
necessarily the one that uses it, but one created specifically for the 
tasks the program is responsible for.


AFAIK in Linux a program will only run with the privileges of the user 
who runs it.
But I can see no reason (other than it is not actually permitted by the 
OS) that a program can't run with it's *own* privileges. Many a time I 
have wanted to allow access to certain privileges to a user but *only* 
through a program. As far as security is concerned it would be enough 
that only root has permission to give the said program running 
privileges (privileges different from those of the user that is actually 
running it), that only allowed users may modify the program, and that 
*other* users may only run it. This would address the issue of someone 
modifying the program to gain access to it's privileges. Now, if someone 
is able to gain illegal privileges to modify the program, then there 
*is* a security hole and the program is not really the problem.


Am I misinformed and you can actually do this in Linux? Am I being naive 
security wise?





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


Re: death of newsgroups (Microsoft closing their newsgroups)

2010-07-14 Thread Ricardo Aráoz

On 14/07/2010 12:19 p.m., Kenneth Tilton wrote:

Steven D'Aprano wrote:

On Tue, 13 Jul 2010 23:24:12 -0400, Kenneth Tilton wrote:


The moral? If you look for the spam, you'll find it.


And if you *don't* look for spam, you can be sure that some goose 
will reply to it and get it past your filters. Thanks for that 
Kenneth, if that is your name and you're not a Xah Lee sock-puppet.


Let me see if I have this right. Your technique for reducing unwanted 
traffic is to openly insult one of the participants? That is how you 
clean things up? Because most people on Usenet respond well to 
personal insults and hush up? I have so much to learn!


PLONK!!!

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


Re: I strongly dislike Python 3

2010-07-01 Thread Ricardo Aráoz

On 30/06/2010 01:23 p.m., Lie Ryan wrote:

On 07/01/10 01:42, Michele Simionato wrote:


On Jun 30, 2:52 pm, Lie Ryan  wrote:


On 06/27/10 11:24, Steven D'Aprano wrote:



Producing print function takes a little bit more effort than producing a
print statement.




(1) The main use-cases for print are quick (and usually dirty) scripts,
interactive use, and as a debugging aid.


That is precisely how the quick-and-dirty syntax of print statement can
be justified. While debugging, you'll need to be able to quickly add and
delete prints here and there, and the extra parens can quickly become
irritating.


Actually when debugging I use pdb which uses "p" (no parens) for
printing, so having
print or print() would not make any difference for me.


You mean I have to start a full-blown debugger to figure out the value
of a variable? No thanks, debugger has its use for stepping through
program, but not when printing values is sufficient.



Let's, as an exercise, count how many keystrokes and clicks you have 
spent on this thread and others complaining on the subject. How many 
programs do you think you could debug with this count (considering you 
spend a stroke in each print sentence, and I assume you being smart will 
not need many prints to figure out problem)?
So let's say you'll keep complaining for a couple of years till you are 
ready to adopt Py3. You see what I mean? If you stop complaining right 
now the keystrokes you'll save will mean you'll have no extra typing to 
do at all.

HTH


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


Re: GUIs - A Modest Proposal

2010-06-14 Thread Ricardo Aráoz

On 14/06/2010 02:57 p.m., rantingrick wrote:

On Jun 14, 11:17 am, Stephen Hansen  wrote:
   

And the recursive flow of the DOM is powerful
 

This style of speaking reminds me of our former hillbilly president
(no not Clinton, he was the eloquent hillbilly!) No i am referring to
good old "George Dubya". He left us with so many juicy sound bites
   



PLONK 

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


Re: Sometimes the python shell cannot recognize the presence of an attribute.

2010-04-12 Thread Ricardo Aráoz
Aahz wrote:
> In article ,
> Justin Park   wrote:
>   
>> The real problem is this.  When I started working on the package,
>> somehow all of indentations were made by space-bars instead of using
>> tabs.  But when I am implementing my own on top of it, I still use tabs
>> to make indentations.
>> 
>
> Stop using TAB.  Allowing TAB was a mistake.  Spaces are the One True
> Way when formatting Python code.
>   
Because .



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


Re: "Usability, the Soul of Python"

2010-03-31 Thread Ricardo Aráoz
Lawrence D'Oliveiro wrote:
> In message <20100331003241.47fa9...@vulcan.local>, Robert Fendt wrote:
>
>   
>> The braces are gone, and with them the holy wars.
>> 
>
> Let me start a new one. I would still put in some kind of explicit indicator 
> of the end of the grouping construct:
>
> count = 99
> while count > 0:
> print u'%d slabs of spam in my mail!' % count
> print u'%d slabs of spam,' % count
> print u'Send one to abuse and Just Hit Delete,'
> count += 1
> print u'%d slabs of spam in my mail!' % count
> print u''
> #end while
>   

I'd much prefer the following :

## Beginning of a program block
count = 99  # Set the variable count as a name for the
integer object 99
while count > 0:  # if count is the name of 0 or less then
exit the loop (this will NEVER happen)
## Beginning of a while loop
print u'%d slabs of spam in my mail!' % count
print u'%d slabs of spam,' % count
print u'Send one to abuse and Just Hit Delete,'
count += 1
print u'%d slabs of spam in my mail!' % count
print u''
## End of a while loop
## End of a program block

Which is reeeaaally easier to understand than :

count = 99
while True
print u'%d slabs of spam in my mail!' % count
print u'%d slabs of spam,' % count
print u'Send one to abuse and Just Hit Delete,'
count += 1
print u'%d slabs of spam in my mail!' % count
print u''



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


Re: Classes as namespaces?

2010-03-26 Thread Ricardo Aráoz
Luis M. González wrote:
> On 26 mar, 11:49, kj  wrote:
>   
>> What's the word on using "classes as namespaces"?  E.g.
>>
>> class _cfg(object):
>> spam = 1
>> jambon = 3
>> huevos = 2
>>
>> breakfast = (_cfg.spam, _cfg.jambon, _cfg.huevos)
>> 
>
> I see no problem.
> I wouldn't mix English, French and Spanish in the same recipe though...
>   
Why? Do you think it might get over cooked? ;c)

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


Exception in pydoc

2010-02-26 Thread Ricardo Aráoz
I'm developing an in house app. Many coders here are not fluent in
english, so docstrings must be in Spanish in spite of recommendations
that docstrings better be in English.
When I use accented characters (in this case an 'ó') in my docstrings I
get :
>>> help('OpMejoraBizobj')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\site.py", line 346, in __call__
return pydoc.help(*args, **kwds)
  File "C:\Python25\lib\pydoc.py", line 1645, in __call__
self.help(request)
  File "C:\Python25\lib\pydoc.py", line 1687, in help
elif request: doc(request, 'Help on %s:')
  File "C:\Python25\lib\pydoc.py", line 1481, in doc
pager(title % desc + '\n\n' + text.document(object, name))
  File "C:\Python25\lib\pydoc.py", line 324, in document
if inspect.ismodule(object): return self.docmodule(*args)
  File "C:\Python25\lib\pydoc.py", line 1072, in docmodule
contents.append(self.document(value, key, name))
  File "C:\Python25\lib\pydoc.py", line 325, in document
if inspect.isclass(object): return self.docclass(*args)
  File "C:\Python25\lib\pydoc.py", line 1208, in docclass
contents = '\n'.join(contents)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
115: ordinal not in range(128)

The file's first two lines are :
"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

Does pydoc only deal with ASCII?



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


Re: Your beloved python features

2010-02-10 Thread Ricardo Aráoz
Bruce C. Baker wrote:
> "Terry Reedy"  wrote in message 
> news:mailman.1929.1265328905.28905.python-l...@python.org...
>   
>> Iterators, and in particular, generators.
>> A killer feature.
>>
>> Terry Jan Reedy
>>
>> 
>
> Neither unique to Python.
>
> And then're the other killer "features" superfluous ":"s and rigid 
> formatting! 
>   

H Let's see. nope, I could not find the "unique" word
neither in the subject or in the cited text.
I've had a strange feeling last weeks.
Two possible explanations come to mind :
a) The list is under a concerted troll attack.
b) Idiocy is contagious.

I wonder which...

P.S. : will the indentation of the choices be noticed? Shouldn't I put
them within braces?

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


Re: yet another list comprehension question

2009-05-05 Thread Ricardo Aráoz
namekuseijin wrote:
> On May 4, 9:15 am, David Robinow  wrote:
>   
>> On Mon, May 4, 2009 at 2:33 AM, namekuseijin
>>
>>  wrote:
>> 
>> ls = [(1,2), (3,4), (5, None), (6,7), (8, None)]
>> [(x,y) for (x,y) in ls if y]
>> 
>>> [(1, 2), (3, 4), (6, 7)]
>>>   
>> Nope. That filters out 0 as well as None. Not what the OP asked for.
>> 
>
> True.  I'm still a C programmer at heart I guess.  ah, the flexibility
> of 0... ;)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>   
This seems to work for any length tuples :

>>> a = [(1,2), (3,4, 'goes'), (5,None), (6,7, 8, 'as', None), (8,
None), (9, 0)]
>>> [tup for tup in a if not [e for e in tup if e == None]]
[(1, 2), (3, 4, 'goes'), (9, 0)]


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


PDB break

2009-04-24 Thread Ricardo Aráoz
Hi, I need to track where a certain condition is met in a program.
Checking on pdb docs I find the break statement :

b(reak) [[/filename/:]/lineno/ | /function/[, /condition/]]

But it requires me to name a line/function where my condition is tested.
Now there are far too many places in a project where this condition may
be set to true, and I might overlook some (and it would take an awful
lot of time to identify them all). Is there a statement that allows me
to stop execution when a condition is met regardless of where this happens?

Thx.

Ricardo.

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


Re: object knows which object called it?

2009-04-07 Thread Ricardo Aráoz
Reckoner wrote:
>> hi,
>>
>> I have the following problem: I have two objects, say, A and B, which
>> are both legitimate stand-alone objects with lives of their own.
>>
>> A contains B as a property, so I often do
>>
>> A.B.foo()
>>
>> the problem is that some functions inside of B actually need A
>> (remember I said they were both standalone objects), so I have to
>> often do:
>>
>> A.B.foo_func(A)
>>
>> Which is kind of awkward.
>>
>> Is there some way that B.foo_func() could somehow know that it was
>> called as a property of A in this way?
>>
>> Note that I'm looking for the calling object and NOT the calling
>> function.
>>
>> Thanks in advance.
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>  
Maybe this would work for you?

>>> class B(object) :
... def __init__(self, owner=None) :
... self.owner = owner
... def someMethod(self) :
... print self.owner.name
...
>>> class A(object) :
... def __init__(self, name='class A') :
... self.B = B(owner=self)
... self.name = name
...
>>> instA1 = A('one')
>>> instA2 = A('two')
>>> instA1.B.someMethod()
one
>>> instA2.B.someMethod()
two
>>>




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


Re: python for loop

2009-04-01 Thread Ricardo Aráoz
Lada Kugis wrote:
> On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano
>  wrote:
>
>   
>> Why Python (and other languages) count from zero instead of one, and 
>> why half-open intervals are better than closed intervals:
>>
>> http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-zero/
>> http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
>> 
>
> steven, thanks for answering,
>
> yes, i saw the second one a little time ago (someone else posted it as
> well in really cute handwriting version :) and the first time just
> now, but the examples which both of them give don't seem to me to be
> that relevant, e.g. the pros don't overcome the cons.
>
> imho, although both sides (mathematical vs engineer) adress some
> points, none of them give the final decisive argument.
> i understand the math. point of view, but from the practical side it
> is not good. it goes nicely into his tidy theory of everything, but
> practical and intuitive it is not. as i said, being an engineer, i
> tend towards the other side, so this is biased opinion (nobody can be
> unbiased) but from a practical side it seems unpractical for
> engineering problems (and to me, the purpose of computers is to help
> humans to build a better world, not to prove theories - theories are
> useless if they don't help us in reality. so we should try to adapt
> computing to real world, not our world to computers).
>   
Speaking about "reality", it would have saved a lot of time (but maybe
not fun) to just do :

>>> myRange = lambda x : range(1, x+1)
>>> myRange(4)
[1, 2, 3, 4]

Put it in a file named "MyIntuition.py" in the python path, and then in
your programs you can code :
from MyIntuition import myRange




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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-22 Thread Ricardo Aráoz
Paul Rubin wrote:
> Mark Wooding  writes:
>   
>> Some people (let's call them `type A programmers') have decided that
>> they want to be assisted with writing correct programs...
>> Other people (`type B programmers') don't like having their (apparently?
>> possibly?) correct programs rejected
>> I think trying to persuade a type A programmer that he wants to work
>> like a type B programmer, or /vice versa/, is difficult, bordering on
>> futile.  Type A stereotypes type B as a bunch of ill-disciplined
>> reckless hackers; type B stereotypes type A as killjoy disciplinarians.
>> Meeting in the middle is difficult.  (`We just want to add a little
>> safety.'  `You want to take away our freedom!'  Etc., /ad nauseam/.)
>> 
>
> That's an interesting analysis.  You know, I think I'm really a type B
> programmer, interested in type A techniques and tools for the same
> reason someone who naturally sleeps late is interested in extra-loud
> alarm clocks.
>
> Also, the application area matters.  There is a difference between
> programming for one's own enjoyment or to do a personal task, and
> writing programs whose reliability or lack of it can affect other
> people's lives.  I've never done any safety-critical programming but I
> do a fair amount of security-oriented Internet programming.  As such,
> I have to always assume that my programs will be attacked by people
> who are smarter than I am and know more than I do.  I can't possibly
> out-think them.  If I don't see problems in a program, it's still
> plausible that someone smarter than me will spot something I missed.
> Therefore, my failure to detect the presence of problems is not
> reassuring.  What I want is means of verifying the absence of
> problems.  
>   

M. your "means of verifying the absence of problems" were
coded/thought by some other person who also has a measurable amount of
intelligence. So it follows that there will be somebody else who is
smarter and will spot something this other person missed and will be
able to subvert those "means". So it would seem that by thinking you can
"verify" the absence of problems you are trying to get a false sense of
security that actually does not exist.

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


Formal specification and proof (was : Does Python really follow its philosophy of "Readability counts"?)

2009-01-22 Thread Ricardo Aráoz
Mark Wooding wrote:
> Steven D'Aprano  writes:
>
>   
>
>> No it's not. It's *practical*. There are domains where *by law* code
>> needs to meet all sorts of strict standards to prove safety and
>> security, and Python *simply cannot meet those standards*.
>> 
>
> Codswallop.  One can prove stuff about Python programs using the same
> techniques as one uses for any other language.  I've done it.  Other
> languages have better automated tools, it's true -- but the techniques
> are basically the same.
>
>   
I've seen this kind of thinking and there are a couple of things about
which I've always wondered.
Let's say you formally specify an application (hey! you are a
zillionaire and can afford it), and that after the app is coded you
formally prove that it complies with the specification. Cool! now your
app is safe? NO, because your formal proof was done over source code and
the compiler has not been formally specified and proven. So your app
might still fail. So let's say you have the $ to do that and you get a
perfect compiler. Are you safe? NO, because the code generated by the
compiler makes calls to the OS which is not specified. So let's assume
you are a world leader and you spend a little war's money in fully
specifying and proving an OS. Are you safe? NO, because the processor
and other hardware logic has NOT been specified. And on and on.

What I've seen engineers do when they need extra safety is to put in
place independently developed and operated redundant systems, at least
three, and the system will do whatever two of the independent systems
agree on. So I guess if I really wanted to be safe with a system I'd
have it made by at least three different teams (yes, also the
requirements should be written by different teams) in different
languages under different OS's and different independent machines. And
THEN I would have some measure of safety (and this would certainly be
more cost effective than the formal specification route).


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


Re: drive a desktop app from python?

2009-01-09 Thread Ricardo Aráoz
James Stroud wrote:
> Tim Arnold wrote:
>> Hi, I don't even know what to google for on this one. I need to drive
>> a commercial desktop app (on windows xp) since the app doesn't have a
>> batch interface.  It's intended to analyze one file at a time and
>> display a report.
>>
>> I can get the thing to write out the report an html browser, but I
>> have thousands of files I need it to analyze every night.
>>
>> Is there any lib or recipe(s) for doing something like this via python?
>
> You are a little thin on details here. My only advice at this point is
> to check out os.system, which is the simplest option. From there you
> can move to the popen2 module for greater control, but if you are
> talking about a gui app, you may run into hang-ups.
>
> A quick recipe would be the following pretend application that
> recursively descends from the current directory calling the utility
> named "dosapp" on every file it finds that ends with "jpg" (what
> "dosapp" does is left to your imagination):
>
>
>
> import os
>
> def doit(suffix, adir, filenames):
>   for afile in filenames:
> if afile.endswith(suffix):
>   pathname = os.path.join(adir, afile)
>   os.system('dosapp %s' % pathname)
>
>
> top = '.'
> suffix = '.jpg'
>
> os.path.walk(top, doit, suffix)
>
>
> Read the docs on os.path.walk, of course.
>
> James
>
>
>From a search in my mail's lists :

http://www.openqa.org/pywinauto/
or
http://pywinauto.openqa.org/

http://wwwsearch.sourceforge.net/mechanize/

http://www.autoitscript.com/autoit3/
(see the COM server)

http://people.redhat.com/zcerza/dogtail/

HTH



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


Re: Snippets management

2008-11-07 Thread Ricardo Aráoz
Edwin B. wrote:
> Robert Lehmann <[EMAIL PROTECTED]> writes:
> 
>> I don't think there is a one-size-fits-all solution.
> 
> I definetly agree.
> 
>> Setting up a 'snippets' repository sounds good if you just want to be 
>> able to look back at what you've done and/or have a place to stash away 
>> quick tests. I have set up a 'sandbox' folder (unrevisioned) and put 
>> together a few shell aliases for easier access and it works pretty well. 
>> I almost never look back at that code though.
>>
>> If you develop a lot of small scripts you think you'll reuse in your 
>> daily routine, you should add a dedicated 'bin' directory and add it to 
>> your PATH.
> 
> This is a nice method. I'm already putting it to use. I've learned about
> /usr/bin and /usr/local/bin so I went ahead and created $HOME/bin and
> added it to my path for this sort of code.
> 
> Now, I was thinking more of a notes+code program. Let me give you an
> example:
> 
> I use Emacs.app (Emacs compiled with --with-ns) and in order to get a
> meta key in the Spanish keyboard on my Mac I had to try different lines
> but I didn't want to keep all these tries in my .emacs file. I also
> wanted to keep the lines that didn't work for later tests in my Free BSD
> PC (also with a Spanish keyboard). So I keep all of them in my notebook.
> 
> Then, I start coding Python. This time I try to translate an old PHP
> script to Python and want to keep a few important lines visible. It'll
> be nice to take some notes of the main differences in my scripts in a
> different place. Like a student's notebook. Once again, all this goes to
> my little program.
> 
> Then, I remember I had to run some Mac maintenance commands... I don't
> remember the complete line very well, so I go to my notebook.
> 
> My point is that sometimes not every note is useful for a program. I
> guess as I gain experience all these little notes will be kept in my
> mind ;). But as a newbie it seems useful.
> 
> As r said, I think it'll be good to write this program. If it doesn't
> result in a very useful piece, it'll be a good way to practice.
> 
> I forgot to mention I don't use a notes program to keep personal and
> programming notes separately.
> 
> Thanks mate!
> 
> P.S.: Man I hope my English doesn't suck too much.
> 

Since you are in Linux you should definitely check "Basket". Go to it's
website and you'll be hooked, just what you need.



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


Re: a short-cut command for globals().clear() ??

2008-09-23 Thread Ricardo Aráoz
Terry Reedy wrote:
> MRAB wrote:
>>
>> How about something like this:
>>
>> def clear_workspace():
>> keep_set = set(['__builtins__', '__doc__', '__name__',
>> 'clear_workspace'])
> 
> For 2.6/3.0, add __package__ to the list to be kept.
> 
>> for x in globals().keys():
>> if x not in keep_set:
>> del globals()[x]


Or... you might have a script clearWorkspace.py :

-
initGlobals = globals().keys()

def clearWorkspace() :
for gVar in globals().keys() :
if gVar not in initGlobals :
del globals()[gVar]
-

Which you run before doing anything else. Then you don't mind if
additions were made to the list to keep, or if you are using something
like pyCrust which has its own initial globals, or if you want to keep
some global vars of your own (in which case you run clearWorkspace AFTER
you instantiate your global vars).


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


Re: Can anyone suggest a good crypto package?

2008-09-10 Thread Ricardo Aráoz
Fett wrote:
> On Sep 4, 2:23 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>> On Sep 4, 1:39 pm, Fett <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> I need a crypto package that works on windows with python 2.5. Can
>>> anyone suggest one for me?
>>> I have been searching for a couple days for a good cryptography
>>> package to use for public/private key encryption, at this point I
>>> would settle for symmetric even.
>>> Every encryption package I have found for python was either operating
>>> system specific (read *nix 
>>> only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/
>>> There was one exception, this version was specifically built to run on
>>> any platform (yay), but the compiler for windows complained that I
>>> wasn't using python2.2 (though the package was said to only need 2.2
>>> or newer).
>>> Is there any crypto package that is actually written in python? I
>>> seriously don't care how slow it is.
>> How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads
>>
>> Mike
> 
> Seems that this is intended more for webapps or something, I intend to
> use this for a client application. This means that I can't require
> outside dependencies, or I risk annoying the clients (if you have
> installed many open-source projects with dependencies that aren't
> handled by portage/apt-get, you know what I would be doing to them).
> 
> I seriously can't believe that there isn't a single python native
> crypto package. Why do they all need to have outside dependencies?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


Hi, maybe I'm a little late but today scanning through "The daily
Python-URL" I came through something that might be pertinent.

The link is http://www.keyczar.org/
And here is the intro to the site :
"""
Keyczar is an open source cryptographic toolkit designed to make it
easier and safer for developers to use cryptography in their
applications. Keyczar supports authentication and encryption with both
symmetric and asymmetric keys. Some features of Keyczar include:

* A simple API
* Key rotation and versioning
* Safe default algorithms, modes, and key lengths
* Automated generation of initialization vectors and ciphertext
signatures
* Java and Python implementations (C++ coming soon)
* International support in Java (Python coming soon)

Keyczar was originally developed by members of the Google Security Team
and is released under an Apache 2.0 license.
"""

HTH


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


Re: Read dbf file as read only

2008-08-26 Thread Ricardo Aráoz

ajak_yahoo wrote:

Hi,
 
How can I access a foxpro dbf file from my python program.

 I just want to read it as a read only file.
Regards,




Check Paul McNett's article in FoxTalk "Exploring Python from a Visual 
Foxpro Perspective" and check the code in :


http://www.paulmcnett.com/vfp/09MCNESC.zip


HTH

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


Re: who to call a list of method inside the class itself

2008-08-20 Thread Ricardo Aráoz

Terry Reedy wrote:


 [EMAIL PROTECTED] wrote:

Is the following code is ok. who to call all method.
It is working but the call to m() without a reference to self seems
strange


The reference to self is bound to the methods by the way you look them up.



class CustomMethod:
def method1(self):

def method2(self):

def method3(self):
   

def getAllMethod(self):
return [self.method1, self.method2, self.method3]

def applyAll(self):
for m in self.getAllMethod():
m()


If the list is static, there is no need to calculate it more than once, 
at class-definition time.  I might do this like so:


class CustomMethod:
...
all_methods = [method1, method2, method3]
def apply_all(self):
for m in self.all_methods:
m(self)

Class code has access to the results of previous class code.



BTW, how would you guys go about registering the functions to be 
returned by apply_all()?

I mean something like :

class CustomMethod(object) :
def __init__(self) :
self.methodList = []

def method1(self) :
...
self.registerMe(send a reference to this method)

def method2(self) :
...
self.registerMe(send a reference to this method)

def registerMe(receive a reference to some method) :
self.methodList.append(the reference to the method)

def getAllMethods(self) :
return self.methodList

etc.





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


Re: Do this as a list comprehension?

2008-06-09 Thread Ricardo Aráoz

Mensanator wrote:

On Jun 6, 1:40 pm, The Pythonista <[EMAIL PROTECTED]> wrote:

On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:

Is it possible to write a list comprehension for this so as to produce a
list of two-item tuples?
base_scores = range(8, 19)
score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
score_costs)

score_costs = [(base_scores[i], score_costs[i]) for i in range (len
(base_scores))]


What happens if your iterables aren't the same length?


But, I'd rather just use zip. :-)


And with zip() you won't get an error, but it won't be correct,
either.



Wouldn't it be nice to have leftZip(), rightZip(), and fullZip() for 
when the lists have different lengths? The final tuples for a leftZip 
could be in the form (value, ) and for right zip (, value) (though I 
think this last tuple is not allowed in python's syntax, we might define 
a "Null" or "Empty" name to act as a place holder in the resulting tuples).


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


Re: python vs. grep

2008-05-13 Thread Ricardo Aráoz

Ville M. Vainio wrote:

Ricardo Aráoz <[EMAIL PROTECTED]> writes:


The easy/simple (too easy/simple?) way I see out of it is to read THE
WHOLE file into memory and don't worry. But what if the file is too


The easiest and simplest approach is often the best with
Python. 


Keep forgetting that!



If the file is too big, you might want to look up mmap:

http://effbot.org/librarybook/mmap.htm


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


Re: python vs. grep

2008-05-12 Thread Ricardo Aráoz

Ville Vainio wrote:

On May 8, 8:11 pm, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:


All these examples assume your regular expression will not span multiple
lines, but this can easily be the case. How would you process the file
with regular expressions that span multiple lines?


re.findall/ finditer, as I said earlier.



Hi, sorry took so long to answer. Too much work.

findall/finditer do not address the issue, they merely find ALL the 
matches in a STRING. But if you keep reading the files a line at a time 
(as most examples given in this thread do) then you are STILL in trouble 
when a regular expression spans multiple lines.
The easy/simple (too easy/simple?) way I see out of it is to read THE 
WHOLE file into memory and don't worry. But what if the file is too 
heavy? So I was wondering if there is any other way out of it. Does grep 
read the whole file into memory? Does it ONLY process a line at a time?


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


Re: python vs. grep

2008-05-08 Thread Ricardo Aráoz

Anton Slesarev wrote:

I try to save my time not cpu cycles)

I've got file which I really need to parse:
-rw-rw-r--  1 xxx  xxx  3381564736 May  7 09:29 bigfile

That's my results:

$ time grep "python" bigfile | wc -l
2470

real0m4.744s
user0m2.441s
sys 0m2.307s

And python scripts:

import sys

if len(sys.argv) != 3:
   print 'grep.py  '
   sys.exit(1)

f = open(sys.argv[2],'r')

print ''.join((line for line in f if sys.argv[1] in line)),

$ time python grep.py "python" bigfile | wc -l
2470

real0m37.225s
user0m34.215s
sys 0m3.009s

Second script:

import sys

if len(sys.argv) != 3:
   print 'grepwc.py  '
   sys.exit(1)

f = open(sys.argv[2],'r',1)

print sum((1 for line in f if sys.argv[1] in line)),


time python grepwc.py "python" bigfile
2470

real0m39.357s
user0m34.410s
sys 0m4.491s

40 sec and 5. This is really sad...

That was on freeBSD.



On windows cygwin.

Size of bigfile is ~50 mb

$ time grep "python" bigfile | wc -l
51

real0m0.196s
user0m0.169s
sys 0m0.046s

$ time python grepwc.py "python" bigfile
51

real0m25.485s
user0m2.733s
sys 0m0.375s

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




All these examples assume your regular expression will not span multiple 
lines, but this can easily be the case. How would you process the file 
with regular expressions that span multiple lines?






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


Re: SV: Where's GUI for Python?

2008-03-01 Thread Ricardo Aráoz
K Viltersten wrote:
>>>import tkininter
>>>
>> When that fails, try without the stutter 
>>
>> import tkinter
> 
> 
> I must be doing something wrong because
> neither tkinter nor tkininter works.
> I tried both with and without stuttering.
> I even asked my wife to stutter some but,
> sadly, to no avail.
> 
> When Tim Chase mentioned "battery-installed", 
> i interpreted it as "all is there". It seems 
> that either
> a) not all the batteries are installed in my
> version (v2.5.2)
> or
> b) some setup/linkage needs to be performed
> in order to get the GUI running.
> 
> The error itself is:
> ImportError: No module named tkinter
> 
> Suggestions?
> 

import Tkinter

(first letter is uppercase)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-24 Thread Ricardo Aráoz
zaley wrote:
> On 2月25日, 上午10时35分, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> zaley wrote:
>>>>> So I hope I can find something helpful in open source IDE for python.
>>>> Exactly so. PyScripter does it easy, besides you can have in different
...
..
>>
>> >From then on you are on your own.
>>
>> HTH
> 
> 
> Hehe. You misunderstand me really.  I know what you say
> I just want to know how to realize it using C language or other
> language.
> I need such source code to study

Ooops! Sorry. My fault.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-24 Thread Ricardo Aráoz
zaley wrote:

>>> So I hope I can find something helpful in open source IDE for python.
>> Exactly so. PyScripter does it easy, besides you can have in different
>> tabs all the modules of your application. You just hit the run button
>> and your program runs, you hit the debug button and you start going step
>> by step. It's free, easy to install, just give it a try and if you don't
>> like it just trash it.
> 
> I just want to know how to do it!!

Ok, I hope I'm not misunderstanding you.
You go to http://www.mmm-experts.com/Downloads.aspx
and you download PyScripter (windows installer). Then you run the
downloaded file (that would be PyScripter-setup.exe) and that will
install PyScripter in your machine. You run PyScripter, click the "open"
 button or menu File/Open... and choose the program you want to debug.
It  will be opened in an edit window in your PyScripter main window.
Then you click on "Step into subroutine" button or just press  and
you'll be in the first line of your program. From then on you keep
clicking "Step into subroutine" () or "Step over next function call"
() or "Step out of the current subroutine" or "Run to cursor" as you
see fit. You can add breakpoints just by clicking to the left of the
line numbers or the appropriate button. You can watch what's going on in
your program in the lower partition of your main window where you have a
"Call Stack" tab and also "Variables", "Watches", "Breakpoints",
"Output" and "Messages" tabs.
>From then on you are on your own.

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


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-24 Thread Ricardo Aráoz
zaley wrote:
> On Feb 24, 6:48 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Lie wrote:
>>> On Feb 23, 4:02 pm, zaley <[EMAIL PROTECTED]> wrote:
>>>> On Feb 22, 11:06 pm, "Jesper"  wrote:
>>>>> Give PyScripter fromhttp://www.mmm-experts.com/atry
>>>>> It is for Windows, though it is written in Delphi and not in C/C++
>>>>> /Jesper
>>>>> "zaley" <[EMAIL PROTECTED]> skrev i en meddelelsenews:[EMAIL PROTECTED]
>>>>> Of course, python scripts debugger
>>>>> On 2ÔÂ22ÈÕ, ÏÂÎç3ʱ22·Ö, zaley <[EMAIL PROTECTED]> wrote:
>>>>>> My project need a simple scripts debugger . I hope I can find
>>>>>> something instructive
>>>>>> Stefan Behnel дµÀ£º
>>>>>>> zaley wrote:
>>>>>>>> Is there a open souce IDE writen by C( C++) or partly writen by C( C+
>>>>>>>> +)?
>>>>>>> Tons of them. What do you want to do with it?
>>>>>>> Stefan- Hide quoted text -
>>>>> - Show quoted text -
>>>> But PyScripter is not a open source project
>>> Am I correct to say that the reason why you wanted an open source C++
>>> IDE is because you wanted the freedom to modify your own programming
>>> environment?
>> >From the "About" window in PyScripter :
>>
>> """
>> A freeware, open source Python scripter integrated
>> development environment created with the ambition to bring to
>> the Python community the quality and functionality available in
>> commercial IDEs available for other languages.
>> """
>>
>> So I think we could say PyScripter IS an open source project.- Hide quoted 
>> text -
>>
>> - Show quoted text -
> 
> Really, what I want to do is that scripts can be executed step by
> step .
> I know By "Py_Runstring"  clauses  in main function can executed by
> step .
> But I can't know how to step into a function and how to step in a
> function.
> So I hope I can find something helpful in open source IDE for python.

Exactly so. PyScripter does it easy, besides you can have in different
tabs all the modules of your application. You just hit the run button
and your program runs, you hit the debug button and you start going step
by step. It's free, easy to install, just give it a try and if you don't
like it just trash it.

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


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-23 Thread Ricardo Aráoz
Lie wrote:
> On Feb 23, 4:02 pm, zaley <[EMAIL PROTECTED]> wrote:
>> On Feb 22, 11:06 pm, "Jesper"  wrote:
>>
>>
>>
>>> Give PyScripter fromhttp://www.mmm-experts.com/atry
>>> It is for Windows, though it is written in Delphi and not in C/C++
>>> /Jesper
>>> "zaley" <[EMAIL PROTECTED]> skrev i en meddelelsenews:[EMAIL PROTECTED]
>>> Of course, python scripts debugger
>>> On 2ÔÂ22ÈÕ, ÏÂÎç3ʱ22·Ö, zaley <[EMAIL PROTECTED]> wrote:
 My project need a simple scripts debugger . I hope I can find
 something instructive
 Stefan Behnel дµÀ£º
> zaley wrote:
>> Is there a open souce IDE writen by C( C++) or partly writen by C( C+
>> +)?
> Tons of them. What do you want to do with it?
> Stefan- Hide quoted text -
>>> - Show quoted text -
>> But PyScripter is not a open source project
> 
> Am I correct to say that the reason why you wanted an open source C++
> IDE is because you wanted the freedom to modify your own programming
> environment?

>From the "About" window in PyScripter :
"""
A freeware, open source Python scripter integrated
development environment created with the ambition to bring to
the Python community the quality and functionality available in
commercial IDEs available for other languages.
"""

So I think we could say PyScripter IS an open source project.

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


Re: ILeo (IPython-Leo bridge); a marriage made in heaven?

2008-02-23 Thread Ricardo Aráoz
Edward K Ream wrote:
>> Here is something cool that will rock your world (ok, excuse the slight 
>> hyperbole):
> 
> Many thanks for this posting, Ville.  It is indeed very cool:
> 
> - It shows how Leo can be used *now* as an IPython notebook.
> 
> - It expands the notion of what is possible with Leo/IPython/Python scripts.
> 
> Your ideas are destined to be of great importance to both the IPython and 
> Leo communities.
> I shall continue this discussion at:
> 
> http://groups.google.com/group/leo-editor/browse_thread/thread/3747a122f913cd7f
> 
> Edward
> 
> Edward K. Ream   email:  [EMAIL PROTECTED]
> Leo: http://webpages.charter.net/edreamleo/front.html
> 
> 
> 

Are you part of Leo? This smells like a marketing scheme to me.





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


Re: The big shots

2008-02-23 Thread Ricardo Aráoz
Dotan Cohen wrote:
> On 20/02/2008, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>  It's a bad sign.  If you aren't keeping your thoughts to yourself, and
>>  thrashing about the world for a peer, a social network, a support
>>  group, or a community, then you missed the day in grammar school when
>>  they were handing out smiles.  But they're not handing them out
>>  anymore.
> 
> You talk in analogies. I don't understand them. I do not know Spanish,
> and maybe if I knew both Spanish and your local customs, I would
> understand your analogies. But as a Hebrew-speaking middle easterner,
> I don't.
> 

I am a native Spanish speaker and I don't understand him either. It
is not cultural.


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


Re: Coverage.py reporting and UML tools - what exists already?

2008-02-13 Thread Ricardo Aráoz
J Peyret wrote:
> I got coverage.py to work after somewhat of a difficult start...
> 
> Hint:  if moving your code from Windows to Linux and if running
> 'coverage.py -r mymodule.py' causes SyntaxError/SyntaxException, the
> 'flip' utility is your friend to deal with removing those nasty \r\n
> newlines that are preventing coverage.py from working.
> 
> ... and I can generate annotated files.  Great, but it would be really
> nice to have an quick overview of untested code.
> 
> One Java tool I've used in the past is Cobertura, which can output its
> coverage reports in html format.
> 
> http://cobertura.sourceforge.net/sample/
> 
> I was wondering if there is anything similar to dress up coverage.py
> annotation files?  Wouldn't seem to be very difficult to html-ize the
> files a bit.  I can probably take a, feeble, stab at it, but I'd
> rather not reinvent any wheels.
> 
> 
> Second question:
> 
> I'd like a basic UML tool to draw up some interaction diagrams
> (Collaboration/Sequence) on some of my hairier pieces of code.  I
> think of it more as documentation/brainstorming diagrams than anything
> else.  I.e. something that helps me remember how things work and can
> help me spot refactoring opportunities.
> 
> Things I don't care about:
> 
> - document most of my code - this is for the truly complex 5-10% of
> interactions
> - generating diagrams from code or code from diagrams
> - static class diagrams
> - descriptions doing the whole UML hog - type declarations,
> stereotypes, etc...
> 
> What I do care about:
> 
> - sketching basic diagrams manually as quickly as possible
> 
> Most of the software I've seen takes great pride in reverse
> engineering or generating code, often of the Java variety.  In fact,
> everything looks dauntingly complex/powerful.  Anybody seen the
> equivalent of an UML/CRC-card aware blackboard?  Something as
> trivially dumb/easy as the early Visio/ABC Flowcharter?
> 
> I've looked at ArgoUML, BoaConstructor and UMLet in the past and
> didn't really like them.  What about Dia?  Looking at UML from a
> Python / post-coding documentation angle, what seems to fit the bill
> best?
> 
> I am on Linux or Windows, using PyDev on Eclipse.
> 
> Cheers

Have you tried StarUML? Worth a look (open source).

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


Re: REALLY simple xml reader

2008-01-31 Thread Ricardo Aráoz
Diez B. Roggisch wrote:
> Ricardo Aráoz schrieb:
>> Diez B. Roggisch wrote:
>>> Ricardo Aráoz schrieb:
>>>> Thanks Ivan, it seems a elegant API, and easy to use.
>>>> I tried to play a little with it but unfortunately could not get it off
>>>> the ground. I kept getting
>>>>>>> root = et.fromstring(doc)
>>>> Traceback (most recent call last):
>>>>   File "", line 1, in 
>>>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
>>>> parser.feed(text)
>>>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
>>>> self._parser.Parse(data, 0)
>>>> ExpatError: XML or text declaration not at start of entity: line 2, column >>>> 0
>>> That's a problem in your XML not being XML. Has nothing to do with 
>>> element-tree - as one sees from the error-message "ExpatError". If you 
>>> show it to us, we might see why.
>>>
>> Sure,
>>
>> doc = """
>> 
> 
> It's not allowed to have a newline before the 
> 
> Put it on the line above, and things will work.
> 
> Diez

Worked ok. Thanks a lot to you all, I'm not using it right now but I've
had a taste and now know where to look and how to start.
Cheers


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


Re: REALLY simple xml reader

2008-01-31 Thread Ricardo Aráoz
Diez B. Roggisch wrote:
> Ricardo Aráoz schrieb:
>> Thanks Ivan, it seems a elegant API, and easy to use.
>> I tried to play a little with it but unfortunately could not get it off
>> the ground. I kept getting
>>>>> root = et.fromstring(doc)
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
>> parser.feed(text)
>>   File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
>> self._parser.Parse(data, 0)
>> ExpatError: XML or text declaration not at start of entity: line 2, column 0
> 
> That's a problem in your XML not being XML. Has nothing to do with 
> element-tree - as one sees from the error-message "ExpatError". If you 
> show it to us, we might see why.
> 

Sure,

doc = """


expenses: january 2002

  
31.19
200213
Walking Store
shoes
  

  
1549.58
200217
Bob's Bolts
  

  
40
200218
pocket money
  

  
25
200218
  

  
188.20
200218
Boston Endodontics
cavity
  

  
10.58
2002110
Exxon Saugus
gasoline
  

  
909.56
2002114
Honda North
car repairs
  

  
24.30
2002115
Johnny Rockets
lunch
  

"""
I thought this was proper XML as it comes straight out from an O'Reilly
XML book.

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


Re: REALLY simple xml reader

2008-01-31 Thread Ricardo Aráoz
Ivan Illarionov wrote:
 from xml.etree import ElementTree as et
 from decimal import Decimal

 root = et.parse('file/with/your.xml')
 debits = dict((debit.attrib['category'], 
 Decimal(debit.find('amount').text)) for debit in root.findall('debit'))

 for cat, amount in debits.items():
> ...   print '%s: %s' % (cat, amount)
> ...
> food: 24.30
> car: 909.56
> medical: 188.20
> savings: 25
> withdrawal: 40
> supplies: 10.58
> clothes: 31.19
> 

Thanks Ivan, it seems a elegant API, and easy to use.
I tried to play a little with it but unfortunately could not get it off
the ground. I kept getting
>>> root = et.fromstring(doc)
Traceback (most recent call last):
  File "", line 1, in 
  File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
parser.feed(text)
  File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
self._parser.Parse(data, 0)
ExpatError: XML or text declaration not at start of entity: line 2, column 0

But it's probably my lack of knowledge on the subject. Well, I guess
there is no free ride and I'll take a look at ElementTree as soon as I
have some spare time, looks promising.
One last question. Am I right to believe "debit" would be an "et" object
of the same class as "root"?
THX
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: REALLY simple xml reader

2008-01-29 Thread Ricardo Aráoz
> What about :
>
> doc = """
> 
>99
> 
> 
>42
> 
> """

That's not an XML document, so what about it?

Stefan

--

Ok Stefan, I will pretend it was meant in good will.

I don't know zit about xml, but I might need to, and I am saving the
thread for when I need it. So I looked around and found some 'real'
XML document (see below). The question is, how to access s from
s (any category) but not s.
Probably my previous example was not properly stated, what I meant to
convey is two substructures (namespaces, or whatever you call them in
XML) which have the same 'properties'  is not the same as
 as  is not the same as .
The examples given by Diez and Mark, though useful, don't seem to
address the problem.
Thanks for your help.


doc = """


expenses: january 2002

  
31.19
200213
Walking Store
shoes
  

  
1549.58
200217
Bob's Bolts
  

  
40
200218
pocket money
  

  
25
200218
  

  
188.20
200218
Boston Endodontics
cavity
  

  
10.58
2002110
Exxon Saugus
gasoline
  

  
909.56
2002114
Honda North
car repairs
  

  
24.30
2002115
Johnny Rockets
lunch
  

"""

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


Re: REALLY simple xml reader

2008-01-29 Thread Ricardo Aráoz
Diez B. Roggisch wrote:
> Simon Pickles schrieb:
>> Hi
>>
>> Can anyone suggest a really simple XML reader for python? I just want to 
>> be able to do something like this:
>>
>> xmlDoc = xml.open("file.xml")
>> element = xmlDoc.GetElement("foo/bar")
>>
>> ... to read the value of:
>>
>> 
>>   42
>> 
> 
> Since python2.5, the ElementTree module is available in the standard 
> lib. Before 2.5, you can of course install it.
> 
> Your code then would look like this:
> 
> import xml.etree.ElementTree  as et
> 
> 
> doc = """
> 
>42
> 
> """
> 
> root = et.fromstring(doc)
> 
> for bar in root.findall("bar"):
>  print bar.text
> 
> 
> 
> Diez
> 

What about :

doc = """

   99


   42

"""


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


Re: split parameter line with quotes

2008-01-14 Thread Ricardo Aráoz
teddyber wrote:
> here's the solution i have for the moment :
> 
>   t = shlex.shlex(data)
>   t.wordchars = t.wordchars + "/+.-"
>   r=''
>   while 1:
>   token = t.get_token()
>   if not token:
>   break
>   if not token==',': r = r+token
>   else: r = r + ' '
>   self.DEBUG(r,'ok')
> for pair in r.split(' '):
> key,value=pair.split('=', 1)
> print(key+':'+value)
> 
> i know this is not perfect still but i'm coming a long way from very
> bad php habits! :o)
> and thanks for your help!
> 
> On 11 jan, 23:30, teddyber <[EMAIL PROTECTED]> wrote:
>> wow! that's perfect this shlex module! thanks for pointing this!
>>
>> On 11 jan, 20:36, Joshua Kugler <[EMAIL PROTECTED]> wrote:
>>
>>> teddyber wrote:
 first i'm a newbie to python (but i searched the Internet i swear).
 i'm looking for some way to split up a string into a list of pairs
 'key=value'. This code should be able to handle this particular
 example string :
 qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,
 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess
 i know i can do that with some regexp (i'm currently trying to learn
 that) but if there's some other way...
>>> Take a look at the shlex module.  You might be able to fiddle with the shlex
>>> object and convince it to split on the commas.  But, to be honest, that
>>> above would be a lot easier to parse if the dividing commas were spaces
>>> instead.
>>> j
> 

Maybe you like :

>>> x = 'qop = "auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,
3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess'

>>> dict(zip([k[-1].strip() for k in (j.split(',') for j in ''.join(i
for i in x if i != '"').split('='))][:-1], [k[:-1] or k for k in
(j.split(',') for j in ''.join(i for i in x if i != '"').split('='))][1:]))

{'maxbuf': ['1024'], 'cipher': ['rc4-40', 'rc4-56', 'rc4', 'des', '
3des'], 'charset': ['utf-8'], 'algorithm': ['md5-sess'], 'qop': ['
auth', 'auth-int', 'auth-conf']}

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


Re: how to generate html table from "table" data?

2007-12-27 Thread Ricardo Aráoz
Bruno Desthuilliers wrote:
> [EMAIL PROTECTED] a écrit :
>  > Vasudev Ram wrote:
>>> Why not try writing your own code for this first?
>>> If nothing else, it'll help you learn more, and may also help you
>>> understand better, the other options.
>>>
>> Thanks for your reply even it was not really helpful.
> 
> The answers boil down to:
> - use the templating engine that comes with your web framework
> or
> - use whatever templating engine you like
> or
> - just do it by hand
> 
> The remaining work is obviously such a no-brainer that there's no need 
> for a specific package, and so application specific that there's 
> probably nothing like a one-size-fits-all answer. IOW : you're not 
> likely to find more "helpful" answer - and your above comment won't 
> help. FWIW, I just wrote a function generating an html table from a list 
> of header and a list of rows. I wrote the most Q&D, straightforward, 
> braindead way, it's 17 lines long, doesn't even need an import 
> statement, and took me less than 2 minutes to write - that is, far less 
> work than reading your post and answering it.

Hi.
Bruno, could you please post those 17 lines? I'm not actually doing HTML
work but I would find it interesting going through your code.

TIA



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


Re: very newbie question about exception handling

2007-12-24 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> code sample:
> --
> i=input()
> try:
> x=int(i)
> print "you input an integer"
> except ValueError:
> print "you must input an integer"
> 
> when I input a value like, b
> I got the traceback message instead of proper exception handling:
> 
> NameError: b is not defined
> 
> I also tried
> --
> try: x=int(i)
> except ValueError: print "something"
> except NameError: pting "something"
> else: print "something"
> 
> It still couldn't capture the exception, just the same traceback error
> msg.
> 
> I'm really confused, any suggestions please?
> 
Yes, you must use raw_input() (check the manual on "input()").

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


Re: Yet Another Tabular Data Question

2007-11-30 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> On Nov 29, 5:46 pm, [EMAIL PROTECTED] wrote:
>> Hi all,
>>
>> Fairly new Python guy here.  I am having a lot of trouble trying to
>> figure this out.  I have some data on some regulations in Excel and I
>> need to basically add up the total regulations for each country--a
>> statistical analysis thing that I'll copy to another Excel file.
>> Writing with pyExcelerator has been easier than reading with xlrd for
>> me...So that's what I did first, but now I'd like to learn how to
>> crunch some data.
>>
>> The input looks like this:
>>
>> Country Module
>> Topic  # of Docs
>> Argentina   Food and Consumer Products  Cosmetics1
>> Argentina   Food and Consumer Products  Cosmetics8
>> Argentina   Food and Consumer Products  Food Additives  1
>> Argentina   Food and Consumer Products  Food Additives  1
>> Australia   Food and Consumer Products  Drinking Water   7
>> Australia   Food and Consumer Products  Food Additives   3
>> Australia   Food and Consumer Products  Food Additives   1
>> etc...
>>
>> So I need to add up all the docs for Argentina, Australia, etc...and
>> add up the total amount for each Topic for each country so, Argentina
>> has 9 Cosmetics laws and 2 Food Additives Laws, etc...
>>
>> So, here is the reduced code that can't add anything...Any thoughts
>> would be really helpful.
>>
>> import xlrd
>> import pyExcelerator
>> from pyExcelerator import *
>>
>> #Open Excel files for reading and writing
>> path_file = "c:\\1\\data.xls"
>> book = xlrd.open_workbook(path_file)
>> Counts = book.sheet_by_index(1)
>> wb=pyExcelerator.Workbook()
>> matrix = wb.add_sheet("matrix")
>>
>> #Get all Excel data
>> n=1
>> data = []
>> while n> data.append(Counts.row_values(n, start_colx=0, end_colx=None))
>> n=n+1
>>
>> COUNTRY, MODULE, TOPIC,DOCS = range(4)
>> COUNTRY_TOT = []
>> n=0
>> while n> x=n
>> while data[n][COUNTRY]==data[n+1][COUNTRY]:
>> n=n+1
>> print sum(data[x:n][FT_DOCS])
>>
>> wb.save('c:\\1\\matrix.xls')
> 

Check itertools.groupby() and operator.itemgetter()


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


Re: better way to write this function

2007-11-26 Thread Ricardo Aráoz
Peter Otten wrote:
> Kelie wrote:
> 
>> Hello,
>>
>> This function does I what I want. But I'm wondering if there is an
>> easier/better way. To be honest, I don't have a good understanding of
>> what "pythonic" means yet.
>>
>> def divide_list(lst, n):
>> """Divide a list into a number of lists, each with n items. Extra
>> items are
>>ignored, if any."""
>> cnt = len(lst) / n
>> rv =  [[None for i in range(n)] for i in range(cnt)]
>> for i in range(cnt):
>> for j in range(n):
>> rv[i][j] = lst[i * n + j]
>> return rv
> 
> You can use slicing:
> 
 def chunks(items, n):
> ... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
> ... 
 for i in range(1,10):
> ... print chunks(range(5), i)
> ... 
> [[0], [1], [2], [3], [4]]
> [[0, 1], [2, 3]]
> [[0, 1, 2]]
> [[0, 1, 2, 3]]
> [[0, 1, 2, 3, 4]]
> []
> []
> []
> []


This won't work(e.g. you don't define "start", you change the value of n
through the loop). I guess you meant :

def chunks(items, n) :
return [items[i:i+n] for i in range(0, len(items)-n+1, n)]





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


Re: Problems with if/elif statement syntax

2007-11-23 Thread Ricardo Aráoz
[EMAIL PROTECTED] wrote:
> On Nov 22, 12:33 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> On 22 Nov, 12:09, Neil Webster <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> Hi all,
>>> I'm sure I'm doing something wrong but after lots of searching and
>>> reading I can't work it out and was wondering if anybody can help?
>>> I've got the following block of code:
>>> if a >= 20 and a < 100:
>>> if c == "c":
>>> radius = 500
>>> else:
>>> radius = 250
>>> elif (a >= 100) and (a < 500):
>>> radius = 500
>>> elif (a >= 500) and (a < 1000):
>>> radius = 1000
>>> elif (a >= 1000) and (a < 3000):
>>> radius = 1500
>>> elif (a >= 3000) and (a < 5000):
>>> radius = 2000
>>> else:
>>> radius = 4000
>>> No matter what value goes in for 'a' the radius always comes out as
>>> 4000.
>>> What am I doing wrong?
>>> Cheers
>>> Neil
>> as Oliver pointed out, check if you're not compairing "a" as a string
>>
>> I wanted to let you know that you can write the above conditions in a
>> more natural way, using the a>
>> e.g.
>>
>> x=int(raw_input("write a number"))
>> if 5<=x<30:
>> print 'x is between 5 and 30'
> 
> Argh, I really dislike raw_input. Though it helps to remind me to use
> Try:Except blocks a lot.


Hasn't anyone TRIED the code? I did, with a = 30 and c = 'x' radius
comes out as 250. So it seems the problem is somewhere else and not in
this bit of code.



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


Re: Populating a dictionary, fast

2007-11-11 Thread Ricardo Aráoz
Michael Bacarella wrote:
>>> This would seem to implicate the line id2name[id] = name as being
>  excruciatingly slow.
>> As others have pointed out there is no way that this takes 45
>> minutes.Must be something with your system or setup.
>>
>> A functionally equivalent code for me runs in about 49 seconds!
>> (it ends up using about twice as much ram as the data on disk)
> 
> You can download the list of keys from here, it's 43M gzipped:
> http://www.sendspace.com/file/9530i7
> 
> and see it take about 45 minutes with this:
> 
> $ cat cache-keys.py
> #!/usr/bin/python
> v = {}
> for line in open('keys.txt'):
> v[long(line.strip())] = True

Have you tried taking the long away? I mean :
 v[line.strip()] = True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-11-02 Thread Ricardo Aráoz
Gabriel Genellina wrote:
> En Thu, 01 Nov 2007 20:12:52 -0300, Ricardo Aráoz <[EMAIL PROTECTED]>  
> escribió:
> 
>>>>>>> def sumToOneDigit(num) :
>>>>if num < 10 :
>>>>return num
>>>>else :
>>>>return sumToOneDigit(sum(int(i) for i in str(num)))
>>>>
> 
> def sumToOneDigit(num):
>  return num % 9 or 9
> 
> Valid when num>=1, which is guaranteed by the OP context.
> 

Beautiful. Much better than mine.

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


Re: Need some help...

2007-11-01 Thread Ricardo Aráoz
Boris Borcic wrote:
> Ricardo Aráoz wrote:
>> Boris Borcic wrote:
>>> [EMAIL PROTECTED] wrote:
>>>> I want to create a program that I type in a word.
>>>>
>>>> for example...
>>>>
>>>> chaos
>>>>
>>>> each letter equals a number
>>>>
>>>> A=1
>>>> B=20
>>>>
>>>>  and so on.
>>>>
>>>> So Chaos would be
>>>>
>>>> C=13 H=4 A=1 O=7 S=5
>>>>
>>>> I want to then have those numbers
>>>> 13+4+1+7+5 added together to be 30.
>>>>
>>>> How can I do that?
>>>>
>>>> Also, just curious, but, how could I then have the 3 and 0 added
>>>> together to be 3?
>>>>
>>>> Please help me out.
>>>>
>>>> Thank you.
>>>>
>>>  >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
>>> 30
>>>  >>> sum(eval(ch) for ch in str(_))
>>> 3
>>
>>>>> def sumToOneDigit(num) :
>>  if num < 10 :
>>  return num
>>  else :
>>  return sumToOneDigit(sum(int(i) for i in str(num)))
>>
>>  
>>>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
>> 6
>>
>>
>>
>> HTH
> 
> HTH what ?


HTH : Hope that helps

Citing your post :
"""
Also, just curious, but, how could I then have the 3 and 0 added
together to be 3?
"""

you have the function "sumToOneDigit" that adds the digits of a number
till you get one digit (isn't that what you where curious about?)

And answering the main question : sum(ord(ch) for ch in 'chaos'.upper())
which is inside the "sumToOneDigit" funtion in my answer.

Sorry if that is not enough for you, but the answer is probably worth
what you paid for it.



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


Re: appending into a list

2007-10-31 Thread Ricardo Aráoz
Beema shafreen wrote:
> hi everybody,
>   I have a file :
>A B  C D   E
> 
>  2717353  2717412A_16_P03641964214-59
>   2717626  2717685A_16_P4156365525-59
>   2717710  2717754A_16_P036419651250-44
>   2719004  2719063A_16_P03641966-36-59
>   2719027  2719086A_16_P21360229289-59
>   2719375  2719428A_16_P0364196760-53
>   2719488  2719542A_16_P21360231418-54
>   2719960  2720014A_16_P03641968727-54
>   2720741  2720786A_16_P03641969494-45
>   2721280  2721339A_16_P03641970-28-59
>   2721311  2721370A_16_P21360234150-59
>   2721520  2721569A_16_P21360235199-49
>   2721768  2721821A_16_P03641971139-53
>   2721960  2722004A_16_P21360237312-44
> I need to append the column D and E into a list:
> in such a way that the list should have 
> [D,E,D,E,D,E]
> How do i do it.
> 
> regards
> shafreen
> 

>>> r = []
>>> for D, E in (i.split()[-2:] for i in open('file')) :
r.append(D)
r.append(E)


>>> r
['214', '-59', '25', '-59', '1250', '-44', '-36', '-59', '289', '-59',
'60', '-53', '418', '-54', '727', '-54', '494', '-45', '-28', '-59',
'150', '-59', '199', '-49', '139', '-53', '312', '-44']


HTH





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


Re: Need some help...

2007-10-31 Thread Ricardo Aráoz
Boris Borcic wrote:
> [EMAIL PROTECTED] wrote:
>> I want to create a program that I type in a word.
>>
>> for example...
>>
>> chaos
>>
>> each letter equals a number
>>
>> A=1
>> B=20
>>
>>  and so on.
>>
>> So Chaos would be
>>
>> C=13 H=4 A=1 O=7 S=5
>>
>> I want to then have those numbers
>> 13+4+1+7+5 added together to be 30.
>>
>> How can I do that?
>>
>> Also, just curious, but, how could I then have the 3 and 0 added
>> together to be 3?
>>
>> Please help me out.
>>
>> Thank you.
>>
> 
>  >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
> 30
>  >>> sum(eval(ch) for ch in str(_))
> 3


>>> def sumToOneDigit(num) :
if num < 10 :
return num
else :
return sumToOneDigit(sum(int(i) for i in str(num)))


>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
6



HTH





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


Re: dictionary and list

2007-10-31 Thread Ricardo Aráoz
Beema shafreen wrote:
> hi everbody,
>I have a file,
>  a b   c   d e
>   2722316  2722360A_16_P03641972150-44
>   2722510  2722554A_16_P2136023916-44
>   2722570  2722614A_16_P0364197344-44
>   2722658  2722702A_16_P415636692187-44
>   2724889  2724948A_16_P03641974738-59
>   2725686  2725745A_16_P03641975422-59
>   2726167  2726219A_16_P0364197688-52
>   2726307  2726366A_16_P415636772167-59
>   2728533  2728589A_16_P213602495819-56
>   2734408  2734467A_16_P21360257-14-59
>   2734453  2734509A_16_P03641977376-56
>   2734885  2734929A_16_P213602591987-44
> 
>  i need to do with dictionary like this : c[d,e,d+1] =
> A_16_P03641972[150,-44,16]
> my script:d = {}
> fh = open('final_lenght_probe_span','r')
> for line in fh.readlines():
> data = line.strip().split('\t')
> probe_id = data[2].strip()
> span = data[3].strip()
> length = data[4].strip()
> d[probe_id ] = []
> d[probe_id] = [span,length,span[0+1]]
> for key in d.keys():
> print key ,d[key]
> I donot end with this result how do i do
> 
> 

I'm not sure if this is what you need
(check: A_16_P03641972 ['150', '-44', '16']) :

>>> d = {}
>>> probes = list(enumerate((i.split()[2],i.split()[3], i.split()[4])
for i in open('pyth3.txt')))
>>> for idx, (probe_id, span, length) \
in probes :
try :
d[probe_id] = [span, length, probes[idx+1][1][1]]
except IndexError :
d[probe_id] = [span, length, None]


>>> for key in d.keys():
print key ,d[key]


A_16_P03641974 ['738', '-59', '422']
A_16_P03641975 ['422', '-59', '88']
A_16_P41563669 ['2187', '-44', '738']
A_16_P03641977 ['376', '-56', '1987']
A_16_P03641972 ['150', '-44', '16']
A_16_P03641973 ['44', '-44', '2187']
A_16_P21360249 ['5819', '-56', '-14']
A_16_P41563677 ['2167', '-59', '5819']
A_16_P03641976 ['88', '-52', '2167']
A_16_P21360239 ['16', '-44', '44']
A_16_P21360259 ['1987', '-44', None]
A_16_P21360257 ['-14', '-59', '376']


HTH

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


Re: two files into an alternate list

2007-10-31 Thread Ricardo Aráoz
Tim Chase wrote:
>> i have a file :
>>  file 1:
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
>>
>> file2:
>> a
>> b
>> c
>> d
>> e
>> f
>> how do i make the two files into  list like this =
>> [1,a,2,b,3,c,4,d,5,e,6,f]
> 
>   from itertools import cycle
>   def serialize(*sources):
> while True:
>   for source in sources:
> yield source.next()
>   def stripper(iterator):
> for thing in iterator:
>   yield thing.strip()
>   for thing in serialize(
>   stripper(file('file1.txt')),
>   stripper(file('file2.txt'))
>   ):
> print thing
> 
> As a previous responder noted, there are a number of ways to
> treat the edge cases when the lengths of the files don't match.
> Since you left the condition underqualified, I chose to let it
> expire when the first one gave out rather than try and deal with
> the complications of such ambiguity.
> 
> -tkc
> 

Or maybe just :

>>> r = []
>>> for a, b in map(None
, (int(i.strip('\n')) for i in open('file1.txt'))
, (i.strip('\n') for i in open('file2.txt'))) :
r.append(a)
r.append(b)

>>> r
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', None, 'f']



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


Re: Using msvcrt (in Windows), how to catch Enter key?

2007-10-29 Thread Ricardo Aráoz
Dick Moores wrote:
> Windows XP Pro, Python 2.5.1
> 
> import msvcrt
> while True:
>  if msvcrt.kbhit():
>  key = msvcrt.getch()
>  if key == 'Enter'
>do something
> 
> Is there a way to catch the pressing of the 'Enter' key?
> 
> Thanks,
> 
> Dick Moores
> 

You have examples for this in http://effbot.org/librarybook/msvcrt.htm

HTH


-- 
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


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: 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: [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: 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: 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: 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: 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: 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: 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

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: 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


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: 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


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


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: 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


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: 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: 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
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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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


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: 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


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
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-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


  1   2   >