Re: String substitution VS proper mysql escaping

2010-08-19 Thread Νίκος
I would expect that:

"nikos" is a string, while,
("nikos") is a single element tuple.
["nikos"] is a single element list.

That way we wouldn't be needing comma seperators.
I just don't like it when "nikos" and ("nikos") is the same thing
exactly. Parentheses are to be used to define a tuple and square
brackets to define a list.

Also i want to ask whats the difference between 'nikos', "nikos" and
'''nikos''' for Python and whats the best way to use to enclose a
string.


==
if in my example instead of

| cursor.execute('''SELECT host, hits, date FROM visitors WHERE
| page=%s ORDER BY date DESC''',  (page,) )

i use

| cursor.execute('''SELECT host, hits, date FROM visitors WHERE
| page=%s ORDER BY date DESC''',  page)

instead which i tend to like more, would there i have a problem?

Also how how this part here page=%s doesn't need to be written as
page='%s' which is the way i used to have it written with myssql
string substitution?

==

And last but not least :-) is that

http://webville.gr/index.html?page="100 ; DELETE FROM visitors;
SELECT
* FROM visitors"
===
don't reproduce the problem of actual deleting my data. I don't care
losing it!
I just want to see that happening with my own eyes!

but if you try it you get an error. Maybe die to whitespace in the
value of the page?
How to write that propetly?

Thank again fellows for ALL your help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Νίκος
On 18 Αύγ, 12:50, Cameron Simpson  wrote:

>
> ("nikos",) is a single element tuple.
> ["nikos"] is a single element list.
> ["nikos",] is also a single element list, just written like the tuple.


It makes more sense if i:

"nikos" is just a string
("nikos") is a single element tuple
["nikos"] is also a single element list


After all () used to define tuples and [] usedd to define lists. Why
commas?

Also is there a difference between 'nikos' or "nikos" or '''nikos''' ?
What's and why best to use to enclose strings?

===

Why in mysql string substitution example i have to use page='%s' and
in the comma way(automatic mysql converetion i dont need the single
quotes page=%s ?
What is the diff?

===

Why http://webville.gr/index.html?page="100 ; DELETE FROM visitors;
SELECT * FROM visitors"

don't reproduce the problem of actual deleting my data to demonstrate
the wrongness of string substitution in mysql queries?

I don't care losing my data! The page is there to helpe me learn
python and mysql.

I just want to see that happening with my own eyes!

Thanks again fols for all your precious help and explanations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to see intermediate fail results from unittest as tests are running?

2010-08-19 Thread Peter Otten
Margie Roginski wrote:

> I am using unittest in a fairly basic way, where I have a single file
> that simply defines a class that inherits from unittest.TestCase and
> then within that class I have a bunch of methods that start with
> "test".  Within that file, at the bottom I have:
> 
> if __name__ == "__main__":
> unittest.main()
> 
> This works fine and it runs all of the testxx() methods in my file.
> As it runs it prints if the tests passed or failed, but if they fail,
> it does not print the details of the assert that made them fail.  It
> collects this info up and prints it all at the end.
> 
> Ok - my question: Is there any way to get unittest to print the
> details of the assert that made a test fail, as the tests are
> running?  IE, after a test fails, I would like to see why, rather than
> waiting until all the tests are done.

Not exactly what you're asking for, but 2.7 has grown a --failfast option 
that tells unittest to stop on the first failure. For older Python versions
you can use nose

nosetests -x myscript.py

at http://somethingaboutorange.com/mrl/projects/nose/0.11.2/
or the unittest backport at http://pypi.python.org/pypi/unittest2

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


Re: OpenCV_Problem

2010-08-19 Thread arihant nahata
> There is no file named _cv.dll file in the directory that you mentioned
>
what to do now.???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Wed, 18 Aug 2010 21:55:30 -0700, Russ P. wrote:

> On Aug 18, 7:58 pm, Steven D'Aprano  t...@cybersource.com.au> wrote:
>> On Wed, 18 Aug 2010 14:47:08 -0700, Russ P. wrote:
>> > Is the top team in the league the number 1 team -- or the number 0
>> > team? I have yet to hear anyone call the best team the number 0 team!
>>
>> Why is the top team the one with the lowest number?
> 
> How could it be otherwise? What is the highest number?

If there are N teams, then the highest number is obviously N (if counting 
from 1) or N-1 (if from 0).

In other words... why do we rank sporting teams Best to Worst rather than 
the other way around?


[...]
> Maybe "goofy" was too derogatory, but I think you are rationalizing a
> bad decision, at least for high-level languages. I don't think
> programming languages should always mimic human languages, but this is
> one case where there is no advantage to doing otherwise.
> 
> Why do you think "off by one" errors are so common? Because the darn
> indexing convention is off by one!

But you have that exactly backwards. Counting from 0 leads to fewer off 
by one errors for many tasks.

(Of course, avoiding indexing in favour of iteration leads to even fewer 
off by one errors.)

Anyway, in a feeble attempt to move this discussion somewhere -- 
anywhere! -- else:

http://c2.com/cgi/wiki?FencePostError
http://c2.com/cgi/wiki?WhyNumberingShouldStartAtZero
http://c2.com/cgi/wiki?WhyNumberingShouldStartAtOne
http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/zero

and of course:

http://xkcd.com/163/




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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread Standish P
On Aug 18, 5:38 pm, Keith Thompson  wrote:
> Standish P  writes:
> > On Aug 18, 12:30 pm, Elizabeth D Rather  wrote:
> [...]
> >> Mostly it had a "snowball's chance" because it was never picked up by
> >> the CS gurus who, AFAIK, never really took a serious look at it.
>
> > Its quite possible that the criticism is unfair, but dont you think
> > that in part some responsibility must be borne by your organization in
> > not doing a good job of education ?
> [snip]
> > Show me on what page does it explain how Forth implements dynamic
> > binding or lexical binding and takes care of the scope of definition
> > of the "nouns" ?
>
> [...]
>

> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory,
> or comp.lang.python.  Please trim the Newsgroups line.

provide a rigorous proof that people are more interested in the
nauseating nude pictures that you post of your mother in the
newsgroups than in the subject of forth implementation. as a matter of
fact a lot of people in various language groups are interested in
implementation aspects and the languages borrow ideas from each other.

now, get away from my thread and take away your odious posts which
positively cause me nausea and vomiting.

we will soon find out the game of stacks.


> --
> Keith Thompson (The_Other_Keith) ks...@mib.org  
> Nokia
> "We must do something.  This is something.  Therefore, we must do this."
>     -- Antony Jay and Jonathan Lynn, "Yes Minister"

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


comp.lang.python

2010-08-19 Thread roshini begum
www.127760.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for an appropriate encoding standard that supports all languages

2010-08-19 Thread ata.jaf
On Aug 17, 11:55 pm, Thomas Jollans  wrote:
> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim:
>
> > I am developing a little program in Mac with wxPython.
> > But I have problems with the characters that are not in ASCII. Like
> > some special characters in French or Turkish.
> > So I am looking for a way to solve this. Like an encoding standard
> > that supports all languages. Or some other way.
>
> Anything that supports all of Unicode will do. Like UTF-8. If your text is
> mostly Latin, then just go for UTF-8, if you use other alphabets extensively,
> you might want to consider UTF-16, which might the use a little less space.

OK, I used UTF-8.
I write a line of strings in the source code and I want my program to
show that as an output on GUI. And this line of strings includes a
character like "ü". But I see that in GUI this character is replaced
with another strange characters. I mean it doesn't work.
And when I try to use UTF-16, I get an syntax error that declares
"UTF-16 stream does not start with BOM".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread John Kelly
On Thu, 19 Aug 2010 00:56:35 -0700 (PDT), Standish P 
wrote:

>On Aug 18, 5:38 pm, Keith Thompson  wrote:
>> Standish P  writes:

>> > Show me on what page does it explain how Forth implements dynamic
>> > binding or lexical binding and takes care of the scope of definition
>> > of the "nouns" ?

>> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory,
>> or comp.lang.python.  Please trim the Newsgroups line.

>fact a lot of people in various language groups are interested in
>implementation aspects and the languages borrow ideas from each other.

Standish sounds like Spinoza in disguise.  Nevertheless, ngs like c.l.c
need more diversity.  Standards minutia is boring.


-- 
Web mail, POP3, and SMTP
http://www.beewyz.com/freeaccounts.php
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for an appropriate encoding standard that supports all languages

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 01:29:51 -0700, ata.jaf wrote:

> On Aug 17, 11:55 pm, Thomas Jollans  wrote:
>> On Tuesday 17 August 2010, it occurred to ata.jaf to exclaim:
>>
>> > I am developing a little program in Mac with wxPython. But I have
>> > problems with the characters that are not in ASCII. Like some special
>> > characters in French or Turkish. So I am looking for a way to solve
>> > this. Like an encoding standard that supports all languages. Or some
>> > other way.
>>
>> Anything that supports all of Unicode will do. Like UTF-8. If your text
>> is mostly Latin, then just go for UTF-8, if you use other alphabets
>> extensively, you might want to consider UTF-16, which might the use a
>> little less space.
> 
> OK, I used UTF-8.
> I write a line of strings in the source code 


Do you have a source code encoding line at the start of your script?


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


> and I want my program to
> show that as an output on GUI. And this line of strings includes a
> character like "ü". But I see that in GUI this character is replaced
> with another strange characters. I mean it doesn't work. And when I try
> to use UTF-16, I get an syntax error that declares "UTF-16 stream does
> not start with BOM".


What GUI are you using?


Please COPY AND PASTE (do not retype) the EXACT error message you get, 
including the entire traceback.




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


Re: Pop return from stack?

2010-08-19 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :


Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in 
Python, even VB in Python, but this is the first time I've meet some one 
who wants to write assembler in Python :)




+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for an appropriate encoding standard that supports all languages

2010-08-19 Thread Martin v. Loewis
> I write a line of strings in the source code and I want my program to
> show that as an output on GUI. And this line of strings includes a
> character like "ü".

Make sure you use Unicode literals in your source code, i.e. u"ü".

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


Re: when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray'

2010-08-19 Thread Duim
On Aug 18, 10:03 pm, Nobody  wrote:
> On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote:
> > Although I'm sure somewhere this issue is discussed in this (great)
> > group, I didn't know the proper search words for it (although I
> > tried).
>
> > I'm using python (2.6) scientifically mostly, and created a simple
> > class to store time series (my 'Signal' class).
> > I need this class to have a possibility to get multiplied by an array,
> > but pre and post multiplication have different mathematical outcomes
> > ( basically A* B != B*A ) .
>
> > Post multiplication by an array works fine defining __mul__ in the
> > Signal class, but pre multiplication does not. It keeps trying to
> > multiply all elements separately instead to send this array to my
> > __rmul__ function.
>
> > How can I fix this without the need for a separate
> > 'multiplysignal(A,B)' function?
>
> Make Signal a subclass of numpy.ndarray. If one operand is a subclass of
> the other, its __rmul__ will be preferred to the parent's __mul__.
>
> In the absence of a subclass-superclass relationship, the LHS's __mul__ is
> preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if
> the LHS lacks a __mul__ method or if the method refuses its argument
> (returns NotImplemented).
>
> Likewise for other "reflected" methods.

Great, many thanks. It seems to work well.
For others looking into the same issue: http://www.scipy.org/Subclasses

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


Unsupported Format Character '&' (0x26)

2010-08-19 Thread Andrew Evans
I get an error message "Unsupported Format Character '&' (0x26)" I narrowed
it down to these two variables

any idea how to fix it?

  SEARCH_URL_0 = "
http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry=
"
NEXT_PAGE_0 = "
http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11
"



Not sure why its doing it the value in parenthesis should work %(query) etc

Any ideas cheeers
-- 
http://mail.python.org/mailman/listinfo/python-list


path to data files

2010-08-19 Thread Daniel Fetchinson
If a python module requires a data file to run how would I reference
this data file in the source in a way that does not depend on whether
the module is installed system-wide, installed in $HOME/.local or is
just placed in a directory from where the interpreter is fired up? I'd
like to always keep the python source and the data file in the same
directory, be it /usr/lib/python2.6/site-packages,
$HOME/.local/lib/python2.6/site-packages or
/arbitrary/path/to/somewhere.

If the data file is called 'foo' and I simply do open('foo') in the
python source file this will not work if they are both installed
either system-wide or locally. More precisely if the module is called
'foo.py', data file called 'foo', they are both in
/usr/lib/python2.6/site-packages and if foo.py I have open('foo') I'll
get a file not found error.

Any ideas?

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path to data files

2010-08-19 Thread Daniel Kluev
On Thu, Aug 19, 2010 at 9:25 PM, Daniel Fetchinson <
fetchin...@googlemail.com> wrote:

> If a python module requires a data file to run how would I reference
> this data file in the source in a way that does not depend on whether
> the module is installed system-wide, installed in $HOME/.local or is
> just placed in a directory from where the interpreter is fired up? I'd
> like to always keep the python source and the data file in the same
> directory, be it /usr/lib/python2.6/site-packages,
> $HOME/.local/lib/python2.6/site-packages or
> /arbitrary/path/to/somewhere.
>

open(os.path.join(os.path.dirname(__file__), 'foo'))

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread spinoza1111
On Aug 18, 1:44 am, James Kanze  wrote:
> On Aug 17, 6:21 pm, Standish P  wrote:
>
> > > Garbage collection doesn't use a stack. It uses a "heap",
> > > which is in the abstract a collection of memory blocks of
> > > different lengths, divided into two lists, generally
> > > represented as linked lists:
> > > 1.  A list of blocks that are free and may be used to store
> > > new data
> > > 2.  A list of blocks that are in use, or haven't been freed (yet)
> > Is this all that a heap is or is there more to it ?
>
> There are many different ways to implement a heap.  The above is
> not a good one, and I doubt that it's really used anywhere.

Actually, that's the only way to implement a heap in the abstract.
Forest and trees, mate. Mathematically a heap is a block of storage, a
list of free blocks and a list of allocated blocks. All the rest is
detail for the little techies to normally, get wrong. The confusion
between scientific and technical progress is a mirror of the (far more
serious) confusion between scientific progress and ethical advance.

Sure, when you free a block it is a good idea to see if you can join
it with its neighbors to get the biggest "bang for the buck". This,
again, is a detail relative to the grand plan which gives only techies
a hard-on, because the way scientific is confused with technical
progress is, in Foucault's terms, capillary. Part of ethical
regression is the overemphasis on efficiency and metaphors taken from
America's genocidal first use of nuclear weapons.

>
> > I have been looking for simple but complete explanation of
> > heap for a while and not gotten to it.
>
> Complete in what sense?  The basic principle of how to use it is
> simple.  As for how to implement it, there are many different
> algorithms that can be used.

Correct, for a change.

>
> > I think I am looking for a stack allocation on the same
> > pattern.
>
> Stack allocation is far, far simpler (usually).

And very different.

>
> > In a disk, a file is fragmented in many contiguous blocks and
> > is accessed automatically.
>
> At the system level, the same thing holds for memory, and the
> actual physical memory is "fragmented" into contiguous blocks,
> each the size of a page.  The MMU (hardware) makes this
> transparent to user programs, however.
>
> > > There is no way you could do memory management of all but the most
> > > trivial and fixed-length data chunks using a stack.
>
> The length isn't the issue.  The order of allocation and freeing
> is.  (For many specific uses, stack based allocators can and
> have been used, but they don't work for generally allocation.)
>
> --
> James Kanze

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


Re: path to data files

2010-08-19 Thread Daniel Fetchinson
>> If a python module requires a data file to run how would I reference
>> this data file in the source in a way that does not depend on whether
>> the module is installed system-wide, installed in $HOME/.local or is
>> just placed in a directory from where the interpreter is fired up? I'd
>> like to always keep the python source and the data file in the same
>> directory, be it /usr/lib/python2.6/site-packages,
>> $HOME/.local/lib/python2.6/site-packages or
>> /arbitrary/path/to/somewhere.
>>
>
> open(os.path.join(os.path.dirname(__file__), 'foo'))

Thanks a lot!

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Tim Chase

On 08/19/10 02:10, Νίκος wrote:

("nikos",) is a single element tuple.
["nikos"] is a single element list.
["nikos",] is also a single element list, just written like the tuple.


It makes more sense if i:

"nikos" is just a string
("nikos") is a single element tuple
["nikos"] is also a single element list

After all () used to define tuples and [] usedd to define lists. Why
commas?


You have to look at the other side:  what *else* they're used 
for.  Python also uses () to override order of operations (and to 
call functions, but that's contextually different) which can 
occur in the same context as tuples, while [] are used only 
within contexts where they can be disambiguated.  Going back to 
one of the originals example posted in this thread:


  (1) + (2)

do you think this should yield (1, 2) or 3?  It would be crazy if 
evaluation of


  (3*14) + (7*21)

was reduced, treated as "(42) + (147)" and then reduced to 
"(42,147)" instead of 189.


So Python needs a way to express that you *explicitly* mean "this 
is one of those rare one-element tuples, not an order of 
operations prioritization":


  (1,) + (2,)

to return "(1,2)"


Also is there a difference between 'nikos' or "nikos" or '''nikos''' ?
What's and why best to use to enclose strings?


Internally, there's no difference other than how easily you can 
include " or ' characters in your string.  Thus you might write:


  with_dquote = 'He said "Hello"'
  with_apos = "It's 2:00am"
  with_both1 = """She said "Don't touch me" to her boss"""
  with_both2 = '''She said "Don't touch me" to her boss'''

You can also prefix any of them with "r" such as

  file_path = r"c:\path\to\file.txt"
  file_path = r'c:\path\to\file.txt
  file_path = r"""c:\path\to\file.txt"""
  file_path = r'''c:\path\to\file.txt'''

to alter how "\" are treated.

Otherwise, if it doesn't make a difference, I tend to use C-ish 
conventions of using " for strings and ' for single characters:


  if 'w' in "hello world":

but the important/kind thing is to be internally consistent to 
make your own life easier. :)


-tkc





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


Re: Unsupported Format Character '&' (0x26)

2010-08-19 Thread Peter Otten
Andrew Evans wrote:

> On Wed, Aug 18, 2010 at 4:35 PM, Andrew Evans  wrote:
> 
>> I get an error message "Unsupported Format Character '&' (0x26)" I
>> narrowed it down to these two variables
>>
>> any idea how to fix it?
>>
>>   SEARCH_URL_0 = "http://search.yahoo.com/search...?p=%(query)..."

> nvm I got it by adding s and d respectively after each value eg %(query)s

If you want to handle this reliably have a look at urllib.urlencode().

Peter


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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Stefan Schwarzer
Hi Νίκος,

On 2010-08-19 09:10, Νίκος wrote:
> On 18 Αύγ, 12:50, Cameron Simpson  wrote:
>>
>> ("nikos",) is a single element tuple.
>> ["nikos"] is a single element list.
>> ["nikos",] is also a single element list, just written like the tuple.
> 
> It makes more sense if i:
> 
> "nikos" is just a string
> ("nikos") is a single element tuple
> ["nikos"] is also a single element list
> 
> After all () used to define tuples and [] usedd to define lists. Why
> commas?

Because parentheses are also used to group expressions.
For example,

>>> 2 * (1+2)
6

If it were as you would like, the result would have been

(3, 3)

So because  inside parentheses
already denotes an expression you have to add a comma to
distinguish a one-element tuple from an expression.

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


How do I make python test.py work without a syntax error msg?

2010-08-19 Thread Agida Kerimova
I am new to programming/python and have been having some difficulties
getting started. I can't seem to run scripts without a syntax error msg.
When I drag the file to the IDLE launcher or run the module it works, but
when I actually type it I get an error msg. I've been told  that the path to
python executable is missing or that i have to specify the path but im not
sure how to do this. I read some articles online but they are not very
clear. A lot of the articles talk about doing this on windows but i have a
mac. Also when I type python at the prompt it starts. Can someone please let
me know what Im doing wrong or give me some advice?

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


Re: path to data files

2010-08-19 Thread Alain Ketterlin
Daniel Fetchinson  writes:

> If a python module requires a data file to run how would I reference
> this data file in the source in a way that does not depend on whether
> the module is installed system-wide, installed in $HOME/.local or is
> just placed in a directory from where the interpreter is fired up?

sys.path[0] is supposed to contain the script's directory.

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


Re: [Python] Unsupported Format Character '&' (0x26)

2010-08-19 Thread Chris Gonnerman

On 08/18/2010 06:35 PM, Andrew Evans wrote:
I get an error message "Unsupported Format Character '&' (0x26)" I 
narrowed it down to these two variables


any idea how to fix it?

  SEARCH_URL_0 = 
"http://search.yahoo.com/search;_ylt=A0oGdEf1XGxMJRoAUdml87UF;_ylc=X1MDMjE0MjQ3ODk0OARfcgMyBGZyA3NmcARuX2dwcwMxMARvcmlnaW4Dc3ljBHF1ZXJ5A3Rlc3QEc2FvAzE-?p=%(query)&fr=sfp&fr2=&iscqry= 
"
NEXT_PAGE_0 = 
"http://search.yahoo.com/search;_ylt=A0oGdEEMXWxMnBAAiWhXNyoA?p=%(query)&fr=sfp&xargs=12KPjg1qNyy4-MkfqnfKqLCLLAhlMFta2E&pstart=%(start)&b=11 
"



Not %(query)

Should be %(query)s

The 's' means "string."

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


Re: How do I make python test.py work without a syntax error msg?

2010-08-19 Thread Sergey Smirnov
*when I actually *

*type it I get an error msg*

Did you type python commands in a bash console? In case you did, you should
run python interactive console instead. Just type python in terminal window
and than you'll be able interactively run statements.

If you have your script saved in a file, for instance, script.py, to run it
on your Mac you should type:
$ python script.py

It would be easier to understand you if you'll post errors messages here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I make python test.py work without a syntax error msg?

2010-08-19 Thread Benjamin Kaplan
On Thu, Aug 19, 2010 at 8:22 AM, Agida Kerimova  wrote:
> I am new to programming/python and have been having some difficulties
> getting started. I can't seem to run scripts without a syntax error msg.
> When I drag the file to the IDLE launcher or run the module it works, but
> when I actually type it I get an error msg. I've been told  that the path to
> python executable is missing or that i have to specify the path but im not
> sure how to do this. I read some articles online but they are not very
> clear. A lot of the articles talk about doing this on windows but i have a
> mac. Also when I type python at the prompt it starts. Can someone please let
> me know what Im doing wrong or give me some advice?
> Thanks!
> --


Are you trying to run ./test.py? If so, make sure you use a shebang
line. The Unix shell doesn't care about those silly little things
called file extensions- that's just part of the file name, after all.
Any executed file will use the shell (bash on OS X) unless you specify
otherwise. Add the following line to the top of the file:
#!/usr/bin/env python

Or, just call the Python interpreter directly
python test.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I make python test.py work without a syntax error msg?

2010-08-19 Thread Sergey Smirnov
I see.
Your script begins with a string:

$ python test.py

It's not a valid python code. Maybe you just copied this text to your script
accidentally. Try to delete the first string. Can you send a few first
strings of your script?


On Thu, Aug 19, 2010 at 17:05, Agida Kerimova  wrote:

> this is what it looks like
>
>
> On Thu, Aug 19, 2010 at 7:01 PM, Agida Kerimova  wrote:
>
>> Hi, I don't know how to work in a non bash console... I typed python in a
>> terminal window and all but it didn't work...
>>
>>
>>
>>
>>
>>
>> On Thu, Aug 19, 2010 at 5:53 PM, Sergey Smirnov wrote:
>>
>>>  *when I actually *
>>>
>>> *type it I get an error msg*
>>>
>>> Did you type python commands in a bash console? In case you did, you
>>> should run python interactive console instead. Just type python in terminal
>>> window and than you'll be able interactively run statements.
>>>
>>> If you have your script saved in a file, for instance, script.py, to run
>>> it on your Mac you should type:
>>> $ python script.py
>>>
>>> It would be easier to understand you if you'll post errors messages here.
>>>
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread Anton Ertl
John Nagle  writes:
>In the superscalar era, there's not much of an advantage to avoiding
>stack accesses.

Apart from 4stack, I am not aware of a superscalar stack machine (and
4stack is more of an LIW than a superscalar).

OTOH, if by stack accesses you mean memory accesses through the stack
pointer on a register machine, then evidence contradicts your claim.
E.g., if we can keep one or two more of Gforth's VM's registers in
real registers rather than on the stack of an IA32 CPU, we see
significant speedups (like a factor of 2).

>x86 superscalar machines have many registers not
>visible to the program, as the fastest level of cache.

They have a data cache for memory accesses (about 3 cycles load-to-use
latency on current CPUs for these architectures), and they have rename
registers (not visible to programmers) that don't cache memory.  They
also have a store buffer with store-to-load forwarding, but that still
has no better load-to-use latency.

>In practice,
>the top of the stack is usually in CPU registers.

Only if the Forth system is written that way.

> The "huge number
>of programmer-visible register" machines like SPARCs turned out to be
>a dead end.

Really?  Architectures with 32 programmer-visible registers like SPARC
(but, unlike SPARC, without register windows) are quite successful in
embedded systems (e.g., MIPS, SPARC).

>So did making all the instructions the same width; it
>makes the CPU simpler, but not faster, and it bulks up the program
>by 2x or so.

In the beginning it also made the CPU faster.  As for the bulk, here's
some data from <2007dec11.202...@mips.complang.tuwien.ac.at>; it's the
text (code) size of /usr/bin/dpkg in a specific version of the dpkg
package:

.text
section
 98132 dpkg_1.14.12_hurd-i386.deb
230024 dpkg_1.14.12_m68k.deb
249572 dpkg_1.14.12_amd64.deb
254984 dpkg_1.14.12_arm.deb
263596 dpkg_1.14.12_i386.deb
271832 dpkg_1.14.12_s390.deb
277576 dpkg_1.14.12_sparc.deb
295124 dpkg_1.14.12_hppa.deb
320032 dpkg_1.14.12_powerpc.deb
351968 dpkg_1.14.12_alpha.deb
361872 dpkg_1.14.12_mipsel.deb
371584 dpkg_1.14.12_mips.deb
615200 dpkg_1.14.12_ia64.deb

Sticking with the Linux packages (i.e., not the Hurd one), the range
in code size increase over the i386 code is 0.97 (ARM) to 1.41 (MIPS)
for the classical architectures with fixed-size instructions (RISCs).
Only the IA64 has a code size increase by a factor of 2.33.  Note that
code size is not everything that's in a program binary, and the rest
should be unaffected by whether the instructions are fixed-size or
variable-sized, so the overall effect on the binary will be smaller.

- anton
-- 
M. Anton Ertl  http://www.complang.tuwien.ac.at/anton/home.html
comp.lang.forth FAQs: http://www.complang.tuwien.ac.at/forth/faq/toc.html
 New standard: http://www.forth200x.org/forth200x.html
   EuroForth 2010: http://www.euroforth.org/ef10/
-- 
http://mail.python.org/mailman/listinfo/python-list


Contains/equals

2010-08-19 Thread Karsten Wutzke
Hello,

I have an object which has a list of other complex objects. How do I
best achieve a complex "contains" comparison based on the object's
class? In Java terms, I'm looking for an equivalent to equals(Object)
in Python. Does a similar thing exist? Directions appreciated.

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


Creating a PYD file

2010-08-19 Thread Rony
Is a PYD file created from Pyrex faster in execution then a PYD file
created from python source ?

Tia

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


Re: 79 chars or more?

2010-08-19 Thread Roald de Vries

Dear Jean-Michel,

On Aug 18, 2010, at 10:57 AM, Jean-Michel Pichavant wrote:

At least, if you still want to stick with 79 chars, do something like

text = find(response, 'MPNExpirationDate', ).text
self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y')


I don't necessarily like this example *so* much. I have no real  
problem with it, and maybe would write it myself sometimes, but I'm  
curious what people think of the following reasoning.


I think that, for optimal readability, variable names should reflect  
the role if the function/class/module of the variable they refer to.  
If you stick to this convention, a function can normally be read very  
easily by just scanning through the left part of assignment  
statements. In your case, it looks like text would better be called  
expiration_text, or something like that. But what I would like better,  
is:


self.expiration_date = translate_date(
text= find(response, 'MPNExpirationDate', ).text,
format1 = '%Y-%m-%d', # I don't know the argument name
format2 = '%m%d%Y',   # ... and of this one neither
)

Moreover, the 'text = ...'-like statement, that are only used in the  
one statement after it, often interrupt a (more) logical sequence of  
variable assignments, and make your program a bit less readable.


Cheers, Roald


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


Re: Python "why" questions

2010-08-19 Thread Grant Edwards
On 2010-08-19, Russ P.  wrote:

> And I'd still like to know if the "1st" element of aList is aList[0]
> or aList[1].

aList[0]

-- 
Grant Edwards   grant.b.edwardsYow! I'm definitely not
  at   in Omaha!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Contains/equals

2010-08-19 Thread Peter Otten
Karsten Wutzke wrote:

> I have an object which has a list of other complex objects. How do I
> best achieve a complex "contains" comparison based on the object's
> class? In Java terms, I'm looking for an equivalent to equals(Object)
> in Python. Does a similar thing exist? Directions appreciated.

I can't infer from your question whether you already know about 
__contains__(). So there:

>>> class Cornucopia:
... def __contains__(self, other):
... return True
...
>>> c = Cornucopia()
>>> 42 in c
True
>>> "cherry pie" in c
True
>>> c in c
True

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


Re: Contains/equals

2010-08-19 Thread Karsten Wutzke
On Aug 19, 4:47 pm, Peter Otten <__pete...@web.de> wrote:
> Karsten Wutzke wrote:
> > I have an object which has a list of other complex objects. How do I
> > best achieve a complex "contains" comparison based on the object's
> > class? In Java terms, I'm looking for an equivalent to equals(Object)
> > in Python. Does a similar thing exist? Directions appreciated.
>
> I can't infer from your question whether you already know about
> __contains__(). So there:
>
> >>> class Cornucopia:
>
> ...     def __contains__(self, other):
> ...             return True
> ...>>> c = Cornucopia()
> >>> 42 in c
> True
> >>> "cherry pie" in c
> True
> >>> c in c
>
> True

Whoops that easy... Thanks!
Karsten
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Contains/equals

2010-08-19 Thread Alex Hall
On 8/19/10, Peter Otten <__pete...@web.de> wrote:
> Karsten Wutzke wrote:
>
>> I have an object which has a list of other complex objects. How do I
>> best achieve a complex "contains" comparison based on the object's
>> class? In Java terms, I'm looking for an equivalent to equals(Object)
>> in Python. Does a similar thing exist? Directions appreciated.
>
> I can't infer from your question whether you already know about
> __contains__(). So there:
>
 class Cornucopia:
> ... def __contains__(self, other):
> ... return True
> ...
 c = Cornucopia()
 42 in c
> True
 "cherry pie" in c
> True
 c in c
> True
You may also want to use the double equals operator; in Java, one
thing I wish I could do is
String s="abc";
String t="def";
if(s==t)...
In Python, as I understand it, you can define this behavior.

class c(object):
 def __init__(self, a=1, b=2):
  self.a=a; self.b=b

 def __eq__(self, obj):
  if self.a==obj.a and self.b==obj.b: return True
  return False


You can now say:
obj1=c()
obj2=c()
print(obj1==obj2) #prints True
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Contains/equals

2010-08-19 Thread Christian Heimes
Am 19.08.2010 17:00, schrieb Alex Hall:
> In Python, as I understand it, you can define this behavior.
> 
> class c(object):
>  def __init__(self, a=1, b=2):
>   self.a=a; self.b=b
> 
>  def __eq__(self, obj):
>   if self.a==obj.a and self.b==obj.b: return True
>   return False

Yes, but you have to return NotImplemented when your type doesn't know
how to handle the other type.

class C(object):
def __eq__(self, other):
if not isinstance(other, C):
return NotImplemented
return self.a == other.a

Christian

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


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread Richard Harter
On Wed, 18 Aug 2010 01:39:09 -0700 (PDT), Nick Keighley
 wrote:

>On 17 Aug, 18:34, Standish P  wrote:

>> How are these heaps being implemented ? Is there some illustrative
>> code or a book showing how to implement these heaps in C for example ?
>
>any book of algorithms I'd have thought
>
>http://en.wikipedia.org/wiki/Dynamic_memory_allocation
>http://www.flounder.com/inside_storage_allocation.htm
>
>I've no idea how good either of these is

The wikipedia page is worthless.  The flounder page has
substantial meat, but the layout and organization is a mess.  A
quick google search didn't turn up much that was general - most
articles are about implementations in specific environments.


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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 2:32 μμ, ο/η Tim Chase έγραψε:
So Python needs a way to express that you *explicitly* mean "this is 
one of those rare one-element tuples, not an order of operations 
prioritization":


  (1,) + (2,)
to return "(1,2)"
Yes i can see the difference now!! I just had to look at the big picture 
here! There is no other way of seperating this for that.



You can also prefix any of them with "r" such as

  file_path = r"c:\path\to\file.txt"
  file_path = r'c:\path\to\file.txt
  file_path = r"""c:\path\to\file.txt"""
  file_path = r'''c:\path\to\file.txt''' 


'r' is to avoid escaping backslashes only or other special charcaters as 
well?


As for the string i noticed that if i'am to mix single quotes and double 
quotes(any number of them not just always pairs)
and backslashes and other special stuff in them then i'm best off using 
3-sinlge-quotes like


name='''My name is "Nikos" and i'am from Thessaloniki\Greece'''

The above example can only be written by using 3-single quoting right? 
Not by pairs of single or double quotes, correct?


And i dont have to use the 'r' in fornt of it too.

===

Also if you please comment on my mysql string substitution example i've 
posted in my previous post just to make it work.

I want it to be able to delete my data but it fails when i try to

http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * 
FROM visitors" 



please try it yourself, i dont mind lossign the data i just want to see 
if this mysql in jection can actually work.


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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 2:32 μμ, ο/η Tim Chase έγραψε:

  (1,) + (2,)

to return "(1,2)" 
This is actually joining two single element tuples (1,)  and (2, ) to a 
new bigger tuple of two elements, correct?

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


Re: How to see intermediate fail results from unittest as tests are running?

2010-08-19 Thread Margie Roginski
On Aug 19, 12:41 am, Peter Otten <__pete...@web.de> wrote:
> Margie Roginski wrote:
> > I am using unittest in a fairly basic way, where I have a single file
> > that simply defines a class that inherits from unittest.TestCase and
> > then within that class I have a bunch of methods that start with
> > "test".  Within that file, at the bottom I have:
>
> > if __name__ == "__main__":
> >     unittest.main()
>
> > This works fine and it runs all of the testxx() methods in my file.
> > As it runs it prints if the tests passed or failed, but if they fail,
> > it does not print the details of the assert that made them fail.  It
> > collects this info up and prints it all at the end.
>
> > Ok - my question: Is there any way to get unittest to print the
> > details of the assert that made a test fail, as the tests are
> > running?  IE, after a test fails, I would like to see why, rather than
> > waiting until all the tests are done.
>
> Not exactly what you're asking for, but 2.7 has grown a --failfast option
> that tells unittest to stop on the first failure. For older Python versions
> you can use nose
>
> nosetests -x myscript.py
>
> athttp://somethingaboutorange.com/mrl/projects/nose/0.11.2/
> or the unittest backport athttp://pypi.python.org/pypi/unittest2
>
> Peter

Thanks for the pointers, I will give those a try.

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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Tim Chase

On 08/19/10 10:42, Nik Gr wrote:

You can also prefix any of them with "r" such as

   file_path = r"c:\path\to\file.txt"
   file_path = r'c:\path\to\file.txt
   file_path = r"""c:\path\to\file.txt"""
   file_path = r'''c:\path\to\file.txt'''


'r' is to avoid escaping backslashes only or other special charcaters as
well?


Yes, just backslashes.


As for the string i noticed that if i'am to mix single quotes and double
quotes(any number of them not just always pairs)
and backslashes and other special stuff in them then i'm best off using
3-sinlge-quotes like

name='''My name is "Nikos" and i'am from Thessaloniki\Greece'''

The above example can only be written by using 3-single quoting right?
Not by pairs of single or double quotes, correct?


It can be written as a non-3-quote string, you just have to 
escape the inner quotes (single & double) and the backslash to be 
seen:


  name = 'My name is Nikos and I\'m from Thessaloniki\\Greece'
  name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece"


And i dont have to use the 'r' in fornt of it too.


Using the 'r' in front would make it much more challenging, 
because it would prevent the backslashes from being seen as 
escaping. :)



  (1,) + (2,)

to return "(1,2)"


This is actually joining two single element tuples (1,)  and (2, ) to a
new bigger tuple of two elements, correct?


Correct.


Also if you please comment on my mysql string substitution example i've
posted in my previous post just to make it work.


There's a number of variables which can impact the exact string 
that would need to be passed, so it's not a trivial thing to do. 
 You may or may not be un-escaping HTML entities in the GET 
parameters ("%20" -> a space, etc), and I don't have a readily 
available way to duplicate your environment, so testing becomes a 
bit harder.  Hopefully others on the list can give you a hand on 
breaking your code.


-tkc



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


bug? context managers vs ImportErrors

2010-08-19 Thread Chris Withers

Hi All,

Am I right in thinking this is a bug:

class MyContextManager:

def __enter__(self):
pass

def __exit__(self,t,e,tb):
print type(t),t
print type(e),e


with MyContextManager():
   import foo.bar.baz

...when executed, gives me:

 
 No module named foo.bar.baz

Why is 'e' ending up as a string rather than the ImportError object?

This is with Python 2.6.5 if that makes a difference...

Chris

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


Reading the access attributes of directories in Windows

2010-08-19 Thread vsoler
Hello everyone!

I need to read, for each of the directories in a shared file server
unit, who has access to the directories and what type of access
privileges.

This is something that I can easily do interactively in my Windows
Document Explorer by right clicking a single directory, clicking on
Properties, then on Security.

There I can see the Users and Group of Users that have access to the
selected directory, as well as the type of access to that directory
(Read/Write/eXecute etc.)

Since I have to prepare a new access scheme, I first need to read what
the current situation is.

I've been looking in the "os" library, and found the "os.chmod" method
but I am not sure that it is going to give me what I need. Should I
also used library "stat"?

So far I have not been able to find my way to the solution of this
problem.

Googling the web, I have seen that some examples provive some kind of
information but using codes (755 or 0577) that I shoud translate to
some form of understandable text messages.

I think that my problem consists of finding the correct library/method
to get the solution.

Can anybody help?

Thank you


Using Python 3.1 on Windows Vista
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?

2010-08-19 Thread Keith Thompson
Standish P  writes:
> On Aug 18, 5:38 pm, Keith Thompson  wrote:
[...]
>> Show me how this is relevant to comp.lang.c, comp.lang.c++, comp.theory,
>> or comp.lang.python.  Please trim the Newsgroups line.
>
> provide a rigorous proof that people are more interested in the
> nauseating nude pictures that you post of your mother in the
> newsgroups than in the subject of forth implementation.
[snip]

*plonk*

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: eGenix mxODBC - Python ODBC Database Interface 3.1.0

2010-08-19 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

 eGenix.com mxODBC - Python ODBC Database Interface

   Version 3.1.0


mxODBC is our commercially supported Python extension providing
 ODBC database connectivity to Python applications
on Windows, Mac OS X, Unix and BSD platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mxODBC-3.1.0-GA.html



INTRODUCTION

mxODBC provides an easy-to-use, high-performance, reliable and robust
Python interface to ODBC compatible databases such as MS SQL Server,
MS Access, Oracle Database, IBM DB2 and Informix , Sybase ASE and
Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more:

 http://www.egenix.com/products/python/mxODBC/

The "eGenix mxODBC - Python ODBC Database Interface" product is a
commercial extension to our open-source eGenix mx Base Distribution:

 http://www.egenix.com/products/python/mxBase/



NEWS

The new mxODBC 3.1.0 release comes with many new features and supports
more ODBC drivers, manager and platforms than ever before.


Release Highlights
--

* We've added Python 2.7 support and builds for all platforms.

* mxODBC 3.1 adds native support for the Windows 64-bit platforms
  as well as the Mac OS X 10.6 (Snow Leopard) 64-bit builds of
  Python.

* mxODBC now fully supports the Oracle Instant Client ODBC driver.

* We have updated the support for the latest IBM DB2 9.7 ODBC
  drivers and enhanced compatibility of mxODBC with the MS SQL
  Server Native Client ODBC driver on Windows and the Sybase ASE 15
  ODBC drivers on Unix.

* mxODBC 3.1 adds support for large-scale data warehouse databases
  Netezza and Teradata.

* In addition to the Windows, Mac OS X, iODBC and unixODBC ODBC
  driver managers, we now also include support for the DataDirect
  ODBC manager.

* The 64-bit support on Unix platforms was updated to support the
  new unixODBC 2.3.0 version.

* We've improved the documentation on how to connect to various
  popular databases and now include many tips & tricks for each
  database/driver.

* The Python 2.7 memoryview object is now supported as binary data
  container.

* We have simplified handling of database warnings using a new
  customizable .warningformat attribute.

* The catalog methods now accept both Unicode and 8-bit strings as
  parameters.

* You can now select whether to use ANSI (8-bit) or Unicode ODBC
  APIs in the ODBC drivers, removing unnecessary data conversions
  and enhancing ODBC driver compatibility.

For the full set of changes please check the mxODBC change log:

http://www.egenix.com/products/python/mxODBC/changelog.html


Feature Highlights
--

* Python Database API 2.0 Compliance: the mxODBC API is fully
  Python DB-API 2.0 compatible and implements a large number of
  powerful extensions.

* Support for all popular ODBC Drivers: mxODBC includes
  adjustments and work-arounds to support MS SQL Server Native
  Client, MS SQL Server ODBC Driver, FreeTDS ODBC Driver, Oracle
  Instant Client ODBC Driver, IBM DB2 ODBC Driver, Sybase ASE ODBC
  Driver, Netezza ODBC Driver, Teradata ODBC Driver, PostgreSQL
  ODBC Driver, MySQL ODBC Driver, .MaxDB ODBC Driver as well as
  the ODBC driver sets of EasySoft, DataDirect, OpenLink, Actual
  Technologies.

* Support for all popular ODBC Driver Managers: mxODBC comes with
  subpackages for the native Windows and Mac OS X ODBC managers,
  as well as the ODBC managers unixODBC, iODBC and DataDirect,
  which are commonly used on Unix systems.

* Stable, robust and reliable:the mxODBC API has been in active
  production use for more than 10 years.

* Full Python Support: mxODBC works with Python 2.3, 2.4, 2.5, 2.6
  and 2.7.

* Full 64-bit Support: mxODBC runs on the following 64-bit
  platforms: Windows, Linux, FreeBSD and Mac OS X.

For the full set of features mxODBC has to offer, please see:

http://www.egenix.com/products/python/mxODBC/#Features


New mxODBC Editions
---

Due to popular demand, we have extended the set of available mxODBC
editions and included a new low-cost standard edition. mxODBC is now
available in thesethree editions:

* The low-cost Standard Edition which provides data connectivity
  to a selected set of database backends.

* The Professional Edition, which gives full access to all mxODBC
  features.

* The Product Development Edition, which allows including mxODBC
  in applications you develop.

At the same time we have simplified our license terms to cla

Re: Python "why" questions

2010-08-19 Thread J.B. Brown
2010/8/9 MRAB :
> Default User wrote:
>>
>> Not to prolong a good "food fight", but IIRC, many years ago in QBasic,
>> one could choose
>>
>> OPTION BASE 0
>>
>> or
>>
>> OPTION BASE 1
>>

When I wrote my own C++ 2-D matrix class, I wrote a member function
which did exactly this - allow you to specify the initial index value.
Then users of my class (mainly my research lab coworkers) could
specify whichever behavior they wanted.

In terms of providing readable code and removing beginning programmer
confusion, why not extend python lists by using something similar to
(but not necessarily identical to)  the C++ STL containers:

C++
int myX[ ]  = { 1,2,3,4,5 };
std::vector vectorX( myX, &myX[  sizeof( myX ) - 1 ] );
std::cout << vectorX.begin() << std::endl;
std::cout << vectorX.end() << std::endl;

Python
x = [ 1 , 2 , 3 , 4 , 5 ]
print x.first()
print x.last(),

where the first and last behavior of python is to return a deep copy
of the object, and not a pointer.
It seems that this would avoid complaints about the 0/1 issue.

Of course, the problem is the behavior of:
myList = [ myObject1, myObject2, myObject3, ... , myObjectLast ]
print myList.first() + 5   ,

in which one will conceptually might want to get the 6th item in a
list, though if first() is defined to return the object, then we get
the returned object plus 5, if such behavior is defined to exist.
I completely acknowledge that the behavior is not well defined, and
that is why I am not proposing this as a final implementation, but
rather as a concept and motivation.

For those who don't like Python's 0-based indexing, why not just build
a wrapper type which features an item() method that handles the
internal conversion from 1 to 0 as the starting index?
Better yet, include a method which sets/specifies the 0/1 behavior,
and have item() reference the 0/1 setting to obtain the proper offset.

Just a thought.

J.B. Brown
Kyoto University
-- 
http://mail.python.org/mailman/listinfo/python-list


Python module Code returns empty list any ideas how to fix

2010-08-19 Thread Andrew Evans
Hello I am trying to modify Python xgoogle module to use yahoo

I have hit a road block where I receive no error messages the code I use to
test just returns an empty list.

and I don't know how to trouble shoot it

the module code is here

http://pastebin.com/iTibRs1R

and the code I am using to test is this

import re
from urlparse import urlparse
from xyahoo.search import YahooSearch, SearchError

gs = YahooSearch("quick and dirty")
print gs
gs.results_per_page = 50
results = gs.get_results()
print results
for res in results:
print res.title.encode("utf8")
print res.desc.encode("utf8")
print res.url.encode("utf8")

Any idea how to fix the module *cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread Neil Cerutti
On 2010-08-19, J.B. Brown  wrote:
> When I wrote my own C++ 2-D matrix class, I wrote a member
> function which did exactly this - allow you to specify the
> initial index value. Then users of my class (mainly my research
> lab coworkers) could specify whichever behavior they wanted.

I did something similar in a library that needs to read
"positions" from the specification for a fixed-length fields
plain text database.

The printed specs for these document types often start counting
character positions at 1, but not universally.

> For those who don't like Python's 0-based indexing, why not
> just build a wrapper type which features an item() method that
> handles the internal conversion from 1 to 0 as the starting
> index? Better yet, include a method which sets/specifies the
> 0/1 behavior, and have item() reference the 0/1 setting to
> obtain the proper offset.

Because they know deep down they wouldn't win anything.

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


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 16:58:30 +0100, Chris Withers wrote:

> Hi All,
> 
> Am I right in thinking this is a bug:
> 
> class MyContextManager:
> 
>  def __enter__(self):
>  pass
> 
>  def __exit__(self,t,e,tb):
>  print type(t),t
>  print type(e),e
> 
> 
> with MyContextManager():
> import foo.bar.baz
> 
> ...when executed, gives me:
> 
>  
>  No module named foo.bar.baz
> 
> Why is 'e' ending up as a string rather than the ImportError object?

Because e is the exception value, not an exception instance. In other 
words, if you call t(e) you will get the instance you're expecting.

See the docs:

http://docs.python.org/library/stdtypes.html#contextmanager.__exit__

The three arguments exc_type, exc_value, exc_tb are the same three 
arguments you can pass to the raise statement:

http://docs.python.org/reference/simple_stmts.html#the-raise-statement

(BTW, I'm not suggesting you should do that from inside the __exit__ 
method.)

So, no, this is not a bug.



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


Re: Contains/equals

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote:

>  def __eq__(self, obj):
>   if self.a==obj.a and self.b==obj.b: return True
>   return False


That would be the same as:

   def __eq__(self, obj):
 return self.a==obj.a and self.b==obj.b



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


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Ethan Furman

Chris Withers wrote:

Hi All,

Am I right in thinking this is a bug:

class MyContextManager:

def __enter__(self):
pass

def __exit__(self,t,e,tb):
print type(t),t
print type(e),e


with MyContextManager():
   import foo.bar.baz

...when executed, gives me:

 
 No module named foo.bar.baz

Why is 'e' ending up as a string rather than the ImportError object?

This is with Python 2.6.5 if that makes a difference...


I don't have an answer, just some more examples across different 
versions/exceptions:



class MyContextManager:
def __enter__(self):
pass
def __exit__(self,t,e,tb):
print ('')
print (type(t),t)
print (type(e),e)
return True

with MyContextManager():
   import foo.bar.baz
with MyContextManager():
   1/0
with MyContextManager():
   not_here()



c:\temp>\python25\python test.py
[0]

(, )
(, 'No module named bar.baz')

(, )
(, 'integer division or modulo by zero')

(, )
(, "name 'not_here' is not defined")

c:\temp>\python26\python test.py
[0]

(, )
(, 'No module named bar.baz')

(, )
(, 'integer division or modulo by zero')

(, )
(, "name 'not_here' is not defined")

c:\temp>\python27\python test.py
[0]

(, )
(, ImportError('No module named bar.baz',))

(, )
(, ZeroDivisionError('integer 
division or modulo by zero',))


(, )
(, NameError("name 'not_here' is not 
defined",))


c:\temp>\python31\python test.py

 
 invalid syntax (foo.py, line 3)

 
 int division or modulo by zero

 
 name 'not_here' is not defined



As an aside, does anyone know why the 2.x versions are printing the [0] 
as the first line?  3.1 does not.

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


Re: Python "why" questions

2010-08-19 Thread Russ P.
On Aug 19, 9:07 am, "J.B. Brown"  wrote:
> 2010/8/9 MRAB :
>
> > Default User wrote:
>
> >> Not to prolong a good "food fight", but IIRC, many years ago in QBasic,
> >> one could choose
>
> >> OPTION BASE 0
>
> >> or
>
> >> OPTION BASE 1
>
> When I wrote my own C++ 2-D matrix class, I wrote a member function
> which did exactly this - allow you to specify the initial index value.
> Then users of my class (mainly my research lab coworkers) could
> specify whichever behavior they wanted.
>
> In terms of providing readable code and removing beginning programmer
> confusion, why not extend python lists by using something similar to
> (but not necessarily identical to)  the C++ STL containers:
>
> C++
> int myX[ ]  = { 1,2,3,4,5 };
> std::vector vectorX( myX, &myX[  sizeof( myX ) - 1 ] );
> std::cout << vectorX.begin() << std::endl;
> std::cout << vectorX.end() << std::endl;
>
> Python
> x = [ 1 , 2 , 3 , 4 , 5 ]
> print x.first()
> print x.last()    ,

Many years ago I wrote a fairly comprehensive vector/matrix class in C+
+. (It was an exercise to learn the intricacies of C++, and I also
really needed it.) I used a system of offset pointers to realize
indexing that starts with 1.

Years later, after I had quit using it, I decided that I should have
just bit the bullet and let the indexing start with zero for
simplicity. I believe that zero-based indexing is a mistake, but
attempts to fix it require additional boilerplate that is prone to
error and inefficiency. Short of a major language overhaul, we are
essentially stuck with zero-based indexing.

But that doesn't mean we should pretend that it was the right choice.

For those who insist that zero-based indexing is a good idea, why you
suppose mathematical vector/matrix notation has never used that
convention? I have studied and used linear algebra extensively, and I
have yet to see a single case of vector or matrix notation with zero-
based indexing in a textbook or a technical paper. Also, mathematical
summation is traditionally shown as "1 to N", not "0 to N-1". Are
mathematicians just too simple-minded and unsophisticated to
understand the value of zero-based indexing? Or have you perhaps been
mislead?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote:

> The convention of starting with zero may have had some slight
> performance advantage in the early days of computing, but the huge
> potential for error that it introduced made it a poor choice in the long
> run, at least for high-level languages.

People keep saying this, but it's actually the opposite. Signpost errors 
and off-by-one errors are more common in languages that count from one.

A simple example: Using zero-based indexing, suppose you want to indent 
the string "spam" so it starts at column 4. How many spaces to you 
prepend?

0123456789
spam

Answer: 4. Nice and easy and almost impossible to get wrong. To indent to 
position n, prepend n spaces.

Now consider one-based indexing, where the string starts at column 5:

1234567890
spam

Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the 
1, hence the off-by-one errors.

Zero-based counting doesn't entirely eliminate off-by-one errors, but the 
combination of that plus half-open on the right intervals reduces them as 
much as possible.

The intuitive one-based closed interval notation used in many natural 
languages is terrible for encouraging off-by-one errors. Quick: how many 
days are there between Friday 20th September and Friday 27th September 
inclusive? If you said seven, you fail.

One-based counting is the product of human intuition. Zero-based counting 
is the product of human reason.


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


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Peter Otten
Ethan Furman wrote:

> Chris Withers wrote:
>> Hi All,
>> 
>> Am I right in thinking this is a bug:
>> 
>> class MyContextManager:
>> 
>> def __enter__(self):
>> pass
>> 
>> def __exit__(self,t,e,tb):
>> print type(t),t
>> print type(e),e
>> 
>> 
>> with MyContextManager():
>>import foo.bar.baz
>> 
>> ...when executed, gives me:
>> 
>>  
>>  No module named foo.bar.baz
>> 
>> Why is 'e' ending up as a string rather than the ImportError object?
>> 
>> This is with Python 2.6.5 if that makes a difference...
> 
> I don't have an answer, just some more examples across different
> versions/exceptions:
> 
> 
> class MyContextManager:
>  def __enter__(self):
>  pass
>  def __exit__(self,t,e,tb):
>  print ('')
>  print (type(t),t)
>  print (type(e),e)
>  return True
> 
> with MyContextManager():
> import foo.bar.baz
> with MyContextManager():
> 1/0
> with MyContextManager():
> not_here()
> 
> 
> 
> c:\temp>\python25\python test.py
> [0]
> 
> (, )
> (, 'No module named bar.baz')
> 
> (, )
> (, 'integer division or modulo by zero')
> 
> (, )
> (, "name 'not_here' is not defined")
> 
> c:\temp>\python26\python test.py
> [0]
> 
> (, )
> (, 'No module named bar.baz')
> 
> (, )
> (, 'integer division or modulo by zero')
> 
> (, )
> (, "name 'not_here' is not defined")
> 
> c:\temp>\python27\python test.py
> [0]
> 
> (, )
> (, ImportError('No module named bar.baz',))
> 
> (, )
> (, ZeroDivisionError('integer
> division or modulo by zero',))
> 
> (, )
> (, NameError("name 'not_here' is not
> defined",))
> 
> c:\temp>\python31\python test.py
> 
>  
>  invalid syntax (foo.py, line 3)
> 
>  
>  int division or modulo by zero
> 
>  
>  name 'not_here' is not defined
> 
> 
> 
> As an aside, does anyone know why the 2.x versions are printing the [0]
> as the first line?  3.1 does not.

If reading the error messages carefully doesn't help scroll down for a 
hint;)
























Look into foo.py

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


Django 1.2.1 - stuck with CSRF verification

2010-08-19 Thread Dodo

Hi all,
I followed the tutorial but at page 4 I can't get rid of CSRF errors, 
even though I followed everything in this page :

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

Any idea?

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


Re: Python "why" questions

2010-08-19 Thread Russ P.
On Aug 19, 11:04 am, Steven D'Aprano  wrote:
> On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote:
> > The convention of starting with zero may have had some slight
> > performance advantage in the early days of computing, but the huge
> > potential for error that it introduced made it a poor choice in the long
> > run, at least for high-level languages.
>
> People keep saying this, but it's actually the opposite. Signpost errors
> and off-by-one errors are more common in languages that count from one.
>
> A simple example: Using zero-based indexing, suppose you want to indent
> the string "spam" so it starts at column 4. How many spaces to you
> prepend?
>
> 0123456789
>     spam
>
> Answer: 4. Nice and easy and almost impossible to get wrong. To indent to
> position n, prepend n spaces.
>
> Now consider one-based indexing, where the string starts at column 5:
>
> 1234567890
>     spam
>
> Answer: 5-1 = 4. People are remarkably bad at remembering to subtract the
> 1, hence the off-by-one errors.
>
> Zero-based counting doesn't entirely eliminate off-by-one errors, but the
> combination of that plus half-open on the right intervals reduces them as
> much as possible.
>
> The intuitive one-based closed interval notation used in many natural
> languages is terrible for encouraging off-by-one errors. Quick: how many
> days are there between Friday 20th September and Friday 27th September
> inclusive? If you said seven, you fail.

The error mode you refer to is much less common than the typical off-
by-one error mode. In the far more common error mode, zero-based
indexing is far more error prone.

> One-based counting is the product of human intuition. Zero-based counting
> is the product of human reason.

I suggest you take that up with mathematicians, who have used one-
based indexing all along. That's why it was used in Fortran and
Matlab, among other more mathematical and numerically oriented and
languages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Ethan Furman

Peter Otten wrote:

Ethan Furman wrote:

As an aside, does anyone know why the 2.x versions are printing the [0]
as the first line?  3.1 does not.


If reading the error messages carefully doesn't help scroll down for a 
hint;)

.

> .
> .

Look into foo.py


AH hahahahahahah.  That's what I get for being in a hurry.  Thanks for 
catching that, Peter!


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


Re: Python "why" questions

2010-08-19 Thread Russ P.

I just checked, and Mathematica uses one-based indexing. Apparently
they want their notation to look mathematical.

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


Re: Django 1.2.1 - stuck with CSRF verification

2010-08-19 Thread Thomas Jollans
On Thursday 19 August 2010, it occurred to Dodo to exclaim:
> Hi all,
> I followed the tutorial but at page 4 I can't get rid of CSRF errors,
> even though I followed everything in this page :
> http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
> 

what kind of errors? Any exception tracebacks you can show us maybe? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote:

> For those who insist that zero-based indexing is a good idea, why you
> suppose mathematical vector/matrix notation has never used that
> convention? I have studied and used linear algebra extensively, and I
> have yet to see a single case of vector or matrix notation with zero-
> based indexing in a textbook or a technical paper. Also, mathematical
> summation is traditionally shown as "1 to N", not "0 to N-1". 

In my experience, it's more likely to be "0 to N" than either of the 
above, thus combining the worst of both notations.


> Are
> mathematicians just too simple-minded and unsophisticated to understand
> the value of zero-based indexing?

No, mathematicians are addicted to tradition.

Unlike computer scientists, who create new languages with radically 
different notation and syntax at the drop of a hat, mathematicians almost 
never change existing notation. Sometimes they *add* new notation, but 
more often they just re-use old notation in a new context. E.g. if you 
see (5, 8), does that mean a coordinate pair, a two-tuple, an open 
interval, or something else?

Additionally, mathematical notation isn't chosen for its ability to 
encourage or discourage errors. It seems often to be chosen arbitrarily, 
or for convenience, but mostly out of tradition and convention. Why do we 
use "x" for "unknown"? Why do we use i for an integer value, but not r 
for a real or c for a complex value?

Mathematicians are awfully lazy -- laziness is one of the cardinal 
virtues of the mathematician, as it is of programmers -- but they value 
brevity and conciseness over notation that improves readability and 
robustness. That's why they (e.g.) they use implicit multiplication, a 
plethora of "line noise" symbols that would boggle even Perl programmers, 
and two-dimensional syntax where the meaning of tokens depends on where 
they are written relative to some other token. (E.g. subscript, 
superscript, and related forms.)

There is one slightly mainstream language that uses mathematical 
notation: APL. The result isn't pretty. 



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


Re: Creating a PYD file

2010-08-19 Thread Thomas Jollans
On Thursday 19 August 2010, it occurred to Rony to exclaim:
> Is a PYD file created from Pyrex faster in execution then a PYD file
> created from python source ?

How do you plan to create an extension module (*.so, *.pyd on Windows) from 
Python source then?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 11:39:05 -0700, Russ P. wrote:

> I just checked, and Mathematica uses one-based indexing. Apparently they
> want their notation to look mathematical.

Well duh. It's called MATHematica, not PROGematica.


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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 6:58 μμ, ο/η Tim Chase έγραψε:
It can be written as a non-3-quote string, you just have to escape the 
inner quotes (single & double) and the backslash to be seen:


  name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece'
  name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece"



So if i enclose the string in double quotes the inner double quotes have 
to be escaped while
if i enclose the string in single quotes the inner single quotes have to 
be escaped.


But in 3-single-quoting thing became easier since i don't have to escape 
all kind of quotes right? just the backslashes.



And i dont have to use the 'r' in fornt of it too.


Using the 'r' in front would make it much more challenging, because it 
would prevent the backslashes from being seen as escaping. :)


So the best way to write the above assignment statement would be:

name = r'''My name is "Nikos" and I'm from Thessaloniki\Greece'''

It cannot get any easier that that can it? :)

''' ''' helps avoid escaping all kind of quotes!
'r' avoid escaping backslashes!

=
Why does the page variable which is actually a string needs to be a 
tuple or a list and not just as a string which is what it actually is?

I have a strong desire to use it like this:

cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page )

opposed to tuple. Would i might facing a problem? Of what? MySQLdb 
instead of give the whole value to the placeholder to give just a single 
char?
Also do i need 3-single-quoting here as well or it can be written qith 
signle/double quotes?

What appleis to  strings apply to mysql queries as well?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Contains/equals

2010-08-19 Thread Tim Chase

On 08/19/10 12:42, Steven D'Aprano wrote:

On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote:


  def __eq__(self, obj):
   if self.a==obj.a and self.b==obj.b: return True
   return False


That would be the same as:

def __eq__(self, obj):
  return self.a==obj.a and self.b==obj.b


Or, if you have lots of attributes and 2.5+

  def __eq__(self, other):
return all(
  getattr(self, attr) == getattr(other, attr)
  for attr in ['a', 'b', 'c', ...]
  )

or even something like

  def __eq__(self, other):
return all(
  getattr(self, attr) == getattr(other, attr)
  for attr in dir(self)
  if not attr.startswith("__") and not attr.endswith("__")
  )



-tkc



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


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread Tim Golden

On 19/08/2010 4:55 PM, vsoler wrote:

I need to read, for each of the directories in a shared file server
unit, who has access to the directories and what type of access
privileges.

This is something that I can easily do interactively in my Windows
Document Explorer by right clicking a single directory, clicking on
Properties, then on Security.

There I can see the Users and Group of Users that have access to the
selected directory, as well as the type of access to that directory
(Read/Write/eXecute etc.)


Here you have one of those occasions when the Windows GUI does
a very good job of presenting a simplified but perfectly usable
interface layer on top of a moderately complex security scheme.

It's not as easy as you think.


I've been looking in the "os" library, and found the "os.chmod" method
but I am not sure that it is going to give me what I need. Should I
also used library "stat"?


No. Both of these are basically doing a best-endeavours job of mapping
certain Windows attributes to some Posix equivalent. They're essentially
useless for anything beyond the most trivial tasks.

Have a read here which will at least put you on the path of knowing
what terminology you need to search for:

  http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html
  http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html

and if you're interested, this is the kind of thing my winsys
package is reasonably good at:

  http://timgolden.me.uk/python/winsys/security.html#module-security

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


Re: Python "why" questions

2010-08-19 Thread Russ P.
On Aug 19, 11:42 am, Steven D'Aprano  wrote:
> On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote:
> > For those who insist that zero-based indexing is a good idea, why you
> > suppose mathematical vector/matrix notation has never used that
> > convention? I have studied and used linear algebra extensively, and I
> > have yet to see a single case of vector or matrix notation with zero-
> > based indexing in a textbook or a technical paper. Also, mathematical
> > summation is traditionally shown as "1 to N", not "0 to N-1".
>
> In my experience, it's more likely to be "0 to N" than either of the
> above, thus combining the worst of both notations.
>
> > Are
> > mathematicians just too simple-minded and unsophisticated to understand
> > the value of zero-based indexing?
>
> No, mathematicians are addicted to tradition.

That is probably true. But computer languages are addicted to more
than tradition. They're addicted to compatibility and familiarity. I
don't know where zero-based indexing started, but I know that C used
it very early, probably for some minuscule performance advantage. When
C++ came along, it tried to be somewhat compatible with C, so it
continued using zero-based indexing. Then Java was loosely modeled
after C++, so the convention continued. Python was written in C, so
zero-based indexing was "natural." So the whole thing is based on a
decision by some guy who was writing a language for operating systems,
not mathematics or application programming.

> Unlike computer scientists, who create new languages with radically
> different notation and syntax at the drop of a hat, mathematicians almost
> never change existing notation. Sometimes they *add* new notation, but
> more often they just re-use old notation in a new context. E.g. if you
> see (5, 8), does that mean a coordinate pair, a two-tuple, an open
> interval, or something else?
>
> Additionally, mathematical notation isn't chosen for its ability to
> encourage or discourage errors. It seems often to be chosen arbitrarily,
> or for convenience, but mostly out of tradition and convention. Why do we
> use "x" for "unknown"? Why do we use i for an integer value, but not r
> for a real or c for a complex value?
>
> Mathematicians are awfully lazy -- laziness is one of the cardinal
> virtues of the mathematician, as it is of programmers -- but they value
> brevity and conciseness over notation that improves readability and
> robustness. That's why they (e.g.) they use implicit multiplication, a
> plethora of "line noise" symbols that would boggle even Perl programmers,
> and two-dimensional syntax where the meaning of tokens depends on where
> they are written relative to some other token. (E.g. subscript,
> superscript, and related forms.)
>
> There is one slightly mainstream language that uses mathematical
> notation: APL. The result isn't pretty.

As I wrote above, the use of zero-based indexing in C++, Java, and
Python are all simply based on the fact that C used it.

I wouldn't have guessed that APL is a "mainstream" language. As I
wrote in recent posts, Fortran, Matlab, and Mathematica all used one-
based indexing. Maybe Basic too, but I haven't checked.

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


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 11:27:18 -0700, Russ P. wrote:

[...]
>> Zero-based counting doesn't entirely eliminate off-by-one errors, but
>> the combination of that plus half-open on the right intervals reduces
>> them as much as possible.
>>
>> The intuitive one-based closed interval notation used in many natural
>> languages is terrible for encouraging off-by-one errors. Quick: how
>> many days are there between Friday 20th September and Friday 27th
>> September inclusive? If you said seven, you fail.
> 
> The error mode you refer to is much less common than the typical off-
> by-one error mode. In the far more common error mode, zero-based
> indexing is far more error prone.

So you say, and yet you don't give any examples of this "far more common" 
error mode.


>> One-based counting is the product of human intuition. Zero-based
>> counting is the product of human reason.
> 
> I suggest you take that up with mathematicians, who have used one- based
> indexing all along. That's why it was used in Fortran and Matlab, among
> other more mathematical and numerically oriented and languages.

Mathematics is an ancient art that values tradition and convention. It 
doesn't matter how hard it was to come up with a proof, or how difficult 
to verify it. Mathematicians value logical correctness and some 
undefinable sense of elegance over how easy it is to verify, the 
readability of the notation, resistance to errors, and the ability of 
mediocre mathematicians to make useful contributions. Mathematical 
notation and conventions are not, by any stretch of the imagination, 
designed to reduce errors. Mathematicians consider it a good thing that 
they are still mostly using the same notation invented by (say) Leibniz.

Programming language design is a young art that values reliability and 
ease of use over tradition. While correctness of the code is important, 
equally important (if not more so) is readability, resistance to errors, 
and the ability of mediocre programmers to write code that works. Or at 
least code that can be hammered into working by slightly less mediocre 
programmers. Maintenance of code is usually more difficult than writing 
it in the first place, and consequently languages often are designed 
specifically to reduce errors rather than to use the exact same notation 
than Grace Hopper or Charles Babbage used.

While businesses are conservative in which languages they choose, 
language designers are not conservative in the design features they come 
up with. That there has been a gradual (although as yet incomplete) 
convergence towards zero-based indexing in languages aimed at 
programmers, and one-based indexing in languages aimed at non-
programmers, tells you everything you need to know.


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


Re: Python "why" questions

2010-08-19 Thread Russ P.
Yes, apparently Basic uses one-based indexing too.

As for Ada, apparently, the programmer needs to explicitly define the
index range for every array. Weird. But I get the impression that one-
based indexing is used much more than zero-based indexing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python "why" questions

2010-08-19 Thread AK

On 08/19/2010 02:04 PM, Steven D'Aprano wrote:

On Tue, 17 Aug 2010 19:15:54 -0700, Russ P. wrote:


The convention of starting with zero may have had some slight
performance advantage in the early days of computing, but the huge
potential for error that it introduced made it a poor choice in the long
run, at least for high-level languages.


People keep saying this, but it's actually the opposite. Signpost errors
and off-by-one errors are more common in languages that count from one.

A simple example: Using zero-based indexing, suppose you want to indent
the string "spam" so it starts at column 4. How many spaces to you
prepend?

0123456789
 spam


Doesn't it start at column 5 as shown?

Anyway, it's far more common, I think, to iterate over a sequence and
say "my list is 12 items long. I need to check if I'm on 12th item and
do something special. Doh, I mean, 11th item." In my view, this is far,
far more common, especially for people new to programming, and isn't one
of Python mottos "programming for everybody"? In other words, starting
with 0 leads to implicit error every time you simply pause and think
"at which item am I now and how many items have I got so far?" which are
the two most basic questions involved in iteration.

I'm not saying that 1-th indexing is necessarily better in programming
than 0-th indexing, all things considered. It's an arguable question, it
depends on what kind of operations are more common, and I can't know
this for everyone.

I am saying that it is much more natural for people new to programming
and outside of programming to count from 1, and I imagine the reason for
this is simply that it's most useful in vast majority of real usage
people deal with.

It's just annoying that people bring up, for example, ground floor/
first floor as proof that both are equally natural. (I don't mean you, I
know you said you agree that 1-th indexing is more intuitive). -ak
--
http://mail.python.org/mailman/listinfo/python-list


Re: Contains/equals

2010-08-19 Thread Christian Heimes
Am 19.08.2010 20:53, schrieb Tim Chase:
> On 08/19/10 12:42, Steven D'Aprano wrote:
>> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote:
>>
>>>   def __eq__(self, obj):
>>>if self.a==obj.a and self.b==obj.b: return True
>>>return False
>>
>> That would be the same as:
>>
>> def __eq__(self, obj):
>>   return self.a==obj.a and self.b==obj.b
> 
> Or, if you have lots of attributes and 2.5+
> 
>def __eq__(self, other):
>  return all(
>getattr(self, attr) == getattr(other, attr)
>for attr in ['a', 'b', 'c', ...]
>)
> 
> or even something like
> 
>def __eq__(self, other):
>  return all(
>getattr(self, attr) == getattr(other, attr)
>for attr in dir(self)
>if not attr.startswith("__") and not attr.endswith("__")
>)
> 

or simpler if you don't take slots and class attributes into account.

def __eq__(self, other):
return self.__dict__ == other.__dict__

Christian

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


Re: Python "why" questions

2010-08-19 Thread Russ P.
On Aug 19, 12:13 pm, Steven D'Aprano  While businesses are conservative in which languages they choose,
> language designers are not conservative in the design features they come
> up with. That there has been a gradual (although as yet incomplete)
> convergence towards zero-based indexing in languages aimed at
> programmers, and one-based indexing in languages aimed at non-
> programmers, tells you everything you need to know.

I beg to differ. I remember reading Bjarne Stroustrup's rationale for
adopting all sorts of junk from C that he really didn't want, just to
make C++ reasonably compatible with it. Had he not done that, C++
probably would have died on the vine. I'm sure the same was true of
Java and Python too.

In any case, I need to drop this discussion and move on. Mr. D'Aprano,
I usually find your posts enlightening and amusing,  but in this case
just don't seem to be converging.

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


Re: Python "why" questions

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote:

> I don't
> know where zero-based indexing started, but I know that C used it very
> early, probably for some minuscule performance advantage.

In C, zero based indexing was used because it made pointer arithmetic 
elegant and reduced bugs.


> When C++ came
> along, it tried to be somewhat compatible with C, so it continued using
> zero-based indexing.

And because a feature that isn't broken doesn't need to be "fixed".

> Then Java was loosely modeled after C++, so the
> convention continued. Python was written in C, so zero-based indexing
> was "natural." So the whole thing is based on a decision by some guy who
> was writing a language for operating systems, not mathematics or
> application programming.

Python is vastly different from C. It has just as many similarities to 
Pascal as C, which uses 1-based indexing. No surprise there -- Python, 
like both Pascal and C, is a member of the Algol family of languages.

It is interesting to see that Nicholas Wirth's first language, Pascal, 
used one-based indexing, and his latest, Oberon, uses zero-based. Say 
what you like about Wirth, but he's not influenced by the desire to be 
like C. Oberon uses the same zero-based half-open on the right indexing 
as Python:

VAR a: ARRAY 10 OF INTEGER;

creates an array a[0]...a[9].

If Wirth has moved to the Python convention, it is because it *works*, 
not because he's trying to ape C.

Not all languages are based on Algol. Languages derived from Lisp also 
start array indexing at 0. So does Forth. So that's at least three 
significantly different language families which have independently 
converged on zero-based indexing.


[...]
> I wouldn't have guessed that APL is a "mainstream" language. 

I said "slightly". It was surprisingly popular in it's time, and there 
are still multiple APL compilers and interpreters for Windows, Linux and 
Mac.


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


Re: Python "why" questions

2010-08-19 Thread MRAB

Russ P. wrote:

On Aug 19, 11:42 am, Steven D'Aprano  wrote:

On Thu, 19 Aug 2010 11:03:53 -0700, Russ P. wrote:

For those who insist that zero-based indexing is a good idea, why you
suppose mathematical vector/matrix notation has never used that
convention? I have studied and used linear algebra extensively, and I
have yet to see a single case of vector or matrix notation with zero-
based indexing in a textbook or a technical paper. Also, mathematical
summation is traditionally shown as "1 to N", not "0 to N-1".

In my experience, it's more likely to be "0 to N" than either of the
above, thus combining the worst of both notations.


Are
mathematicians just too simple-minded and unsophisticated to understand
the value of zero-based indexing?

No, mathematicians are addicted to tradition.


That is probably true. But computer languages are addicted to more
than tradition. They're addicted to compatibility and familiarity. I
don't know where zero-based indexing started, but I know that C used
it very early, probably for some minuscule performance advantage. When
C++ came along, it tried to be somewhat compatible with C, so it
continued using zero-based indexing. Then Java was loosely modeled
after C++, so the convention continued. Python was written in C, so
zero-based indexing was "natural." So the whole thing is based on a
decision by some guy who was writing a language for operating systems,
not mathematics or application programming.


[snip]
C was derived ultimately from BCPL.

In C array indexing is syntactic sugar for pointer arithmetic with
dereferencing, so:

p[i]

means the same as:

*(p + i)

BCPL, IIRC, didn't use the familiar indexing syntax. !p was the
equivalent of *p and p!i was short for !(p + i), the equivalent of p[i].
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a PYD file

2010-08-19 Thread Rony
Sorry that was a typo...
The question actually is, is a PYD file created from C faster then a
PYD file from Pyrex ?
I know it will depend on how it is written, but let's imagine a tiny
example, like

(Pseudo code)

result = arg1 + arg2
return result



Tia

Rony



On 19 août, 20:47, Thomas Jollans  wrote:
> On Thursday 19 August 2010, it occurred to Rony to exclaim:
>
> > Is a PYD file created from Pyrex faster in execution then a PYD file
> > created from python source ?
>
> How do you plan to create an extension module (*.so, *.pyd on Windows) from
> Python source then?

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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread MRAB

Nik Gr wrote:
[snip]
Why does the page variable which is actually a string needs to be a 
tuple or a list and not just as a string which is what it actually is?

I have a strong desire to use it like this:

cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page )

opposed to tuple. Would i might facing a problem? Of what? MySQLdb 
instead of give the whole value to the placeholder to give just a single 
char?


When there's more than one value you provide a tuple. It's makes sense
from the point of view of consistency that you also provide a tuple when
there's only one value.

Also do i need 3-single-quoting here as well or it can be written qith 
signle/double quotes?

What appleis to  strings apply to mysql queries as well?


It's just a normal string literal.
--
http://mail.python.org/mailman/listinfo/python-list


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Christian Heimes
> Why is 'e' ending up as a string rather than the ImportError object?
> 
> This is with Python 2.6.5 if that makes a difference...

It's a known bug in Python 2.6 and earlier. See
http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7

Due to a bug in Python 2.6, the exc_value parameter to __exit__()
methods was often the string representation of the exception, not an
instance. This was fixed in 2.7, so exc_value will be an instance as
expected. (Fixed by Florent Xicluna; issue 7853.)

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


Wing IDE 3.2.10 released

2010-08-19 Thread Wingware

Hi,

Wingware has released version 3.2.10 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

This release includes the following improvements:

* Several vi mode fixes and other key binding enhancements
* Copy from selected text in Exceptions tool and Testing tool
* Fix Perforce support to run client command in project directory
* Fix debug attach to remote host
* Don't output XML when debugging unit tests
* About 20 other bug fixes (see CHANGELOG.txt for details)

See the change log at http://wingware.com/pub/wingide/3.2.10/CHANGELOG.txt
for details of other recent changes.

*Downloads*

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run.  A free trial license can be obtained directly
from the product.  Wing IDE 101 can be used free of charge.

Wing IDE Pro 3.2.10   http://wingware.com/downloads/wingide/3.2

Wing IDE Personal 3.2.10  http://wingware.com/downloads/wingide-personal/3.2

Wing IDE 101 3.2.10   http://wingware.com/downloads/wingide-101/3.2

*About Wing IDE*

Wing IDE is an integrated development environment designed specifically for
the Python programming language.  It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching entry level programming courses with Python.

Version 3.2 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard 
personalities
* Code intelligence for Python:  Auto-completion, call tips, 
goto-definition,

error indicators, smart indent and re-wrapping, and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,

conditional breakpoints, data value tool tips over code, watch tool, and
externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical

UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and

Perforce
* Integrated unit testing for the unittest, nose, and doctest frameworks
* Many other features including project manager, bookmarks, code snippets,
OS command integration, indentation manager, PyLint integration, and 
perspectives

* Extremely configurable and may be extended with Python scripts

Please refer to the feature list at http://wingware.com/wingide/features for
a detailed listing of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for 
PPC or

Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).
Wing IDE supports Python versions 2.0.x through 3.1.x and Stackless Python.

For more information, see http://wingware.com/products

*Purchasing and Upgrading*

Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Version 2.x
licenses cost 1/2 the normal price to upgrade.

Upgrade a 2.x license: https://wingware.com/store/upgrade

Purchase a 3.x license:https://wingware.com/store/purchase

--

Wingware | Python IDE

The Intelligent Development Environment
for Python Programmers

www.wingware.com

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


Re: Python "why" questions

2010-08-19 Thread MRAB

Russ P. wrote:

Yes, apparently Basic uses one-based indexing too.


For arrays, yes and no. Traditionally, DIM A(10) has 11 elements,
starting at 0, although it might depend on the version of Basic.

For strings, yes.


As for Ada, apparently, the programmer needs to explicitly define the
index range for every array. Weird. But I get the impression that one-
based indexing is used much more than zero-based indexing.


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


tkinter

2010-08-19 Thread Eric J. Van der Velden
Hello,

I have python2.7 .I have compiled tcl en tk and installed them in my
home directory, say /home/eric/tcl and /home/eric/tk .

I have edited
$ vi Modules/Setup
...
_tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \
-L/home/eric/tcl/lib \
-L/home/eric/tk/lib \
-I/home/eric/tcl/include \
-I/home/eric/tcl/include \
-I/usr/include \
-ltcl8.6 -ltk8.6 \
-L/usr/lib \
-lX11

But setup.py does

   self.announce("INFO: Can't locate Tcl/Tk libs and/or
headers", 2)

When I pdb setup.py I see

(Pdb) p inc_dirs
['/home/eric/Unix/Python/Python-2.7-install/include', '.', 'Include',
'./Include', '/usr/local/include', '/home/eric/Unix/Python/Python-2.7-
install/include/python2.7', '/usr/include']
(Pdb) p lib_dirs
['/home/eric/Unix/Python/Python-2.7-install/lib', '/usr/local/lib', '/
lib64', '/usr/lib64', '/lib', '/usr/lib']

So no tcl or tk libraries or header files. Is my Modules/Setup not OK?

Thanks,

Eric J.



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


Re: Python "why" questions

2010-08-19 Thread geremy condra
On Thu, Aug 19, 2010 at 12:32 PM, Steven D'Aprano
 wrote:
> On Thu, 19 Aug 2010 11:57:53 -0700, Russ P. wrote:
>
>> I don't
>> know where zero-based indexing started, but I know that C used it very
>> early, probably for some minuscule performance advantage.
>
> In C, zero based indexing was used because it made pointer arithmetic
> elegant and reduced bugs.

That's because in C, an array 'index' is not an ordinal, but a
distance. Distances are easier to work with if you are comparing
indices and performing arithmetic on them, while ordinals are easier
to work with for straightforward I'd-like-this-element-please. I'm
personally glad that Python uses the former.

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


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread vsoler
On Aug 19, 8:55 pm, Tim Golden  wrote:
> On 19/08/2010 4:55 PM, vsoler wrote:
>
> > I need to read, for each of the directories in a shared file server
> > unit, who has access to the directories and what type of access
> > privileges.
>
> > This is something that I can easily do interactively in my Windows
> > Document Explorer by right clicking a single directory, clicking on
> > Properties, then on Security.
>
> > There I can see the Users and Group of Users that have access to the
> > selected directory, as well as the type of access to that directory
> > (Read/Write/eXecute etc.)
>
> Here you have one of those occasions when the Windows GUI does
> a very good job of presenting a simplified but perfectly usable
> interface layer on top of a moderately complex security scheme.
>
> It's not as easy as you think.
>
> > I've been looking in the "os" library, and found the "os.chmod" method
> > but I am not sure that it is going to give me what I need. Should I
> > also used library "stat"?
>
> No. Both of these are basically doing a best-endeavours job of mapping
> certain Windows attributes to some Posix equivalent. They're essentially
> useless for anything beyond the most trivial tasks.
>
> Have a read here which will at least put you on the path of knowing
> what terminology you need to search for:
>
>    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html
>    http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file
>
> and if you're interested, this is the kind of thing my winsys
> package is reasonably good at:
>
>    http://timgolden.me.uk/python/winsys/security.html#module-security
>
> TJG

Thank you very much, Tim, for your answer.

It looks as though it is going to suit my needs.

Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and
2.6.
File WinSys-0.4.zip should be for the same versions of Python,
probably.
What about your WinSys-0.5beta.win32.exe file? is it for python 3?

I currently have python 3 in my pc. Do I need to install a previous
version of python?

Thank you for your help

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


Re: Django 1.2.1 - stuck with CSRF verification

2010-08-19 Thread Dodo

Le 19/08/2010 20:40, Thomas Jollans a écrit :

On Thursday 19 August 2010, it occurred to Dodo to exclaim:

Hi all,
I followed the tutorial but at page 4 I can't get rid of CSRF errors,
even though I followed everything in this page :
http://docs.djangoproject.com/en/dev/ref/contrib/csrf/



what kind of errors? Any exception tracebacks you can show us maybe?


Well I fill the form, submit via POST
then :


Forbidden (403)

CSRF verification failed. Request aborted.
Help

Reason given for failure:

No CSRF or session cookie.

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


Re: String substitution VS proper mysql escaping

2010-08-19 Thread John Nagle

On 8/18/2010 2:50 AM, Cameron Simpson wrote:

On 18Aug2010 12:07, Nik Gr  wrote:
|  Στις 18/8/2010 7:31 πμ, ο/η Cameron Simpson έγραψε:
|>On 17Aug2010 20:15, Νίκος   wrote:
|>| ===
|>| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page =
|>| '%s' ORDER BY date DESC ''' % (page) )
|>| ===
|>|
|>| Someone told me NOT to do string substitution ("%") on SQL statements
|>| and to let MySQLdb do it
|>| for me, with proper escaping like the following
|>|
|>| ===
|>| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s
|>| ORDER BY date DESC''', (page,))
|>| ===
|>|
|>| The difference is that if some external source can control "page",
|>| and
|>| they put in a value like
|>| 100 ; DELETE FROM visitors; SELECT * FROM visitors
|>| i will be losing my database table data.
|>
|>That other difference is that the mysql dialect support knows how to
|>correctly escape a string for insertion into an SQL statement. You may
|>not, or may forget to pre-escape the string, etc. Using the MySQLdb
|>stuff do it for you is reliable and robust.
|
| Can you please tell me what escaping means by giving me an example
| of what is escaped and whats isn't?

In your plain substitution example above:

   cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page =
   '%s' ORDER BY date DESC ''' % (page) )

Supposing page is the string "100". This will produce the SQL statement:

   SELECT host, hits, date FROM visitors WHERE page = '100' ORDER BY date DESC

which looks ok. But suppose page was the string:

   bill o'reilly

Then your SQL statement looks like this:

   SELECT host, hits, date FROM visitors WHERE page = 'bill o'reilly' ORDER BY 
date DESC

To the SQL engine this looks like the string "bill o" followed by an SQL
instruction named "reilly", and then the opening quote for another string.
Invalid SQL.

The procedure used to avoid this problem (to insert an _arbitrary_
string into the SQL statement) is to "escape" problematic characters in
strings when placing them into SQL statements. In this case, the quote
character in the string is the SQL "end string" character. Therefore the
string must be modified in the SQL statement to be correctly expressed.

IIRC, SQL uses the quote doubling convention for strings, so this:

   SELECT host, hits, date FROM visitors WHERE page = 'bill o''reilly' ORDER BY 
date DESC

is how one would write the literal SQL for that.

The MySQLdb library will do this and a host of other equivalent things
automatically and correctly and consistently when you pass page as a
parameter to the execute() method, needing no special attention or
detailed syntactic knowledge on your part when you write your program.


   Right.  There's much mystery about this, but it's really simple.
All MySQLdb is doing for

cursor.execute(sqlstring, values)

is

quotedstr = sqlstring % map(MySQLdb.escape_string, values)
cursor.execute(quotedstr)

It just applies "MySQLdb.escape_string to each arg.

If PHP did that, we'd have far fewer "SQL injection attacks".

   Most programs shouldn't use "MySQLdb.escape", and should let
the built-in call do it.  It's useful, though, if you're constructing
a data file for LOAD DATA to do a bulk database load.  The
same escaping works for LOAD DATA INFILE with the default
input format.

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


Re: Creating a PYD file

2010-08-19 Thread Terry Reedy

On 8/19/2010 3:41 PM, Rony wrote:


is a PYD file created from C faster then a PYD file from Pyrex ?


Since a .pyd file from Pyrex is also from C, the question is ill-posed.
It is equivalent to "Does the C code generated by Pyrex compile to 
faster or slower machine code than the C code generated by some other 
person or program?". Leaving compiler variations aside, the answer 
depend on the proficiency of the other source in relation to the 
particular function being computed. Perhaps you already answered this...



I know it will depend on how it is written,


depending on what you meant by 'it'. To be fair, the two code have to 
have exactly the same input/output relationships, including exception 
raising.


--
Terry Jan Reedy

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


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread Tim Golden

On 19/08/2010 9:17 PM, vsoler wrote:

On Aug 19, 8:55 pm, Tim Golden  wrote:

On 19/08/2010 4:55 PM, vsoler wrote:


I need to read, for each of the directories in a shared file server
unit, who has access to the directories and what type of access
privileges.



This is something that I can easily do interactively in my Windows
Document Explorer by right clicking a single directory, clicking on
Properties, then on Security.



There I can see the Users and Group of Users that have access to the
selected directory, as well as the type of access to that directory
(Read/Write/eXecute etc.)


Here you have one of those occasions when the Windows GUI does
a very good job of presenting a simplified but perfectly usable
interface layer on top of a moderately complex security scheme.

It's not as easy as you think.


I've been looking in the "os" library, and found the "os.chmod" method
but I am not sure that it is going to give me what I need. Should I
also used library "stat"?


No. Both of these are basically doing a best-endeavours job of mapping
certain Windows attributes to some Posix equivalent. They're essentially
useless for anything beyond the most trivial tasks.

Have a read here which will at least put you on the path of knowing
what terminology you need to search for:

http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html
http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file

and if you're interested, this is the kind of thing my winsys
package is reasonably good at:

http://timgolden.me.uk/python/winsys/security.html#module-security

TJG


Thank you very much, Tim, for your answer.

It looks as though it is going to suit my needs.

Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and
2.6.
File WinSys-0.4.zip should be for the same versions of Python,
probably.
What about your WinSys-0.5beta.win32.exe file? is it for python 3?

I currently have python 3 in my pc. Do I need to install a previous
version of python?

Thank you for your help

Vicente Soler


I have a subversion branch for Python 3. If you have subversion
access, try:

  http://winsys.googlecode.com/svn/branches/py3k

and do the python setup.py install dance.

If you can't get that working, let me know and I'll publish
an installer somewhere.

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


Iterative vs. Recursive coding

2010-08-19 Thread Baba
Level: Beginner

exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf

I am looking at the first problem in the above assignment. The
assignemnt deals, amongst others, with the ideas of iterative vs.
recursive coding approaches and i was wondering what are the
advantages of each and how to best chose between both options?

I had a go at the first part of the exercise and it seems that i can
handle it. However i think my Recursive version can be improved. By
the way, is my code actually proper recursive code?

part 1 iterative approach:

from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0  #fsi=find string index
while fsihttp://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread vsoler
On Aug 19, 10:59 pm, Tim Golden  wrote:
> On 19/08/2010 9:17 PM, vsoler wrote:
>
>
>
> > On Aug 19, 8:55 pm, Tim Golden  wrote:
> >> On 19/08/2010 4:55 PM, vsoler wrote:
>
> >>> I need to read, for each of the directories in a shared file server
> >>> unit, who has access to the directories and what type of access
> >>> privileges.
>
> >>> This is something that I can easily do interactively in my Windows
> >>> Document Explorer by right clicking a single directory, clicking on
> >>> Properties, then on Security.
>
> >>> There I can see the Users and Group of Users that have access to the
> >>> selected directory, as well as the type of access to that directory
> >>> (Read/Write/eXecute etc.)
>
> >> Here you have one of those occasions when the Windows GUI does
> >> a very good job of presenting a simplified but perfectly usable
> >> interface layer on top of a moderately complex security scheme.
>
> >> It's not as easy as you think.
>
> >>> I've been looking in the "os" library, and found the "os.chmod" method
> >>> but I am not sure that it is going to give me what I need. Should I
> >>> also used library "stat"?
>
> >> No. Both of these are basically doing a best-endeavours job of mapping
> >> certain Windows attributes to some Posix equivalent. They're essentially
> >> useless for anything beyond the most trivial tasks.
>
> >> Have a read here which will at least put you on the path of knowing
> >> what terminology you need to search for:
>
> >>    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html
> >>    http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file
>
> >> and if you're interested, this is the kind of thing my winsys
> >> package is reasonably good at:
>
> >>    http://timgolden.me.uk/python/winsys/security.html#module-security
>
> >> TJG
>
> > Thank you very much, Tim, for your answer.
>
> > It looks as though it is going to suit my needs.
>
> > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and
> > 2.6.
> > File WinSys-0.4.zip should be for the same versions of Python,
> > probably.
> > What about your WinSys-0.5beta.win32.exe file? is it for python 3?
>
> > I currently have python 3 in my pc. Do I need to install a previous
> > version of python?
>
> > Thank you for your help
>
> > Vicente Soler
>
> I have a subversion branch for Python 3. If you have subversion
> access, try:
>
>    http://winsys.googlecode.com/svn/branches/py3k
>
> and do the python setup.py install dance.
>
> If you can't get that working, let me know and I'll publish
> an installer somewhere.
>
> TJG

I currently do not have subversion access in my PC. I could try to
install a free copy of it. But it you could ptovide an installer, it
certainly would do things easier. Please let me know if it is
possible.

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


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Chris Withers

Christian Heimes wrote:

Why is 'e' ending up as a string rather than the ImportError object?

This is with Python 2.6.5 if that makes a difference...


It's a known bug in Python 2.6 and earlier. See
http://docs.python.org/whatsnew/2.7.html#porting-to-python-2-7


When was it introduced?

I've been relying on the value being an exception a lot in 2.5, and only 
hit problems in 2.6 with ImportError, everything else seems fine, which 
doesn't agree with Florent's statements in #7853...


Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread Emile van Sebille

On 8/19/2010 2:17 PM vsoler said...

On Aug 19, 10:59 pm, Tim Golden  wrote:



I have a subversion branch for Python 3. If you have subversion
access, try:

http://winsys.googlecode.com/svn/branches/py3k

and do the python setup.py install dance.

If you can't get that working, let me know and I'll publish
an installer somewhere.

TJG


I currently do not have subversion access in my PC. I could try to
install a free copy of it.


I like this one for windows...

http://tortoisesvn.net/downloads

Emile

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


Re: bug? context managers vs ImportErrors

2010-08-19 Thread Benjamin Peterson
Chris Withers  simplistix.co.uk> writes:

> When was it introduced?

It depends on how the exception was raised.




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


Re: Iterative vs. Recursive coding

2010-08-19 Thread Thomas Jollans
On Thursday 19 August 2010, it occurred to Baba to exclaim:
> def countSubStringMatchRecursive(target,key):
> counter=0
> fsi=0 #fsi=find string index
> if len(key)==len(target):   #base case
>   if key==target:
>counter+=1
> elif len(key) while fsi fsi=target.find(key,fsi)
> if fsi!=-1:
>counter+=1
> else:
> break
> fsi=fsi+1
> else:
> print 'key is longer than target...'
> 
> print '%s is %d times in the target string' %(key,counter)
> 
> countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcat
> atgc")

This is not recursive. In fact, it's exactly the same approach as
the first one, plus a bit of an if statement.

Take another good look at the definition of "recursion" I'm sure you were
given.
To sum it up:

"iterate": use a loop. and again. and again. and again. and again. and aga

"recurse": consider. recurse.

This is another good one: 

http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg

 - Thomas

PS: If you think you're thinking, then you're really only thinking that
you're thinking. Or are you?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterative vs. Recursive coding

2010-08-19 Thread MRAB

Baba wrote:

Level: Beginner

exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf

I am looking at the first problem in the above assignment. The
assignemnt deals, amongst others, with the ideas of iterative vs.
recursive coding approaches and i was wondering what are the
advantages of each and how to best chose between both options?

I had a go at the first part of the exercise and it seems that i can
handle it. However i think my Recursive version can be improved. By
the way, is my code actually proper recursive code?

part 1 iterative approach:

from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0  #fsi=find string index
while fsi
'countSubStringMatchRecursive' isn't recursive at all.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterative vs. Recursive coding

2010-08-19 Thread Daniel Kluev
On Fri, Aug 20, 2010 at 8:12 AM, Baba  wrote:

> Level: Beginner
>
> exercise source:
>
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf
>
> I am looking at the first problem in the above assignment. The
> assignemnt deals, amongst others, with the ideas of iterative vs.
> recursive coding approaches and i was wondering what are the
> advantages of each and how to best chose between both options?
>
>
With Python, I'd avoid using recursions unless it is absolutely needed /
much simpler than iteration and depth is known in advance, and not exceeds
the limit.
Reason is that Python does not optimize recursion calls, and even tail
recursions get own stack frame on each call.
It is more expensive than iteration and risks to exceed max recursion depth.


part 2 recursive approach:
>
>
> def countSubStringMatchRecursive(target,key):
>counter=0
>fsi=0 #fsi=find string index
>if len(key)==len(target):   #base case
>  if key==target:
>   counter+=1
>elif len(key)while fsifsi=target.find(key,fsi)
>if fsi!=-1:
>   counter+=1
>else:
>break
>fsi=fsi+1
>else:
>print 'key is longer than target...'
>
>print '%s is %d times in the target string' %(key,counter)
>
>
> countSubStringMatchRecursive("atgacatgcacaagtatgcat","atgacatgcacaagtatgcatatgc")
>

Maybe I'm missing something, but this one seems to be iterative too.
Recursive is one which calls itself, like

def countSubString(haystack, needle):
 def checkMatch(haystack, needle):
  if not needle:
  return True
  elif not haystack:
  return False
  elif haystack[0] == needle[0]:
  return checkMatch(haystack[1:], needle[1:])
  else:
  return False
 return len(filter(bool, map(lambda i: checkMatch(haystack[i:], needle),
range(len(haystack)

Where checkMatch would be called recursively to match needle over particular
part of haystack.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a PYD file

2010-08-19 Thread Martin v. Loewis
> (Pseudo code)
> 
> result = arg1 + arg2
> return result

For this code, the manually-written version will most likely
be faster than the Pyrex-generated one.

This is, most likely, because the manually-written version will
assume a specific data type for the arguments (e.g. int), which
Pyrex will not.

As a consequence, the manually-written version will be more
restricted than the Pyrex one, and most likely, that will be
acceptable in your application.

Theoretically speaking.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterative vs. Recursive coding

2010-08-19 Thread Martin Gregorie
On Thu, 19 Aug 2010 14:12:44 -0700, Baba wrote:

> Level: Beginner
> 
> exercise source:
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-
science/6-00-introduction-to-computer-science-and-programming-fall-2008/
assignments/pset3.pdf
> 
> I am looking at the first problem in the above assignment. The
> assignemnt deals, amongst others, with the ideas of iterative vs.
> recursive coding approaches and i was wondering what are the advantages
> of each and how to best chose between both options?
> 
> I had a go at the first part of the exercise and it seems that i can
> handle it. However i think my Recursive version can be improved. By the
> way, is my code actually proper recursive code?
>
No, it isn't. 

By way of a hint, here are two versions of the classic example of 
recursion: calculating factorials. Recursion can be quite a trick to get 
your mind round at first, so compare the two and follow through their 
operation step by step...

-

def i_factorial(n):
"Iterative factorial calculation"
f = 1;
for n in range(1, n+1):
f = f * n
return f

def r_factorial(n):
"Recursive factorial calculation"
if (n > 1):
return n * r_factorial(n - 1)
else:
return 1

print i_factorial.__doc__
for n in range(1,10):
print "%d! = %d" % (n, i_factorial(n))

print r_factorial.__doc__
for n in range(1,10):
print "%d! = %d" % (n, r_factorial(n))

-

In case you're wondering "print i_factorial.__doc__" 
prints the docstring out of the i_factorial subroutine. 
You probably haven't covered that yet, but run it and see.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread Thomas Jollans
On Thursday 19 August 2010, it occurred to Tim Golden to exclaim:
> On 19/08/2010 4:55 PM, vsoler wrote:
> > I've been looking in the "os" library, and found the "os.chmod" method
> > but I am not sure that it is going to give me what I need. Should I
> > also used library "stat"?
> 
> No. Both of these are basically doing a best-endeavours job of mapping
> certain Windows attributes to some Posix equivalent. They're essentially
> useless for anything beyond the most trivial tasks.

This brings up an interesting, but probably quite complicated question: is it 
reasonable to try to express Windows permissions using full POSIX ACLs (not 
the traditional UNIX mode, the full-featured complex beast that most users 
know nothing about and that many file systems don't enable by default) -- or 
is it, maybe, possible to express the Windows permissions model as a subset of 
POSIX ACL?

I'm no expert either, but the basic idea is that you replace the traditional 
UNIX model with one where not only does every file have an owner and an owning 
group, and r/w/x permission bits for owner, group, and "the rest", but you can 
also specify permissions for arbitrary users and groups, in addition to the 
standard set. I'm leaving out all the details, of course, first and foremost 
those I don't know about myself, but that's essentially it.

Do Windows NT permissions do anything more? Or, apart from the "executable" 
bit, anything less, for that matter?

Just asking. Maybe there are some experts around.

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


Re: Iterative vs. Recursive coding

2010-08-19 Thread Dave Angel


Baba wrote:

Level: Beginner

exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf

I am looking at the first problem in the above assignment. The
assignemnt deals, amongst others, with the ideas of iterative vs.
recursive coding approaches and i was wondering what are the
advantages of each and how to best chose between both options?

I had a go at the first part of the exercise and it seems that i can
handle it. However i think my Recursive version can be improved. By
the way, is my code actually proper recursive code?

part 1 iterative approach:

from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0  #fsi=find string index
while fsi  
A function that doesn't call itself (directly or indirectly) isn't 
recursive.  So you don't have any recursion here.



An example of recursion might be where your function simply compares the 
key to the beginning of the target, then calls itself with a substring 
of the target (  target[1:] )  Don't forget to return 0 if the target is 
smaller than the key.


And take the print out of the recursive function.  Write a separate 
function that does that, after calling the worker function.


DaveA

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


Re: path to data files

2010-08-19 Thread Nobody
On Thu, 19 Aug 2010 14:30:34 +0200, Alain Ketterlin wrote:

>> If a python module requires a data file to run how would I reference
>> this data file in the source in a way that does not depend on whether
>> the module is installed system-wide, installed in $HOME/.local or is
>> just placed in a directory from where the interpreter is fired up?
> 
> sys.path[0] is supposed to contain the script's directory.

One caveat: if you use wxPython, wxversion.select() pushes the directory
containing the selected version at the front of sys.path, so that a
subsequent "import wx" will import the correct version.

It's possible that other functions may do likewise, so if you're
relying upon sys.path[0] to find the script's directory, it's a good idea
to make a copy of sys.path[0] before importing any modules (other than sys).

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


Re: Iterative vs. Recursive coding

2010-08-19 Thread MRAB

Thomas Jollans wrote:
[snip]

"iterate": use a loop. and again. and again. and again. and again. and aga

"recurse": consider. recurse.

This is another good one: 


http://mytechquest.com/blog/wp-content/uploads/2010/05/From-a-Programming-Book.jpg


The definition for recursion looks a lot like that for infinite loop.
Perhaps because it's tail-recursive?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading the access attributes of directories in Windows

2010-08-19 Thread Nobody
On Fri, 20 Aug 2010 00:04:29 +0200, Thomas Jollans wrote:

> This brings up an interesting, but probably quite complicated question: is it 
> reasonable to try to express Windows permissions using full POSIX ACLs

> Do Windows NT permissions do anything more? Or, apart from the
> "executable" bit, anything less, for that matter?

1. There are far more permission types than just "rwx". Specifically:

For files:

Execute File
Read Data
Write Data
Append Data

For folders:

Traverse Folder
List Folder
Create Files
Create Folders
Delete Subfolders and Files

For both:

Full Control
Read Attributes
Read Extended Attributes
Write Attributes
Write Extended Attributes
Delete
Read Permissions
Change Permissions
Take Ownership

Note that files/folders have a distinct "Delete" permission, as well as
the "Delete Subfolders and Files" permission on the parent folder.

Unix lacks the "Append Data" permission for files, and the "Create Files",
"Create Folders" and "Delete Subfolders and Files" correspond to having
write permission on a directory.

On Unix, you can read permissions (and attributes if the filesystem has
them) for any file which you can "reach" (i.e. have "x" permission on all
ancestor directories). You can only change permissions (and some
attributes) if you own the file, and only root can change ownership (and
change some attributes).

2. Permissions can be inherited from the "parent object" (which isn't
necessarily the parent folder). If you change a permission on the parent
object, it automatically affects any file or folder which inherits the
permission.

3. The owner can be either a user or a group.

4. On Windows, a file cannot be "given away" either by its owner or an
administrator. You can grant the "Take Ownership" permission, but
the recipient still has to explicitly change the ownership.

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


  1   2   >