Re: looking for open source python project

2010-08-29 Thread Daniel Fetchinson
> looking for a python project (preferably something a bit small) that
> is looking for contributors. the small bit is because i've never
> worked in a team before and haven't really read source code that's
> 1000s of lines long, so i'm not too sure i can keep up.
>
> my python fu is decent (i think), i recently wrote a small archive/
> grimoire program (command line only) that can store multiline text
> with title, tags, and basic search functionality (not using curses so
> the entry, once entered, can't be modified), entries are stored in a
> pickle file.
>
> anybody have any suggestions? i'm keen to work on something with
> others, both for learning and i'd like to do something a bit
> meaningful, plus i'm sure it's fun.

Have a look at http://wiki.python.org/moin/CodingProjectIdeas

Cheers,
Daniel



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


basketball shoe ( http://www.brandtrade66.com/

2010-08-29 Thread jersey-2009
hox Shoes (http://
www.brandtrade66.com/)
shoes shox shoes (http://
www.brandtrade66.com/)
nike shox shoe (http://
www.brandtrade66.com/)
nike shox shoes ( http://www.brandtrade66.com/
)
shox shoe ( http://www.brandtrade66.com/
)

LV,coach,chanel boots wholesale (
http://www.brandtrade66.com/ )
air force ones (http://
www.brandtrade66.com/)
nike trading ( http://www.brandtrade66.com/
)
nike shox ( http://www.brandtrade66.com/
)
shox air ( http://www.brandtrade66.com/)
white shoe (http://
www.brandtrade66.com/ )
nike shoe ( http://www.brandtrade66.com/
)
nike air shox ( http://www.brandtrade66.com/)
shox r4
tennis shoes (http://
www.brandtrade66.com/ )
tennis shoe ( http://www.brandtrade66.com/)
basketball shoe ( http://www.brandtrade66.com/
)
jordan shoe (http://
www.brandtrade66.com/)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: InteractiveConsole and namespace

2010-08-29 Thread Arnaud Delobelle
Chris Rebert  writes:

> On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT  wrote:
>> Hi all,
>>
>> I want to use an InteractiveConsole at some stage in a program to
>> interact with the local namespace: access, but also modify objects.
>> When the interactive console ends (ctrl-d) I want the program to
>> continue processing with the variables that may have been modified
>> interactively.
>>
[...]
>> However, on the other code below (the console is invoked from within a
>> function block), during the interactive session, I can read value of
>> a, I can change value of a. But the local namespace of the function is
>> not updated:
>>
>> import code
>> def test():
>>    a=1
>>    c = code.InteractiveConsole(locals())
>>    c.interact() # Here I interactively change the value of a (a=2)
>>    print "Value of a: ", a
>>
>> if __name__ == '__main__':
>>    test()
>>
>> print returns --> Value of a: 1
>>
>> I need to run the InteractiveConsole from a function block. I tried
>> different things with the local and parent frames (sys._getframe())
>> but nothing successful. If I put a in the global namespace it works,
>> but I would like to
> [...]
>> understand what the
>> problem is.
>
> Read http://docs.python.org/library/functions.html#locals (emphasis added):
>
> "locals()
> [...]
> Note: The contents of this dictionary should not be modified;
[...]

Here is a solution:

def test():
a=1
loc = dict(locals())
c = code.InteractiveConsole(loc)
c.interact() # Here I interactively change the value of a (a=2)
for key in loc:
if key != '__builtins__':
exec "%s = loc[%r]" % (key, key)
print "Value of a: ", a

HTH

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


PyGeo

2010-08-29 Thread L
has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu 
10.04) ,

the site says

 http://www.wspiegel.de/pymaxima/index_en.html

"Note: The installation of PyGeo work's only under Python 2.4 (The 
further development of pygeo seems to be stopped)"


is this to do with re-org of site-packages, dist_packages etc.

any help most appreciated.

TIA


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


Re: palindrome iteration

2010-08-29 Thread Matteo Landi
Well, I tried the also the solution posted above (recursive w/o
slicing and iterative), and I discovered they were the slowest..

is_palindrome_recursive 2.68151649808
is_palindrome_slice 0.44510699381
is_palindrome_list 1.93861944217
is_palindrome_reversed 3.28969831976
is_palindrome_recursive_no_slicing 6.78929775328
is_palindrome_iterative 4.88826141315

Nothing to say about the iterative function, but the benchmark of the
recursive was unexpected, at least for my point of view: do you think
it is due to the try/except overhead?

On Sun, Aug 29, 2010 at 8:53 AM, Josh English
 wrote:
> This whole conversation got interesting, so I thought I'd run some
> speed tests:
>
> The code:
> from timeit import Timer
>
> def is_palindrome_recursive(s):
>    if len(s) <= 1:
>        return True
>    if s[0] != s[-1]:
>        return False
>    else:
>        return is_palindrome(s[1:-1])
>
> def is_palindrome_slice(s):
>    return s == s[::-1]
>
> def is_palindrome_list(s):
>    l = list(s)
>    l.reverse()
>    return s == ''.join(l)
>
> def is_palindrome_reversed(s):
>    return s == ''.join(reversed(s))
>
> t = Timer("is_palindrome_recursive('madamimadam')", "from __main__
> import is_palindrome_recursive")
> print "is_palindrome_recursive", min(t.repeat())
>
> t = Timer("is_palindrome_slice('madamimadam')", "from __main__ import
> is_palindrome_slice")
> print "is_palindrome_slice", min(t.repeat())
>
> t = Timer("is_palindrome_list('madamimadam')", "from __main__ import
> is_palindrome_list")
> print "is_palindrome_list", min(t.repeat())
>
> t = Timer("is_palindrome_reversed('madamimadam')", "from __main__
> import is_palindrome_reversed")
> print "is_palindrome_reversed", min(t.repeat())
>
> The results:
> is_palindrome_recursive 6.32680866827
> is_palindrome_slice 1.23618350114
> is_palindrome_list 4.60104846653
> is_palindrome_reversed 5.99355296513
>
> The slice method is uglier, I have to admit, but it's the fastest of
> these four on my machine.
>
> Josh
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-29 Thread Gregory Ewing

Steven D'Aprano wrote:

 I'm not entirely sure what the use-case for swapcase is.


Obviously it's for correcting things that were typed
in with tHE cAPS lOCK kEY oN bY mISTAKE. :-)

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


Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails.

2010-08-29 Thread Osmo Maatta
Hello,

Sub class test fails.
==
I have a program that needs to load plugin-classes during runtime.

The program has these subdirectories (modules).

$ tree
.
`-- test.py
|   
|-- plugins
|   |-- base_plugin.py
|   |-- base_plugin.pyc
|   |-- __init__.py
|   `-- oca
|   |-- __init__.py
|   |-- open_clipart.py


The plugins (sub directory) contains one or more plugin modules, in this
test-case there is only one; oca/open_clipart.py.

The plugins/base_plugin.py (contains class Plugin()) is a base class of
all plugins.

I want to list and load all plugin-classes (that inherit from
base_plugin.Plugin). I have a Python code that successfully browses the
plugins, but the the test issubclass(x, base_plugin.Plugin) fails.

Please see this Python code:
http://futuredesktop.com/tmp/test6.tar.gz

Why the issubclass(entry, cls) test fails?

if issubclass(entry, cls):
print "Found a subclass: " + key
subclasses.append(entry)

I can see that the class names are right, even objects of these classes
are ok.

My OS is Ubuntu 10.04.
$ python --version
Python 2.6.5

The actual, final product will be this
http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv
It is a ClipArt query-engine and browser.
It can translate queries from "any" language to english ;-)

Most kindly
  Osmo Antero Maatta
  Grønland, Oslo



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


Re: Queue cleanup

2010-08-29 Thread Hans Mulder

Steven D'Aprano wrote:

On Sat, 28 Aug 2010 00:33:10 -0700, Paul Rubin wrote:



If you drop the last reference
to a complex structure, it could take quite a long time to free all the
components.  By contrast there are provably real-time tracing gc
schemes, including some parallelizeable ones.


I could be wrong, but how can they not be subject to the same performance 
issue? If you have twenty thousand components that all have to be freed, 
they all have to be freed whether you do it when the last reference is 
cleared, or six seconds later when the gc does a sweep.


Parallelizable garbage collectors have performance issues, but they're
not the same issues as mark&sweep collectors have.  Parallelizable GCs
break up their work in a zillion little pieces and allow the VM to do
some real work after each piece.  They won't free your twenty thousand
components all in one go and you won't have that embarrassing pause.

Parallelizable garbage collectors require some careful coordination
between the GC and the VM.  This takes CPU time, so on the whole they're
slower than traditional garbage collectors.  So instead of unpredictable
embarrassing pauses, you have a VM that's consistently slow.
For some applications consistency is more important than raw speed and
for these applications parallelizeable GCs are an improvement.

HTH,

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


Re: palindrome iteration

2010-08-29 Thread Arnaud Delobelle
Matteo Landi  writes:

> Well, I tried the also the solution posted above (recursive w/o
> slicing and iterative), and I discovered they were the slowest..
>
> is_palindrome_recursive 2.68151649808
> is_palindrome_slice 0.44510699381
> is_palindrome_list 1.93861944217
> is_palindrome_reversed 3.28969831976
> is_palindrome_recursive_no_slicing 6.78929775328
> is_palindrome_iterative 4.88826141315

What are the last two functions?

I suggest another:

def is_palindrome(s):
return all(map(str.__eq__, s, reversed(s)))

:)

> Nothing to say about the iterative function, but the benchmark of the
> recursive was unexpected, at least for my point of view: do you think
> it is due to the try/except overhead?
>
> On Sun, Aug 29, 2010 at 8:53 AM, Josh English
>  wrote:
>> This whole conversation got interesting, so I thought I'd run some
>> speed tests:
>>
>> The code:
>> from timeit import Timer
>>
>> def is_palindrome_recursive(s):
>>    if len(s) <= 1:
>>        return True
>>    if s[0] != s[-1]:
>>        return False
>>    else:
>>        return is_palindrome(s[1:-1])

This should be return is_palindrome_recursive(s[1:-1]).  If this is
copy-pasted, then you may call a different is_palindrome function and
invalidate the timings!

[...]

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


Re: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails.

2010-08-29 Thread Arnaud Delobelle
Osmo Maatta  writes:

> Hello,
>
> Sub class test fails.
> ==
> I have a program that needs to load plugin-classes during runtime.
>
> The program has these subdirectories (modules).
>
> $ tree
> .
> `-- test.py
> | 
> |-- plugins
> |   |-- base_plugin.py
> |   |-- base_plugin.pyc
> |   |-- __init__.py
> |   `-- oca
> |   |-- __init__.py
> |   |-- open_clipart.py
>
>
> The plugins (sub directory) contains one or more plugin modules, in this
> test-case there is only one; oca/open_clipart.py.
>
> The plugins/base_plugin.py (contains class Plugin()) is a base class of
> all plugins.
>
> I want to list and load all plugin-classes (that inherit from
> base_plugin.Plugin). I have a Python code that successfully browses the
> plugins, but the the test issubclass(x, base_plugin.Plugin) fails.
>
> Please see this Python code:
> http://futuredesktop.com/tmp/test6.tar.gz
>
> Why the issubclass(entry, cls) test fails?
>
> if issubclass(entry, cls):
> print "Found a subclass: " + key
> subclasses.append(entry)
>
> I can see that the class names are right, even objects of these classes
> are ok.
>
> My OS is Ubuntu 10.04.
> $ python --version
> Python 2.6.5
>
> The actual, final product will be this
> http://www.futuredesktop.com/clipart-applet/clipart-applet.ogv
> It is a ClipArt query-engine and browser.
> It can translate queries from "any" language to english ;-)
>
> Most kindly
>   Osmo Antero Maatta
>   Grønland, Oslo

Hi,

I haven't looked closely at your problem, but are you aware of the
__subclasses__ class method?  E.g.

>>> class A(object): pass
... 
>>> class B(A): pass
... 
>>> class C(A): pass
... 
>>> A.__subclasses__()
[, ]
>>> 

This might help you.

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


Re: palindrome iteration

2010-08-29 Thread Matteo Landi
I thought they reached you. Here they are again:

def palindrome(str, i=0, j=-1):
   try:
   if str[i] == str[j]:
   return palindrome(str, i + 1, j - 1)
   return False
   except IndexError:
   return True

def palindrome(str, i=0, j=-1):
   try:
   while True:
   if str[i] != str[j]:
   return False
   i, j = i + 1, j - 1
   return True
   except IndexError:
   return True

On Sun, Aug 29, 2010 at 12:36 PM, Arnaud Delobelle
 wrote:
> Matteo Landi  writes:
>
>> Well, I tried the also the solution posted above (recursive w/o
>> slicing and iterative), and I discovered they were the slowest..
>>
>> is_palindrome_recursive 2.68151649808
>> is_palindrome_slice 0.44510699381
>> is_palindrome_list 1.93861944217
>> is_palindrome_reversed 3.28969831976
>> is_palindrome_recursive_no_slicing 6.78929775328
>> is_palindrome_iterative 4.88826141315
>
> What are the last two functions?
>
> I suggest another:
>
> def is_palindrome(s):
>    return all(map(str.__eq__, s, reversed(s)))
>
> :)
>
>> Nothing to say about the iterative function, but the benchmark of the
>> recursive was unexpected, at least for my point of view: do you think
>> it is due to the try/except overhead?
>>
>> On Sun, Aug 29, 2010 at 8:53 AM, Josh English
>>  wrote:
>>> This whole conversation got interesting, so I thought I'd run some
>>> speed tests:
>>>
>>> The code:
>>> from timeit import Timer
>>>
>>> def is_palindrome_recursive(s):
>>>    if len(s) <= 1:
>>>        return True
>>>    if s[0] != s[-1]:
>>>        return False
>>>    else:
>>>        return is_palindrome(s[1:-1])
>
> This should be return is_palindrome_recursive(s[1:-1]).  If this is
> copy-pasted, then you may call a different is_palindrome function and
> invalidate the timings!
>
> [...]
>
> --
> Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


setuptools msvc build

2010-08-29 Thread Sazzad Kamal
is it possible to build python setuptools with msvc?

> On Monday, July 12, 2010 4:59 PM Alf P. Steinbach /Usenet wrote:

> I let the setup.py script talk:
> 
> 
> 
> 
> from distutils.core import setup, Extension
> import distutils.ccompiler
> 
> compilerName = distutils.ccompiler.get_default_compiler()
> options = []
> if compilerName == "msvc":
> options.append( "/W4" ) # Must be done in this script.
> options.append( "/EHsc" )   # Could be done via CL env. var.
> options.append( "/GR" ) # Could be done via CL env. var.
> options.append( "/Zc:forScope,wchar_t" )# Could be done via CL env. var.
> 
> module1 = Extension(
> name = "noddy",
> sources = [ "noddy.cpp" ],
> extra_compile_args = options
> )
> 
> setup(
> name= "noddy",
> version = '1.0',
> description = 'This is a demo package',
> ext_modules = [module1]
> )
> 
> 
> 
> Cheers,
> 
> - Alf
> 
> --


> Submitted via EggHeadCafe - Software Developer Portal of Choice 
> Custom Favorites Web Site with MongoDb and NoRM
> http://www.eggheadcafe.com/tutorials/aspnet/7fbc7a01-5d30-4cd3-b373-51d4a0e1afa8/custom-favorites-web-site-with-mongodb-and-norm.aspx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails.

2010-08-29 Thread Peter Otten
Osmo Maatta wrote:

> Hello,
> 
> Sub class test fails.
> ==
> I have a program that needs to load plugin-classes during runtime.
> 
> The program has these subdirectories (modules).
> 
> $ tree
> .
> `-- test.py
> |
> |-- plugins
> |   |-- base_plugin.py
> |   |-- base_plugin.pyc
> |   |-- __init__.py
> |   `-- oca
> |   |-- __init__.py
> |   |-- open_clipart.py
> 
> 
> The plugins (sub directory) contains one or more plugin modules, in this
> test-case there is only one; oca/open_clipart.py.
> 
> The plugins/base_plugin.py (contains class Plugin()) is a base class of
> all plugins.
> 
> I want to list and load all plugin-classes (that inherit from
> base_plugin.Plugin). I have a Python code that successfully browses the
> plugins, but the the test issubclass(x, base_plugin.Plugin) fails.
> 
> Please see this Python code:
> http://futuredesktop.com/tmp/test6.tar.gz
> 
> Why the issubclass(entry, cls) test fails?

base_plugin.py is imported twice, once as plugins.base_plugin and a second 
time as base_plugin. You can see that when you add a bit more debug code 
into your test.py:


--- a/test.py   Sun Aug 29 12:57:25 2010 +0200
+++ b/test.py   Sun Aug 29 12:58:25 2010 +0200
@@ -24,6 +24,8 @@
 #print "entry's class<%s> -- cls's class=<%s>" % 
(obj1.get_name(), obj2.get_name(), )

 print "Check %s against %s" % (entry, cls, )
+print entry.__bases__
+print cls

 if issubclass(entry, cls):
 print "Found a subclass: " + key

$ python test.py
Importing plugins.base_plugin
Importing plugins.oca.open_clipart
Check  against 
(,)

Got subclasses= []

The solution is to remove all sys.path gymnastics and to adapt your import 
statements accordingly:

$ hg diff
diff -r 9fe6129ba8fc plugins/oca/open_clipart.py
--- a/plugins/oca/open_clipart.py   Sun Aug 29 12:51:51 2010 +0200
+++ b/plugins/oca/open_clipart.py   Sun Aug 29 13:02:55 2010 +0200
@@ -2,9 +2,7 @@
 import os
 import threading, thread

-sys.path.insert(0, '..')
-import base_plugin
-#sys.path.insert(0, '../..')
+from .. import base_plugin

 # --
 # class OpenClipArt
diff -r 9fe6129ba8fc test.py
--- a/test.py   Sun Aug 29 12:51:51 2010 +0200
+++ b/test.py   Sun Aug 29 13:02:55 2010 +0200
@@ -1,7 +1,6 @@
 import os, sys
 import inspect

-sys.path.insert(0, "plugins")

 # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins-
made-easy/
 def find_subclasses(path, cls):


$ python test.py
Importing plugins.base_plugin
Importing plugins.oca.open_clipart
Check  against 
Found a subclass: OpenClipArt
Got subclasses= []

You should also remove the __init__.py from the folder containing test.py 
which is just begging for the same problem when you import your plugins as 
test.plugins.whatever.

Peter

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


Re: Fibonacci: How to think recursively

2010-08-29 Thread News123
On 08/29/2010 01:12 AM, Baba wrote:
> Level: beginner
> 
> I would like to know how to approach the following Fibonacci problem:
> How may rabbits do i have after n months?
> 
> I'm not looking for the code as i could Google that very easily. I'm
> looking for a hint to put me on the right track to solve this myself
> without looking it up.
> 
> my brainstorming so far brought me to a stand still as i can't seem to
> imagine a recursive way to code this:
> 
> my attempted rough code:
> 
> def fibonacci(n):
> # base case:
> result = fibonacci (n-1) + fibonacci (n-2)
>>> this will end up in a mess as it will create overlapping recursions
> 
> OR
> 
> def fibonacci(n):
> # base case:
> fibonacci(n+2) - fibonacci(n+1) - n = 0
>>> this too would create overlapping recursions
> 
Hi Baba,

Let's take another example: factorials:
Trivial, but you 'just have to apply the same techniques FIbonacci


n! = 1 * 2 * 3 . . . * n

Very first thing is to always find a trivial case, or the terminal
condition.
Tjis is, when you reduced the problem to the most trivial case(s), for
which you don't need anymore recursion

for factorials this would be
0! = 1
for Fibonacci you might have multiple trivial cases

and the recursive definition of factorial is\
n! = (n - 1) * n

so the code for factorial looks something like:


def factorial(n):
  if n == 0:
  # treat the trivial case / cases for which ou know the answer
  return 1
  else:
  # reduce the problem by the recursive definition
  return factorial(n-1)*n


Hope this helps.





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


Re: Tag parsing in python

2010-08-29 Thread Paul McGuire
On Aug 28, 11:23 pm, Paul McGuire  wrote:
> On Aug 28, 11:14 am, agnibhu  wrote:
>
>
>
>
>
> > Hi all,
>
> > I'm a newbie in python. I'm trying to create a library for parsing
> > certain keywords.
> > For example say I've key words like abc: bcd: cde: like that... So the
> > user may use like
> > abc: How are you bcd: I'm fine cde: ok
>
> > So I've to extract the "How are you" and "I'm fine" and "ok"..and
> > assign them to abc:, bcd: and cde: respectively.. There may be
> > combination of keyowords introduced in future. like abc: xy: How are
> > you
> > So new keywords qualifying the other keywords so on..

I got to thinking more about your keywords-qualifying-keywords
example, and I thought this would be a good way to support locale-
specific tags.  I also thought how one might want to have tags within
tags, to be substituted later, requiring a "abc::" escaped form of
"abc:", so that the tag is substituted with the value of tag "abc:" as
a late binding.

Wasn't too hard to modify what I posted yesterday, and now I rather
like it.

-- Paul


# tag_substitute.py

from pyparsing import (Combine, Word, alphas, FollowedBy, Group,
OneOrMore,
empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal,
And, replaceWith)

tag = Combine(Word(alphas) + ~FollowedBy("::") + ":")
tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag |
LineEnd())("body") + Optional(LineEnd().suppress())


# now combine macro detection with substitution
macros = {}
macro_substitution = Forward()
def make_macro_sub(tokens):
# unescape '::' and substitute any embedded tags
tag_value =
macro_substitution.transformString(tokens.body.replace("::",":"))

# save this tag and value (or overwrite previous)
macros[tuple(tokens.tag)] = tag_value

# define overall macro substitution expression
macro_substitution << MatchFirst(
[(Literal(k[0]) if len(k)==1
else And([Literal(kk) for kk in
k])).setParseAction(replaceWith(v))
for k,v in macros.items()] ) + ~FollowedBy(tag)

# return empty string, so macro definitions don't show up in final
# expanded text
return ""

tag_defn.setParseAction(make_macro_sub)

# define pattern for macro scanning
scan_pattern = macro_substitution | tag_defn


sorry = """\
nm: Dave
sorry: en: I'm sorry, nm::, I'm afraid I can't do that.
sorry: es: Lo siento nm::, me temo que no puedo hacer eso.
Hal said, "sorry: en:"
Hal dijo, "sorry: es:" """
print scan_pattern.transformString(sorry)

Prints:

Hal said, "I'm sorry, Dave, I'm afraid I can't do that."
Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding and loading subclasses dynamically. issubclass(x, base_plugin.Plugin) fails.

2010-08-29 Thread Osmo Maatta
Re-hi and thank you.
That solved my problem.

I can now see that the base_plugin.Plugin is loaded several times.
The numeric id(the_class) is not the same in all places.

Anyway, I thought that a class is always the same if it has been loaded
from the same module (in Linux/Unix; from the same file and inode). So
this experience was a bit confusing.

I need to learn more about how to set the search path (sys.path) right.
More Python!

Thanks
 Osmo Antero
 Grønland, Oslo


On 08/29/2010 01:06 PM, Peter Otten wrote:
> Osmo Maatta wrote:
> 
>> Hello,
>>
>> Sub class test fails.
>> ==
>> I have a program that needs to load plugin-classes during runtime.
>>
>> The program has these subdirectories (modules).
>>
>> $ tree
>> .
>> `-- test.py
>> |
>> |-- plugins
>> |   |-- base_plugin.py
>> |   |-- base_plugin.pyc
>> |   |-- __init__.py
>> |   `-- oca
>> |   |-- __init__.py
>> |   |-- open_clipart.py
>>
>>
>> The plugins (sub directory) contains one or more plugin modules, in this
>> test-case there is only one; oca/open_clipart.py.
>>
>> The plugins/base_plugin.py (contains class Plugin()) is a base class of
>> all plugins.
>>
>> I want to list and load all plugin-classes (that inherit from
>> base_plugin.Plugin). I have a Python code that successfully browses the
>> plugins, but the the test issubclass(x, base_plugin.Plugin) fails.
>>
>> Please see this Python code:
>> http://futuredesktop.com/tmp/test6.tar.gz
>>
>> Why the issubclass(entry, cls) test fails?
> 
> base_plugin.py is imported twice, once as plugins.base_plugin and a second 
> time as base_plugin. You can see that when you add a bit more debug code 
> into your test.py:
> 
> 
> --- a/test.py   Sun Aug 29 12:57:25 2010 +0200
> +++ b/test.py   Sun Aug 29 12:58:25 2010 +0200
> @@ -24,6 +24,8 @@
>  #print "entry's class<%s> -- cls's class=<%s>" % 
> (obj1.get_name(), obj2.get_name(), )
> 
>  print "Check %s against %s" % (entry, cls, )
> +print entry.__bases__
> +print cls
> 
>  if issubclass(entry, cls):
>  print "Found a subclass: " + key
> 
> $ python test.py
> Importing plugins.base_plugin
> Importing plugins.oca.open_clipart
> Check  against  'plugins.base_plugin.Plugin'>
> (,)
> 
> Got subclasses= []
> 
> The solution is to remove all sys.path gymnastics and to adapt your import 
> statements accordingly:
> 
> $ hg diff
> diff -r 9fe6129ba8fc plugins/oca/open_clipart.py
> --- a/plugins/oca/open_clipart.py   Sun Aug 29 12:51:51 2010 +0200
> +++ b/plugins/oca/open_clipart.py   Sun Aug 29 13:02:55 2010 +0200
> @@ -2,9 +2,7 @@
>  import os
>  import threading, thread
> 
> -sys.path.insert(0, '..')
> -import base_plugin
> -#sys.path.insert(0, '../..')
> +from .. import base_plugin
> 
>  # --
>  # class OpenClipArt
> diff -r 9fe6129ba8fc test.py
> --- a/test.py   Sun Aug 29 12:51:51 2010 +0200
> +++ b/test.py   Sun Aug 29 13:02:55 2010 +0200
> @@ -1,7 +1,6 @@
>  import os, sys
>  import inspect
> 
> -sys.path.insert(0, "plugins")
> 
>  # Thanks to http://www.luckydonkey.com/2008/01/02/python-style-plugins-
> made-easy/
>  def find_subclasses(path, cls):
> 
> 
> $ python test.py
> Importing plugins.base_plugin
> Importing plugins.oca.open_clipart
> Check  against  'plugins.base_plugin.Plugin'>
> Found a subclass: OpenClipArt
> Got subclasses= []
> 
> You should also remove the __init__.py from the folder containing test.py 
> which is just begging for the same problem when you import your plugins as 
> test.plugins.whatever.
> 
> Peter
> 

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


controlling the mouse pointer on linux (or as vnc client)

2010-08-29 Thread Gelonida
Hi,

>From a python script I'd like to be able to move the mouse to certain
absolute coordinates on the screen.


There's no problems calling an external program with subprocess.popen,
as I do not want to perform many movements.

The mouse can jump it doesn't have to visibly move to the target coordinate.



What would you suggest to achieve this on Linux Ubuntu 10.4?

Lateron it would be intersting to acheive the same on a Windows PC


One idea, that I had (for a cross platform solution) would be to start a
VNC server on localhost and the current display and run a small custom
VNC client, which will only control the mouse.

However I have no idea how easy it would be to use a custom VNC client
for moving the mouse.


I read about python-vnc-viewer but don't know how complex it would be to
use it as a base for 'just moving the mouse'



Thanks for any suggestions and ideas



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


Re: palindrome iteration

2010-08-29 Thread bruno.desthuilli...@gmail.com
On 27 août, 18:20, Mark Lawrence  wrote:
> On 27/08/2010 15:43, Bruno Desthuilliers wrote:
>
> > Dave Angel a écrit :
> > (snip)
>
> >> or (untested)
> >> def is_palindrom(s):
> >> s = s.lower()
> >> return s == s[::-1]
>
> > Right, go on, make me feel a bit more stupid :-/
> > Who's next ?
>
> It could be worse, try responding to issue 9702. :)

lol ! Nice one, indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci: How to think recursively

2010-08-29 Thread Baba
On Aug 29, 3:25 am, Steven D'Aprano  wrote:

> Mathematically, there is nothing wrong with overlapping recursion. It
> will work, and Python can handle it easily.

Based on the advice by Steven and Mel i tried my initial 'guess' and
it does seem to work fine. When looking at it using pencil and paper i
thought "well, each recursive call will call 2 new ones and if n is
large i will have a huge overlap, so it probably is the wrong
approach". However it turns out to be fine in principle. It can be
handled, as Steven pointed out.


> But in practical terms, it can lead to great inefficiency. In this
> example, it should be avoided because it is slow. Very slow. To calculate
> the nth Fibonacci number using naive recursion requires *many* calls:
>
> You can make it even more efficient by giving fib() a long-term cache, so
> that each call to fib(5) requires one cache lookup rather than six (or
> fifteen) recursive calls. Other than the first time, obviously. This is
> called memoisation, but again I digress.
>

I looked memoisation up and decided that for now  i will not go near
it. First i will try to build up some bacic skills but thank you very
much for the hint. Memoisation will certainly be on the list of future
exercises.

However, the idea that memoisation is needed to make the computation
more efficient confirms my initial  feeling that a 'simple' recursive
approach is somewhat not ideal.


So here's my code. It does still cause me one headache. If i use
f(0)=0
and f(1)=1 as base cases the result will be 144. I was expecting the
result to be the next value in the series (233)...
If i use f(1)=1 and f(2)=2 as base cases them i get my expected
result. I assume this has to do with our understanding/defining the
start of the Fibonacci series?


def r_fib(n):
if n == 1: return 1
elif n == 2: return 2
else: return r_fib(n-2) + r_fib(n-1)

print r_fib(12)


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


Using a function for regular expression substitution

2010-08-29 Thread naugiedoggie
Hello,

I'm having a problem with using a function as the replacement in
re.sub().

Here is the function:

def normalize(s) :
return
urllib.quote(string.capwords(urllib.unquote(s.group('provider'

The purpose of this function is to proper-case the words contained in
a URL query string parameter value.  I'm massaging data in web log
files.

In case it matters, the regex pattern looks like this:

provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)'

The call looks like this:


re.sub(matcher,normalize,line)


Where line is the log line entry.

What I get back is first the entire line with the normalization of the
parameter value, but missing the parameter; then appended to that
string is the entire line again, with the query parameter back in
place pointing to the normalized string.


>>> fileReader = open(log,'r')
>>>
>>> lines = fileReader.readlines()
>>> for line in lines:
if line.find('Search_Type') != -1 and line.find('Search_Provider') !=
-1 :
re.sub(provider_matcher,normalize,line)
print line,'\n'


The output of the print is like this:


'log-entry parameter=value&normalized-string¶meter=value\n
log-entry parameter=value¶meter=normalized-string¶meter=value'


The goal is to massage the specified entries in the log files and
write the entire log back into a new file.  The new file has to be
exactly the same as the old one, with the exception of the entries
I've altered with my function.

No doubt I'm doing something trivially wrong, but I've tried to
reproduce the structure as defined in the documentation.

Thanks.

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


Re: controlling the mouse pointer on linux (or as vnc client)

2010-08-29 Thread John Bokma
Gelonida  writes:

> Hi,
>
>>From a python script I'd like to be able to move the mouse to certain
> absolute coordinates on the screen.
>
>
> There's no problems calling an external program with subprocess.popen,
> as I do not want to perform many movements.

xte?

sudo apt-get install xautomation
xte 'mousemove 200 200'

see: http://linux.die.net/man/1/xte

-- 
John Bokma   j3b

Blog: http://johnbokma.com/Facebook: http://www.facebook.com/j.j.j.bokma
Freelance Perl & Python Development: http://castleamber.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


in place functions from operator module

2010-08-29 Thread ernest
Hi,

The operator module provides separate functions for
"in place" operations, such as iadd(), isub(), etc.
However, it appears that these functions don't really
do the operation in place:

In [34]: a = 4

In [35]: operator.iadd(a, 3)
Out[35]: 7

In [36]: a
Out[36]: 4

So, what's the point? If you have to make the
assignment yourself... I don't understand.

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


Re: in place functions from operator module

2010-08-29 Thread Peter Otten
ernest wrote:

> The operator module provides separate functions for
> "in place" operations, such as iadd(), isub(), etc.
> However, it appears that these functions don't really
> do the operation in place:
> 
> In [34]: a = 4
> 
> In [35]: operator.iadd(a, 3)
> Out[35]: 7
> 
> In [36]: a
> Out[36]: 4
> 
> So, what's the point? If you have to make the
> assignment yourself... I don't understand.

Integers are immutable, and for instances a of immutable types

a += b

is equivalent to

a = a + b

For mutable types like list add() and iadd() may differ:

>>> a = ["first"]
>>> operator.iadd(a, [42])
['first', 42]
>>> a
['first', 42]

>>> a = ["first"]
>>> operator.add(a, [42])
['first', 42]
>>> a
['first']

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


Re: Using a function for regular expression substitution

2010-08-29 Thread Roy Smith
In article 
<9170aad0-478a-4222-b6e2-88d00899d...@t2g2000yqe.googlegroups.com>,
 naugiedoggie  wrote:

> Hello,
> 
> I'm having a problem with using a function as the replacement in
> re.sub().
> 
> Here is the function:
> 
> def normalize(s) :
> return
> urllib.quote(string.capwords(urllib.unquote(s.group('provider'

I read though this entire post, and I'm not quite sure what you're 
asking.  May I suggest that you need to break this down into smaller 
pieces and find a minimal test case.

I'm guessing this is a problem with the regex processing.  To prove 
that, strip away everything else and verify that part in isolation.  
Compile your regex, and match it against a string that you expect it to 
match.  Then, examine the groups returned by the match object.  If 
they're not what you expect, then re-post your question, with just this 
minimal test code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: in place functions from operator module

2010-08-29 Thread ernest
On 29 Ago, 17:00, Peter Otten <__pete...@web.de> wrote:
> ernest wrote:
> > The operator module provides separate functions for
> > "in place" operations, such as iadd(), isub(), etc.
> > However, it appears that these functions don't really
> > do the operation in place:
>
> > In [34]: a = 4
>
> > In [35]: operator.iadd(a, 3)
> > Out[35]: 7
>
> > In [36]: a
> > Out[36]: 4
>
> > So, what's the point? If you have to make the
> > assignment yourself... I don't understand.
>
> Integers are immutable, and for instances a of immutable types
>
> a += b
>
> is equivalent to
>
> a = a + b
>
> For mutable types like list add() and iadd() may differ:
>
> >>> a = ["first"]
> >>> operator.iadd(a, [42])
> ['first', 42]
> >>> a
>
> ['first', 42]
>
> >>> a = ["first"]
> >>> operator.add(a, [42])
> ['first', 42]
> >>> a
>
> ['first']

It makes sense now. Thank you :)

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


Re: in place functions from operator module

2010-08-29 Thread Arnaud Delobelle
ernest  writes:

> Hi,
>
> The operator module provides separate functions for
> "in place" operations, such as iadd(), isub(), etc.
> However, it appears that these functions don't really
> do the operation in place:
>
> In [34]: a = 4
>
> In [35]: operator.iadd(a, 3)
> Out[35]: 7
>
> In [36]: a
> Out[36]: 4
>
> So, what's the point? If you have to make the
> assignment yourself... I don't understand.
>
> Cheers,
> Ernest

That's because

   a += b

is executed as:

   a = a.__iadd__(b)

For immutable objects, (such as integers), a.__iadd__(b) returns a + b
*and then* this value is assigned to a (or rather 'a' is bound to the
value).  So for immutables objects, iadd(a, b) is the same as a + b

For mutable objects (such as lists), a.__iadd__(b) mutates the object
*and then* returns self so that when the assignement is executed, 'a'
will still be bound the the same object.  E.g. if a = [1, 2] then

a += [3]

will first append 3 to the list and then reassign the list to 'a' (it is
unnecessary in this case but if this step was omitted, the "in place"
operators wouldn't work on immutables types).
   
-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: controlling the mouse pointer on linux (or as vnc client)

2010-08-29 Thread Gelonida
Hi John,

> Hi,
> 
>>From a python script I'd like to be able to move the mouse to certain
> absolute coordinates on the screen.
> 
> 
> There's no problems calling an external program with subprocess.popen,
> as I do not want to perform many movements.
> 
> The mouse can jump it doesn't have to visibly move to the target coordinate.
> 
> 
> 
> What would you suggest to achieve this on Linux Ubuntu 10.4?
> 
> Lateron it would be intersting to acheive the same on a Windows PC
> 

On 08/29/2010 04:25 PM, John Bokma wrote:
> sudo apt-get install xautomation
> xte 'mousemove 200 200'
> 

Thanks a lot.

This solution is perfect for Linux.
Exactly what I was looking for. :-)


I guess for Windows it would be a little more complicated?


bye


G




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


Re: Using a function for regular expression substitution

2010-08-29 Thread Terry Reedy

On 8/29/2010 10:22 AM, naugiedoggie wrote:

Hello,

I'm having a problem with using a function as the replacement in
re.sub().

Here is the function:

def normalize(s) :
 return
urllib.quote(string.capwords(urllib.unquote(s.group('provider'


To debug your problem, I would start with print(s) in the function and 
if still not clear, unnest the expression and print intermediate results.


--
Terry Jan Reedy

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


Re: Fibonacci: How to think recursively

2010-08-29 Thread Alain Ketterlin
Baba  writes:

> Level: beginner
>
> I would like to know how to approach the following Fibonacci problem:
> How may rabbits do i have after n months?
>
> I'm not looking for the code as i could Google that very easily. I'm
> looking for a hint to put me on the right track to solve this myself
> without looking it up.

fib(n) = fib(n-1) + fib(n-2), so you need the two previous values to
compute the next one (that's the main difference between fibonacci and
factorial). So here is a hint: instead of computing only fib(n), compute
a pair (fib(n),fib(n-1)). It now becomes a problem very similar to
factorial: for instance, what's (fib(7),fib(6)) if you have the values
of (fib(6),fib(5))? Now write a recursive function fib2(n) that returns
the last two values. And a simple wrapper fib(n) that calls fib2(n) and
returns the first element of the pair.

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


Re: Using a function for regular expression substitution

2010-08-29 Thread MRAB

On 29/08/2010 15:22, naugiedoggie wrote:

Hello,

I'm having a problem with using a function as the replacement in
re.sub().

Here is the function:

def normalize(s) :
 return
urllib.quote(string.capwords(urllib.unquote(s.group('provider'


This normalises the provider and returns only that, and none of the
remainder of the string.

I think you might want this:

def normalize(s):
return s[ : s.start('provider')] + 
urllib.quote(string.capwords(urllib.unquote(s.group('provider' + 
s[s.start('provider') : ]


It returns the part before the provider, followed by the normalised
provider, and then the part after the provider.



The purpose of this function is to proper-case the words contained in
a URL query string parameter value.  I'm massaging data in web log
files.

In case it matters, the regex pattern looks like this:

provider_pattern = r'(?PSearch_Provider)=(?P[^&]+)'

The call looks like this:


re.sub(matcher,normalize,line)


Where line is the log line entry.

What I get back is first the entire line with the normalization of the
parameter value, but missing the parameter; then appended to that
string is the entire line again, with the query parameter back in
place pointing to the normalized string.



fileReader = open(log,'r')

lines = fileReader.readlines()
for line in lines:

if line.find('Search_Type') != -1 and line.find('Search_Provider') !=
-1 :


These can be replaced by:

if 'Search_Type' in line and 'Search_Provider' in line:


re.sub(provider_matcher,normalize,line)


re.sub is returning the result, which you're throwing away!

line = re.sub(provider_matcher,normalize,line)


print line,'\n'


The output of the print is like this:


'log-entry parameter=value&normalized-string¶meter=value\n
log-entry parameter=value¶meter=normalized-string¶meter=value'


The goal is to massage the specified entries in the log files and
write the entire log back into a new file.  The new file has to be
exactly the same as the old one, with the exception of the entries
I've altered with my function.

No doubt I'm doing something trivially wrong, but I've tried to
reproduce the structure as defined in the documentation.


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


Fibonacci: returning a selection of the series

2010-08-29 Thread Baba
level: beginner

i would like to return a selection of the Fibonacci series.
example:
start = 5 ; end  = 55
the function should then return [5, 8, 13, 21, 34, 55]

it seems that this is best resolved using an iterative approach to
generate the series. In another post (http://groups.google.ie/group/
comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/
d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach
which seems best to compute the nth number but it seems to me that the
recursive code is not suited for generating the actual list.

my questios:
- would you agree that recursive is not ideal for generating a list?
(in this particular case and in general)
- can my code below be optimised?
- how to deal with 'start' and 'end' values that are not in the list
e.g. 4,76 ?

def i_fib(n):
a = 0
b = 1
list = []
counter = 0
while counter < n:
a, b = b, a+b
counter += 1
list = list + [b,]
return list

def fib_range(start,end):
list = i_fib(12)
if start in list and end in list:
start = list.index(start)
end = list.index(end)
print list[start:end+1]
else: print 'not in list'

fib_range(5,55)

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


Re: Fibonacci: returning a selection of the series

2010-08-29 Thread Alain Ketterlin
Baba  writes:

> i would like to return a selection of the Fibonacci series.
> example:
> start = 5 ; end  = 55
> the function should then return [5, 8, 13, 21, 34, 55]
[...]
> my questios:
> - would you agree that recursive is not ideal for generating a list?
> (in this particular case and in general)

I would not, in the general case. Well-known problems like fact or fib
have been scrutinized in so much detail that I find it hard to conclude
anything by looking at them. And problems producing lists are usually
"easy" to transform from one version to the other.

However in the general case, to me, the recursive version is usually
much easier to understand, and the iterative version is just an
optimization to save space. There are recursive algorithms that I would
have trouble to write in an iterative way (unless I use an explicit
stack, but that doesn't really count).

We'll stay with the iterative version here, because you've started with
that and you're not far from the solution. But when you're done, try to
think about a recursive version. When the goal is to produce a list, the
recursion scheme is almost immediate: produce one element per call, one
after the other.

> - can my code below be optimised?

Sure. What's this 12 there? Why traversing the list three times (index()
needs to traverse at least some part of it)? And...

> - how to deal with 'start' and 'end' values that are not in the list
> e.g. 4,76 ?

In general, if you have a program that produces something just to
remove/ignore it five lines later, you have a problem. In your case:

1) are you sure you need to append to list(*) at every iteration? When
do you *really* need to? And...

2) your loop runs up to n (the index of the fib number), but you want to
stop on some fib number value (not index).

So, why not pass start and end to i_fib, and use them where appropriate?

-- Alain.

(*) Don't use "list" as a name, because it's a (useful) built-in
function. Use more expressive names: fn instead of b, fn_1 instead of a,
fibnumbers instead of list, etc.

>
> def i_fib(n):
> a = 0
> b = 1
> list = []
> counter = 0
> while counter < n:
> a, b = b, a+b
> counter += 1
> list = list + [b,]
> return list
>
> def fib_range(start,end):
> list = i_fib(12)
> if start in list and end in list:
> start = list.index(start)
> end = list.index(end)
> print list[start:end+1]
> else: print 'not in list'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread MRAB

On 29/08/2010 06:13, Νίκος wrote:

On 28 Αύγ, 23:12, MRAB  wrote:

On 28/08/2010 20:51, Νίκος wrote:










On 28 Αύγ, 22:35, MRABwrote:



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



Can you write something that make use of more than one value?



Perhaps you mena somethign like?



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



Is this what you mean?



All those special format strign identifiers will grab their values out
of the tuple?


Your example contains 3 placeholders, so it needs 3 values:

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

This will be safe. Any quoting that's needed will be done by .execute().


Will this also work without the parentheses?


Have you tried it?

I did. It didn't like it!

It likes the values to be in a tuple. If there's one value, that's a
1-tuple: (page, ).


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


or python will not allow it cause it might think there are 4 args
isntead of two?


Not Python (the language) as such, but the method. As I said, it
expects the value(s) to be in a tuple.



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


Whats happens if i attempt to also quote by single or double quoting
the above although now i'm aware that .execute method does the quoting
for me?


The method will put in any quoting that's needed. If you also put in
quotes then that'll result in 2 sets of quoting, one inside the other
(or something like that).

Why make more work for yourself? Let the method do it for you, safely
and correctly!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci: How to think recursively

2010-08-29 Thread News123
Hi Baba,

> So here's my code. It does still cause me one headache. If i use
> f(0)=0
> and f(1)=1 as base cases the result will be 144. I was expecting the
> result to be the next value in the series (233)...
> If i use f(1)=1 and f(2)=2 as base cases them i get my expected
> result. I assume this has to do with our understanding/defining the
> start of the Fibonacci series?
> 
> 
> def r_fib(n):
> if n == 1: return 1
> elif n == 2: return 2
> else: return r_fib(n-2) + r_fib(n-1)
> 
> print r_fib(12)
> 

Let's calculate the first 12 Fobonacci numbers first manually:

0: 0 # as of its definition
1: 1 @ as of its definition
2: 0 + 1 = 1
3: 1 + 1 = 2
4: 1 + 2 = 3
5: 2 + 3 = 5
6: 3 + 5 = 8
7: 5 + 8 = 13
8: 8 + 13 = 21
9: 13 + 21 = 34
10: 21 + 34 = 55
11: 34 + 55 = 89
12: 55 + 89 = 144

So if you use f(0) = 0 and f(1) = 1 you seem to get the coorec result,
right?


Now the question is why you get the wrong result with your code:

def r_fib(n):
if n == 1: return 1
elif n == 2: return 2
else: return r_fib(n-2) + r_fib(n-1)


The answer is very simple your result n=2 is wrong.
You wrote, that it  is 2, but it should be 1




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


Re: Problem checking an existing browser cookie

2010-08-29 Thread MRAB

On 29/08/2010 06:34, Νίκος wrote:

On 28 Αύγ, 23:15, MRAB  wrote:

On 28/08/2010 20:37, Íßêïò wrote:










On 22 Áýã, 10:27, Íßêïòwrote:

On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>wrote:



Íßêïò wrote:

# initializecookie
cookie=Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie =cookie.get('visitor')



if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
yandex|13448|spider|crawl)', host ) is None:
  blabla...




I checked and Chrome has acookienames visitor with a value ofnikos
within.
So, i have to ask why the if fails?



Maybe it's because != != ==



Iwant ti if code block to be executed only if the browsercookienames
visitor fetched doesnt cotnain the vbalue of 'nikos'



Is there somethign wrong with the way i wrote it?



Please do help me with this too becaus eif i dont solve this my
website keeps count my each visit like iam a guest visitor!


Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
repr(host). Then follow the code yourself to see whether the condition
is True.


print mycookie outputs 'None'

Thts weird because i check with the browser and the cookie is there!


Just because you can see it doesn't mean your code can.


print repr(host) outputs '78-236-176.adsl.cyta.gr'

repr(mycookie.value) (unless mycookie is None)

and also

print mycookie.value gives an error too. Maybe there is not a value
method?


If mycookie is None, then it's not surprising that doesn't have 'value'.

In summary, mycookie is None, so:

mycookie and mycookie.value != 'nikos'

is false (actually None, which is treated as false).

host == '78-236-176.adsl.cyta.gr', so:

re.search(r'(cyta|yandex|13448|spider|crawl)', host)

finds 'cyta' and the search returns a match.

false or false == false

blabla... isn't executed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci: returning a selection of the series

2010-08-29 Thread News123
On 08/29/2010 07:36 PM, Baba wrote:
> level: beginner
> 
> i would like to return a selection of the Fibonacci series.
> example:
> start = 5 ; end  = 55
> the function should then return [5, 8, 13, 21, 34, 55]
> 
> it seems that this is best resolved using an iterative approach to
> generate the series. In another post (http://groups.google.ie/group/
> comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/
> d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach
> which seems best to compute the nth number but it seems to me that the
> recursive code is not suited for generating the actual list.
> 
> my questios:
> - would you agree that recursive is not ideal for generating a list?
Of course, This is probably the whole point of this exercise.

Just because something can be defined recursively doesn't mean, that it
should be
calculated recursively

> - can my code below be optimised?
> - how to deal with 'start' and 'end' values that are not in the list
> e.g. 4,76 ?
> 
> def i_fib(n):
> a = 0
> b = 1
> list = []
> counter = 0
> while counter < n:
> a, b = b, a+b
> counter += 1
> list = list + [b,]
> return list

lateron you should probably use a generator function for i_fib(n)
Then you will only calculate what is needed.

minor suggestion for above code.
Instead of:
list = list + [b,]
it is common practice to write
list.append(b)

> 
> def fib_range(start,end):
> list = i_fib(12)
> if start in list and end in list:
> start = list.index(start)
> end = list.index(end)
> print list[start:end+1]
> else: print 'not in list'
> 
> fib_range(5,55)


you know, that the list returned by i_fib() is sorted.
Knowing this you can look at the python module bisect.
It allows you to identify the index of the closest entry in a list.

Just read it up in the net:
http://docs.python.org/library/bisect.html



You could do this of course also do manually
(perhaps better for learning python than just using exsitng funtions)

Search for the first Fibonacci number which is bigger than your start number
Then search for the first Fibonacci number, which is bigger than your
end number

Display all numbers between these two indices

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


Re: Fibonacci: returning a selection of the series

2010-08-29 Thread geremy condra
On Sun, Aug 29, 2010 at 10:36 AM, Baba  wrote:
> level: beginner
>
> i would like to return a selection of the Fibonacci series.
> example:
> start = 5 ; end  = 55
> the function should then return [5, 8, 13, 21, 34, 55]
>
> it seems that this is best resolved using an iterative approach to
> generate the series. In another post (http://groups.google.ie/group/
> comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/
> d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach
> which seems best to compute the nth number but it seems to me that the
> recursive code is not suited for generating the actual list.
>
> my questios:
> - would you agree that recursive is not ideal for generating a list?
> (in this particular case and in general)
> - can my code below be optimised?
> - how to deal with 'start' and 'end' values that are not in the list
> e.g. 4,76 ?
>
> def i_fib(n):
>    a = 0
>    b = 1
>    list = []
>    counter = 0
>    while counter < n:
>        a, b = b, a+b
>        counter += 1
>        list = list + [b,]
>    return list
>
> def fib_range(start,end):
>    list = i_fib(12)
>    if start in list and end in list:
>        start = list.index(start)
>        end = list.index(end)
>        print list[start:end+1]
>    else: print 'not in list'
>
> fib_range(5,55)
>
> thanks
> Baba

Get the index of the start, use that to generate the second, and
iterate until you hit the end.

from math import sqrt, log, floor

phi = (1 + sqrt(5))/2

def fibonacci_index(n):
return floor(log(n * sqrt(5))/log(phi) + .5)

def ith_fibonacci(i):
return floor(phi**i/sqrt(5) + .5)

def next_fibonacci(a, b):
   return a + b

def fibonacci_between(start, stop):
# find the index of the first
i = fibonacci_index(start)
# find the second value given the first
second_fib = ith_fibonacci(i+1)
# build the list from there
fibs = [start, second_fib]
while fibs[-1] != stop:
fibs.append(next_fibonacci(fibs[-1], fibs[-2]))
# and we're done
return fibs


Now try to understand *why* the above works, rather than just copy-pasting it.

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


Re: PyGeo

2010-08-29 Thread Thomas Jollans
On Sunday 29 August 2010, it occurred to L to exclaim:
> has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu
> 10.04) ,
> the site says
> 
>   http://www.wspiegel.de/pymaxima/index_en.html
> 
> "Note: The installation of PyGeo work's only under Python 2.4 (The
> further development of pygeo seems to be stopped)"
> 
> is this to do with re-org of site-packages, dist_packages etc.
> 
> any help most appreciated.

I don't know. I haven't tried. Maybe somebody else here has, but don't count 
on it. Have you tried it? If not, then why not? Try it. Maybe it just works. 
As far as I know, distutils haven't changed much, carefully avoiding any 
changes that could break packages.

I think it's entirely possible that the web page author claiming "the 
installation" doesn't work was referring only to the Windows installer.

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


Re: palindrome iteration

2010-08-29 Thread bruno.desthuilli...@gmail.com
On 27 août, 20:05, Jussi Piitulainen  > def
palindromep(s):
>     return ( s == "" or
>              ( s[0] == s[-1] and
>                palindromep(s[1:-1]) ) )
>

I-can-write-lisp-in-any-language-p !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-29 Thread bruno.desthuilli...@gmail.com
On 29 août, 06:39, Gregory Ewing  wrote:
> Steven D'Aprano wrote:
> >  I'm not entirely sure what the use-case for swapcase is.
>
> Obviously it's for correcting things that were typed
> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-)
>

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


Performance: sets vs dicts.

2010-08-29 Thread John Nagle

   Is the "in" test faster for a dict or a set?
Is "frozenset" faster than "set"?  Use case is
for things like applying "in" on a list of 500 or so words
while checking a large body of text.

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


Re: Fibonacci: returning a selection of the series

2010-08-29 Thread Arnaud Delobelle
Baba  writes:

> my questios:
> - would you agree that recursive is not ideal for generating a list?
> (in this particular case and in general)

In Python that is probably correct in the vast majority of cases for two
reasons:

* lists in Python are implemented as arrays;
* there is no tail call optimisation in Python.

But not necessarily in other languages.  In Lisp for example, recursion
is *the* natural way of generating lists.

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


Re: Performance: sets vs dicts.

2010-08-29 Thread Arnaud Delobelle
John Nagle  writes:

>Is the "in" test faster for a dict or a set?
> Is "frozenset" faster than "set"?  Use case is
> for things like applying "in" on a list of 500 or so words
> while checking a large body of text.
>
>   John Nagle

IIRC Frozensets are implemented more or less as sets with a hash
function and immutability so I would expect "in" to perform exactly the
same as for sets.  For dicts, I would think that the set implementation
is very close to the dict one.

So I wouldn't expect any significant difference between any of them.

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


Re: Performance: sets vs dicts.

2010-08-29 Thread Peter Otten
John Nagle wrote:

> Is the "in" test faster for a dict or a set?
> Is "frozenset" faster than "set"?  Use case is
> for things like applying "in" on a list of 500 or so words
> while checking a large body of text.

As Arnaud suspects: no significant difference:

$ python dictperf.py
dict --> 0.210289001465
set --> 0.202902793884
frozenset --> 0.198950052261

$ cat dictperf.py
import random
import timeit

with open("/usr/share/dict/words") as instream:
words = [line.strip() for line in instream]

#random.seed(42)
sample = random.sample(words, 501)

n = sample.pop()
y = random.choice(sample)

d = dict.fromkeys(sample)
s = set(sample)
f = frozenset(sample)


for lookup in d, s, f:
print type(lookup).__name__, "-->", timeit.timeit(
"n in lookup; y in lookup",
"from __main__ import lookup, n, y")

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


Re: palindrome iteration

2010-08-29 Thread Roy Smith
In article <8dunm7fv5...@mid.individual.net>,
 Gregory Ewing  wrote:

> Steven D'Aprano wrote:
> >  I'm not entirely sure what the use-case for swapcase is.
> 
> Obviously it's for correcting things that were typed
> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-)

So it would seem (http://bugs.python.org/msg94026).

It's also useful for when you're looking for a crypto algorithm and 
rot13 is too strong.

It also provides a handy way to write is_alpha()...

def is_alpha(c):
return abs(ord(c) - ord(c.swapcase())) == 32

print is_alpha('a')
print is_alpha('A')
print is_alpha('1')
print is_alpha('>')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-29 Thread Josh English
I have no idea. That's a lower level of programming than I'm used to
dealing with.

Josh

(I also only tried the one value. Had I tried with other strings that
would fail the test, some
functions may have performed better.)

On Aug 29, 2:19 am, Matteo Landi  wrote:
> Well, I tried the also the solution posted above (recursive w/o
> slicing and iterative), and I discovered they were the slowest..
>
> is_palindrome_recursive 2.68151649808
> is_palindrome_slice 0.44510699381
> is_palindrome_list 1.93861944217
> is_palindrome_reversed 3.28969831976
> is_palindrome_recursive_no_slicing 6.78929775328
> is_palindrome_iterative 4.88826141315
>
> Nothing to say about the iterative function, but the benchmark of the
> recursive was unexpected, at least for my point of view: do you think
> it is due to the try/except overhead?
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-29 Thread MRAB

On 29/08/2010 21:34, Roy Smith wrote:

In article<8dunm7fv5...@mid.individual.net>,
  Gregory Ewing  wrote:


Steven D'Aprano wrote:

  I'm not entirely sure what the use-case for swapcase is.


Obviously it's for correcting things that were typed
in with tHE cAPS lOCK kEY oN bY mISTAKE. :-)


So it would seem (http://bugs.python.org/msg94026).

It's also useful for when you're looking for a crypto algorithm and
rot13 is too strong.

It also provides a handy way to write is_alpha()...

def is_alpha(c):
 return abs(ord(c) - ord(c.swapcase())) == 32

print is_alpha('a')
print is_alpha('A')
print is_alpha('1')
print is_alpha('>')


How is that better than:

print 'a'.isalpha()
print 'A'.isalpha()
print '1'.isalpha()
print '>'.isalpha()
--
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-29 Thread Roy Smith
In article ,
 MRAB  wrote:

> On 29/08/2010 21:34, Roy Smith wrote:
> > In article<8dunm7fv5...@mid.individual.net>,
> >   Gregory Ewing  wrote:
> >
> >> Steven D'Aprano wrote:
> >>>   I'm not entirely sure what the use-case for swapcase is.
> >>
> >> Obviously it's for correcting things that were typed
> >> in with tHE cAPS lOCK kEY oN bY mISTAKE. :-)
> >
> > So it would seem (http://bugs.python.org/msg94026).
> >
> > It's also useful for when you're looking for a crypto algorithm and
> > rot13 is too strong.
> >
> > It also provides a handy way to write is_alpha()...
> >
> > def is_alpha(c):
> >  return abs(ord(c) - ord(c.swapcase())) == 32
> >
> > print is_alpha('a')
> > print is_alpha('A')
> > print is_alpha('1')
> > print is_alpha('>')
> 
> How is that better than:
> 
> print 'a'.isalpha()
> print 'A'.isalpha()
> print '1'.isalpha()
> print '>'.isalpha()

Think of my post as an implemention of is_reader_humour_impaired().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Functional composition in python

2010-08-29 Thread Audric Schiltknecht

Le 29/08/2010 04:54, Dmitry Groshev a écrit :

On Aug 29, 5:14 am, Steven D'Aprano  wrote:

On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote:

Hello all. Some time ago I wrote a little library:
http://github.com/si14/python-functional-composition/, inspired by
modern functional languages like F#. In my opinion it is quite useful
now, but I would like to discuss it.
An example of usage:

[snip]


Generally, f1>>  f2 means "lambda x: f2(f1(x))" or "pass the result of
f1 to f2". But in python function can return only one value, so a
composable function should be a function of one argument.


You can use a tuple to return more than just one value:

def f(a,b):
return (a,b)

>>> f(1,2)
(1,2)


Ok, technically, it is ONE value, but since you can access any member of 
this tuple :)

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


Re: Fibonacci: How to think recursively

2010-08-29 Thread Baba
Thanks to All for your kind help!

Baba

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


Change case of package name on PyPI

2010-08-29 Thread David Zaslavsky
Hi everyone,

I recently uploaded a package to PyPI under a name with mixed-case letters, 
but in retrospect I think it'd be better to have the package name be all 
lowercase. Is there a way I can change it?

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


Re: Performance: sets vs dicts.

2010-08-29 Thread Seth Rees

On 08/29/10 14:43, Peter Otten wrote:

John Nagle wrote:


 Is the "in" test faster for a dict or a set?
Is "frozenset" faster than "set"?  Use case is
for things like applying "in" on a list of 500 or so words
while checking a large body of text.


As Arnaud suspects: no significant difference:

$ python dictperf.py
dict -->  0.210289001465
set -->  0.202902793884
frozenset -->  0.198950052261

$ cat dictperf.py
import random
import timeit

with open("/usr/share/dict/words") as instream:
 words = [line.strip() for line in instream]

#random.seed(42)
sample = random.sample(words, 501)

n = sample.pop()
y = random.choice(sample)

d = dict.fromkeys(sample)
s = set(sample)
f = frozenset(sample)


for lookup in d, s, f:
 print type(lookup).__name__, "-->", timeit.timeit(
 "n in lookup; y in lookup",
 "from __main__ import lookup, n, y")

Peter

What about lists versus tuples?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Change case of package name on PyPI

2010-08-29 Thread Ben Finney
David Zaslavsky  writes:

> I recently uploaded a package to PyPI under a name with mixed-case
> letters, but in retrospect I think it'd be better to have the package
> name be all lowercase. Is there a way I can change it?

Your question is on-topic here. However, you might get a more focussed
discussion at the forum specific for discussing PyPI, the catalog SIG
http://www.python.org/community/sigs/current/catalog-sig/>. Try
starting the same discussion there.

-- 
 \   “[Freedom of speech] isn't something somebody else gives you. |
  `\  That's something you give to yourself.” —_Hocus Pocus_, Kurt |
_o__) Vonnegut |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


how to find out, whether a path is socket or device

2010-08-29 Thread News123
Hi,

Under Linux I'd like to find out, whether I got a file, a character
device or a socket as a parameter.


What is the right way to do this


How can I found out, whether a path name is:
- a file ( os.isfile() )
- a character device
- a socket
- a named pipe



thanks a lot for pointers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to find out, whether a path is socket or device

2010-08-29 Thread Steven D'Aprano
On Mon, 30 Aug 2010 01:46:16 +0200, News123 wrote:

> Hi,
> 
> Under Linux I'd like to find out, whether I got a file, a character
> device or a socket as a parameter.

See the stat module.



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


Re: Change case of package name on PyPI

2010-08-29 Thread David Zaslavsky
On Sunday 29 August 2010 7:09:37 pm Ben Finney wrote:
> David Zaslavsky  writes:
> > I recently uploaded a package to PyPI under a name with mixed-case
> > letters, but in retrospect I think it'd be better to have the package
> > name be all lowercase. Is there a way I can change it?
> 
> Your question is on-topic here. However, you might get a more focussed
> discussion at the forum specific for discussing PyPI, the catalog SIG
> http://www.python.org/community/sigs/current/catalog-sig/>. Try
> starting the same discussion there.
Thanks, I'll do that.

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


Re: in place functions from operator module

2010-08-29 Thread Steven D'Aprano
On Sun, 29 Aug 2010 07:44:47 -0700, ernest wrote:

> Hi,
> 
> The operator module provides separate functions for "in place"
> operations, such as iadd(), isub(), etc. However, it appears that these
> functions don't really do the operation in place:
> 
> In [34]: a = 4
> 
> In [35]: operator.iadd(a, 3)
> Out[35]: 7
> 
> In [36]: a
> Out[36]: 4
> 
> So, what's the point? If you have to make the assignment yourself... I
> don't understand.


The point is that if you could modify the int 4 to become 7, you would 
then see horrible things like this:


>>> a = 4
>>> operator.iadd(a, 3)
>>> 4 + 1  # the int "4" has been changed to have the value 7
8

Nobody wants that. Some very early versions of Fortran allowed that sort 
of thing, apparently by accident. I've been told you can get it to work 
with Lisp too, and Python with ctypes. You don't want to go there.

That is why ints are immutable in Python, and so "in-place" operations 
aren't really in-place for them.

Remember that 4 is an actual *object*, and so the iadd function can only 
see the object, not the name it is bound to. It sees 4 as the first 
argument, not the memory location of "a". There's no way for it to know 
which name you are trying to modify, or even if the object 4 is bound to 
any name.


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


Re: problem in using linalg solver in numpy

2010-08-29 Thread Aahz
In article <242fd242-5f29-4358-8c12-f5763b7be...@g21g2000prn.googlegroups.com>,
Pramod   wrote:
>
>When run the below  program in python i got error like this ,

You may want to consider asking future questions on the NumPy list:

http://projects.scipy.org/mailman/listinfo/numpy-discussion
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci: How to think recursively

2010-08-29 Thread Steven D'Aprano
On Sun, 29 Aug 2010 06:43:40 -0700, Baba wrote:

> So here's my code. It does still cause me one headache. If i use f(0)=0
> and f(1)=1 as base cases the result will be 144. I was expecting the
> result to be the next value in the series (233)... 

That's because you're not generating the Fibonacci series, but a similar 
unnamed(?) series with the same recurrence but different starting 
conditions. The Fibinacci series starts with f(0)=1, f(1)=1.


> If i use f(1)=1 and
> f(2)=2 as base cases them i get my expected result. 

Which implies that f(0) must be 1, not 0.



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


Re: Fibonacci: returning a selection of the series

2010-08-29 Thread Steven D'Aprano
On Sun, 29 Aug 2010 10:36:45 -0700, Baba wrote:

> level: beginner
> 
> i would like to return a selection of the Fibonacci series. example:
> start = 5 ; end  = 55
> the function should then return [5, 8, 13, 21, 34, 55]

Start with something to lazily generate Fibonacci numbers. It doesn't 
matter whether this is iterative or recursive, but it must be *lazy* -- 
only generating each number when you ask for the next one. Generators are 
ideal for this:

# Untested.
def fib():
"""Generate the Fibonacci numbers."""
a, b = 1, 1
yield a
while 1:
yield b
a, b = b, a+b


Then pass it into a filter than skips numbers less than start, 
accumulates numbers until you exceed end, and stop. Then return the 
numbers that you collected.



> it seems that this is best resolved using an iterative approach to
> generate the series. In another post (http://groups.google.ie/group/
> comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/
> d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach
> which seems best to compute the nth number but it seems to me that the
> recursive code is not suited for generating the actual list.

In this specific case, you can get recursion to be much, much more 
efficient than the naive f(n) = f(n-1) + f(n-2) case, but iteration in 
Python is often more efficient.


> my questios:
> - would you agree that recursive is not ideal for generating a list? (in
> this particular case and in general) 

In this particular case, an iterative approach to Fibonacci will probably 
be more effective.

In general, no, recursion is fine for generating lists.


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


Re: Queue cleanup

2010-08-29 Thread Paul Rubin
Hans Mulder  writes:
> Parallelizable garbage collectors have performance issues, but they're
> not the same issues as mark&sweep collectors have.  Parallelizable GCs
> break up their work in a zillion little pieces and allow the VM to do
> some real work after each piece.  They won't free your twenty thousand
> components all in one go and you won't have that embarrassing pause.

Quibble: parallel GC just means any GC that runs in multiple threads
simultaneously.  A GC that guarantees no pauses (more technically,
specifies a constant such that any GC pause is guaranteed to be shorter
than the constant) is called a "real time" GC, and real-time GC's are
usually single threaded.  Parallel real-time GC's were once sort of a
holy grail, though workable ones have been implemented.  GHC for example
currently uses a GC that is parallel (runs on multiple cores for speed)
but is not real-time (there can be a pause), and I think the Sun JVM is
the same way.

These days I think the GC pause issue is overrated except for real-time
control applications.  GC's no longer frequently make the program freeze
up for seconds at a time or anything like that.  It was worse in the old
days when CPU's were slower and memory was scarcer.  Serious GC's are
usually generational, with "minor" GC's taking microseconds and less
frequent "major" GC's taking fractions of a second.  So in an
interactive program or animation on your desktop you might notice a
little hiccup once in a while.  For something like a web server an
occasional slight variation in response time could easily be random
network delays and so forth.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-29 Thread Paul Rubin
Steven D'Aprano  writes:
> You can add cycle detection to a reference count gc, at the cost of more 
> complexity.

But then it's not purely a refcount gc. ;)

> If you read the Wikipedia article I linked to, tracing algorithms can 
> also be unsound:  [describes "conservative" gc]

Yeah, whether that counts as a real GC is subjective too.

>> and 2) it requires constant attention from the mutator to incr and
>> decr the reference counts.
> Yes. And?

I thought I made it clear, the purpose of gc is to improve programmer
productivity and program reliability by relieving the programmer from
the burden of memory allocation bookkeeping.  If the programmer has to
painstakingly manage refcounts by hand and the resulting programs are
still prone to refcount bugs (both of which are the case with CPython),
it's not really gc in a way that lives up to the name.

> That's a problem with the CPython API, not reference counting. The 
> problem is that the CPython API is written at too low a level, beneath 
> that at which the garbage collector exists, so naturally you have to 
> manually manage memory.

Care to give an example of a reference counted system that's written any
other way?

> On the other hand, tracing gcs have their own set of problems too, mostly 
> due to the use of finalizers and attempts to make garbage collection run 
> more predictably. See here:

I think it's fairly common wisdom that finalizers and gc don't interact
very well.  Finalizers in general aren't in the gc spirit, which says
the system should give the illusion that every object stays around
forever.  As for stuff like hash tables, a usual way to help out the gc
is by populating the hash table with weak references, rather than by
clearing it out manually when you're done with it.  It's also possible
for fancy compilers to use a mixture of gc and stack- or region-based
allocation.

> Tracing garbage collectors aren't a panacea. They're software themselves, 
> and complex software, which means they're subject to bugs like the one ...

You could say the same thing about compilers instead of gc's.  The idea
in both cases is yes, they're complex, but they put the complexity in
one place, so that the application program can rely on the complicated
gc or compiler features while itself staying simple.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-29 Thread Paul Rubin
Steven D'Aprano  writes:
> I could be wrong, but how can they not be subject to the same performance 
> issue? If you have twenty thousand components that all have to be freed, 
> they all have to be freed whether you do it when the last reference is 
> cleared, or six seconds later when the gc does a sweep.

GC's on large machines these days do not sweep at all.  They copy the
live data to a new heap, then release the old heap.  Because there is
usually more garbage than live data, copying GC's that never touch the
garbage are usually faster than any scheme involving freeing unused
objects one by one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Νίκος
On 29 Αύγ, 21:44, MRAB  wrote:
> On 29/08/2010 06:34, Νίκος wrote:
>
>
>
>
>
>
>
> > On 28 Αύγ, 23:15, MRAB  wrote:
> >> On 28/08/2010 20:37, Íßêïò wrote:
>
> >>> On 22 Áýã, 10:27, Íßêïò    wrote:
>  On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>    wrote:
>
> > Íßêïò wrote:
> >> # initializecookie
> >> cookie=Cookie.SimpleCookie()
> >> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> >> mycookie =cookie.get('visitor')
>
> >> if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
> >> yandex|13448|spider|crawl)', host ) is None:
> >>       blabla...
> >> 
>
> >> I checked and Chrome has acookienames visitor with a value ofnikos
> >> within.
> >> So, i have to ask why the if fails?
>
> > Maybe it's because != != ==
>
>  Iwant ti if code block to be executed only if the browsercookienames
>  visitor fetched doesnt cotnain the vbalue of 'nikos'
>
>  Is there somethign wrong with the way i wrote it?
>
> >>> Please do help me with this too becaus eif i dont solve this my
> >>> website keeps count my each visit like iam a guest visitor!
>
> >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
> >> repr(host). Then follow the code yourself to see whether the condition
> >> is True.
>
> > print mycookie outputs 'None'
>
> > Thts weird because i check with the browser and the cookie is there!
>
> Just because you can see it doesn't mean your code can.
>
> > print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> > repr(mycookie.value) (unless mycookie is None)
>
> > and also
>
> > print mycookie.value gives an error too. Maybe there is not a value
> > method?
>
> If mycookie is None, then it's not surprising that doesn't have 'value'.
>
> In summary, mycookie is None, so:
>
>      mycookie and mycookie.value != 'nikos'
>
> is false (actually None, which is treated as false).
>
> host == '78-236-176.adsl.cyta.gr', so:
>
>      re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> finds 'cyta' and the search returns a match.
>
> false or false == false
>
> blabla... isn't executed.

Lets forget the 2nd or argument, ill put it off

so we have this now

if ( mycookie and mycookie.value != 'nikos' ):
#do stuff as long as there ins't a cookie names visitor with a
value of nikos in the broswer

What does it mean practically that the mycookie equals to None?
That mycookie doesnt exist?

How should i write this if block to mkake sure it checks whether or
not the cookie exists?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread Νίκος
On 29 Αύγ, 21:34, MRAB  wrote:

> It likes the values to be in a tuple. If there's one value, that's a
> 1-tuple: (page, ).

I noticed that if we are dealing with just a single value 'page' will
do, no need to tuple for 1-value.
it handles fine as a string.

> >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and
> >> date = %s and host = %s''', page, date, host)
>
> > or python will not allow it cause it might think there are 4 args
> > isntead of two?
>
> Not Python (the language) as such, but the method. As I said, it
> expects the value(s) to be in a tuple.

If i dont parenthesize the execute method instead of getting 2
args(sql_query and tuple value) as it expects by deficition, it gets 4
args instead and thats why it fails? I need to know why ti fails. Is
that it?

Also in here,

page, date, host is 3 separate variable values here

while

(page, date, host) is 3 separate variables values also but withing a
tuple. Is this correct?


> >> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> >> date = '%s' and host = '%s' ''', (page, date, host))
>
> > Whats happens if i attempt to also quote by single or double quoting
> > the above although now i'm aware that .execute method does the quoting
> > for me?
>
> The method will put in any quoting that's needed. If you also put in
> quotes then that'll result in 2 sets of quoting, one inside the other
> (or something like that).
>
> Why make more work for yourself? Let the method do it for you, safely
> and correctly!

I'am askign this because i'm tryong to see why

On 29 Αύγ, 21:34, MRAB  wrote:

> It likes the values to be in a tuple. If there's one value, that's a
> 1-tuple: (page, ).

I noticed that if we are dealing with just a single value 'page' will
do, no need to tuple for 1-value.
it handles fine as a string.

> >> cursor.execute('''SELECT hits FROM counters WHERE page = %s and
> >> date = %s and host = %s''', page, date, host)
>
> > or python will not allow it cause it might think there are 4 args
> > isntead of two?
>
> Not Python (the language) as such, but the method. As I said, it
> expects the value(s) to be in a tuple.

If i dont parenthesize the execute method instead of getting 2
args(sql_query and tuple value) as it expects by deficition, it gets 4
args instead and thats why it fails? I need to know why ti fails. Is
that it?


Also in here,

page, date, host is 3 separate variable values here

while

(page, date, host) is 3 separate variables values also but withing a
tuple. Is this correct?


=
I'm asking this to see why

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

does work, while same thign qithout the quotes

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

doesn't. Dont know why but quotes somehopw confuse me both in strings
and sql_queries as well when it comes to substitutions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread MRAB

On 30/08/2010 02:14, Νίκος wrote:

On 29 Αύγ, 21:44, MRAB  wrote:

On 29/08/2010 06:34, Νίκος wrote:








On 28 Αύγ, 23:15, MRABwrote:

On 28/08/2010 20:37, Íßêïò wrote:



On 22 Áýã, 10:27, Íßêïò  wrote:

On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>  wrote:



Íßêïò wrote:

# initializecookie
cookie=Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie =cookie.get('visitor')



if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
yandex|13448|spider|crawl)', host ) is None:
   blabla...




I checked and Chrome has acookienames visitor with a value ofnikos
within.
So, i have to ask why the if fails?



Maybe it's because != != ==



Iwant ti if code block to be executed only if the browsercookienames
visitor fetched doesnt cotnain the vbalue of 'nikos'



Is there somethign wrong with the way i wrote it?



Please do help me with this too becaus eif i dont solve this my
website keeps count my each visit like iam a guest visitor!



Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
repr(host). Then follow the code yourself to see whether the condition
is True.



print mycookie outputs 'None'



Thts weird because i check with the browser and the cookie is there!


Just because you can see it doesn't mean your code can.


print repr(host) outputs '78-236-176.adsl.cyta.gr'



repr(mycookie.value) (unless mycookie is None)



and also



print mycookie.value gives an error too. Maybe there is not a value
method?


If mycookie is None, then it's not surprising that doesn't have 'value'.

In summary, mycookie is None, so:

  mycookie and mycookie.value != 'nikos'

is false (actually None, which is treated as false).

host == '78-236-176.adsl.cyta.gr', so:

  re.search(r'(cyta|yandex|13448|spider|crawl)', host)

finds 'cyta' and the search returns a match.

false or false == false

blabla... isn't executed.


Lets forget the 2nd or argument, ill put it off

so we have this now

if ( mycookie and mycookie.value != 'nikos' ):
 #do stuff as long as there ins't a cookie names visitor with a
value of nikos in the broswer

What does it mean practically that the mycookie equals to None?
That mycookie doesnt exist?

How should i write this if block to mkake sure it checks whether or
not the cookie exists?


Under what conditions do you want to execute the block?

This:

mycookie and mycookie.value != 'nikos'

will be true if:

there _is_ a cookie, but its value isn't 'nikos'

I think that you want is to execute the block if someone else is
visiting. Correct?

How do you know when it _is_ you? There'll be a cookie which says it's
you?

If so, then you want to execute the block if there isn't any cookie, or
if there's a cookie but it doesn't say it's you:

not mycookie or mycookie.value != 'nikos'
--
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread MRAB

On 30/08/2010 02:38, Νίκος wrote:

On 29 Αύγ, 21:34, MRAB  wrote:


It likes the values to be in a tuple. If there's one value, that's a
1-tuple: (page, ).


I noticed that if we are dealing with just a single value 'page' will
do, no need to tuple for 1-value.
it handles fine as a string.


I tried it with sqlite3, which it didn't like it. For consistency, and
compatibility with other SQL engines, I recommend that you always
provide a tuple.


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



or python will not allow it cause it might think there are 4 args
isntead of two?


Not Python (the language) as such, but the method. As I said, it
expects the value(s) to be in a tuple.


If i dont parenthesize the execute method instead of getting 2
args(sql_query and tuple value) as it expects by deficition, it gets 4
args instead and thats why it fails? I need to know why ti fails. Is
that it?


If the SQL query contains placeholder(s), the .execute method expects
the value(s) to be provided in a tuple. It's as simple as that.


Also in here,

page, date, host is 3 separate variable values here

while

(page, date, host) is 3 separate variables values also but withing a
tuple. Is this correct?


It doesn't care about the variables as such, only their values. You're
putting the values into a tuple and then passing that tuple because
that's what the method wants.



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



Whats happens if i attempt to also quote by single or double quoting
the above although now i'm aware that .execute method does the quoting
for me?


The method will put in any quoting that's needed. If you also put in
quotes then that'll result in 2 sets of quoting, one inside the other
(or something like that).

Why make more work for yourself? Let the method do it for you, safely
and correctly!


I'am askign this because i'm tryong to see why

On 29 Αύγ, 21:34, MRAB  wrote:


It likes the values to be in a tuple. If there's one value, that's a
1-tuple: (page, ).


I noticed that if we are dealing with just a single value 'page' will
do, no need to tuple for 1-value.
it handles fine as a string.


As I've said, for consistency I recommend that you always provide a
tuple because some SQL engines require it, and if you need to provide
multiple values then you'll need to anyway.


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



or python will not allow it cause it might think there are 4 args
isntead of two?


Not Python (the language) as such, but the method. As I said, it
expects the value(s) to be in a tuple.


If i dont parenthesize the execute method instead of getting 2
args(sql_query and tuple value) as it expects by deficition, it gets 4
args instead and thats why it fails? I need to know why ti fails. Is
that it?


Also in here,

page, date, host is 3 separate variable values here

while

(page, date, host) is 3 separate variables values also but withing a
tuple. Is this correct?


=
I'm asking this to see why

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

does work, while same thign qithout the quotes

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

doesn't. Dont know why but quotes somehopw confuse me both in strings
and sql_queries as well when it comes to substitutions.


Don't quote the placeholders yourself. Let the method do it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 04:51, MRAB  wrote:
> On 30/08/2010 02:14, Νίκος wrote:
>
>
>
>
>
>
>
>
>
> > On 29 Αύγ, 21:44, MRAB  wrote:
> >> On 29/08/2010 06:34, Νίκος wrote:
>
> >>> On 28 Αύγ, 23:15, MRAB    wrote:
>  On 28/08/2010 20:37, Íßêïò wrote:
>
> > On 22 Áýã, 10:27, Íßêïò      wrote:
> >> On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>      wrote:
>
> >>> Íßêïò wrote:
>  # initializecookie
>  cookie=Cookie.SimpleCookie()
>  cookie.load( os.environ.get('HTTP_COOKIE', '') )
>  mycookie =cookie.get('visitor')
>
>  if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
>  yandex|13448|spider|crawl)', host ) is None:
>         blabla...
>  
>
>  I checked and Chrome has acookienames visitor with a value ofnikos
>  within.
>  So, i have to ask why the if fails?
>
> >>> Maybe it's because != != ==
>
> >> Iwant ti if code block to be executed only if the browsercookienames
> >> visitor fetched doesnt cotnain the vbalue of 'nikos'
>
> >> Is there somethign wrong with the way i wrote it?
>
> > Please do help me with this too becaus eif i dont solve this my
> > website keeps count my each visit like iam a guest visitor!
>
>  Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
>  repr(host). Then follow the code yourself to see whether the condition
>  is True.
>
> >>> print mycookie outputs 'None'
>
> >>> Thts weird because i check with the browser and the cookie is there!
>
> >> Just because you can see it doesn't mean your code can.
>
> >>> print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> >>> repr(mycookie.value) (unless mycookie is None)
>
> >>> and also
>
> >>> print mycookie.value gives an error too. Maybe there is not a value
> >>> method?
>
> >> If mycookie is None, then it's not surprising that doesn't have 'value'.
>
> >> In summary, mycookie is None, so:
>
> >>       mycookie and mycookie.value != 'nikos'
>
> >> is false (actually None, which is treated as false).
>
> >> host == '78-236-176.adsl.cyta.gr', so:
>
> >>       re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> >> finds 'cyta' and the search returns a match.
>
> >> false or false == false
>
> >> blabla... isn't executed.
>
> > Lets forget the 2nd or argument, ill put it off
>
> > so we have this now
>
> > if ( mycookie and mycookie.value != 'nikos' ):
> >      #do stuff as long as there ins't a cookie names visitor with a
> > value of nikos in the broswer
>
> > What does it mean practically that the mycookie equals to None?
> > That mycookie doesnt exist?
>
> > How should i write this if block to mkake sure it checks whether or
> > not the cookie exists?
>
> Under what conditions do you want to execute the block?
>
> This:
>
>      mycookie and mycookie.value != 'nikos'
>
> will be true if:
>
>      there _is_ a cookie, but its value isn't 'nikos'
>
> I think that you want is to execute the block if someone else is
> visiting. Correct?

Yes that exactyl right!

To make sure a cookie is set i have a script names koukos.py
containing this:

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

import cgitb; cgitb.enable()
import cgi, os, Cookie


# initialize cookie
cookie = Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie = cookie.get('visitor')

htmlBody = []

# if visitor cookie does exist
if ( mycookie and mycookie.value == 'nikos' ):
htmlBody.append('ΑΠΟ ΤΗΝ ΕΠΟΜΕΝΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ
ΕΠΙΣΚΕΠΤΗ ΑΥΞΑΝΟΝΤΑΣ ΤΟΝ ΜΕΤΡΗΤΗ!')
cookie['visitor'] = 'nikos'
cookie['visitor']['expires'] = -1  #this cookie will expire
now
else:
htmlBody.append('ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ
ΣΕ ΑΚΟΥΣΑ! ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!')
cookie['visitor'] = 'nikos'
cookie['visitor']['expires'] = 60*60*24*30*12

htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n')

print(cookie)
print('\n'.join(htmlBody))
=

Which i seicth on and off according to my desire if i want to be
counted or not!

> How do you know when it _is_ you? There'll be a cookie which says it's
> you?
>
> If so, then you want to execute the block if there isn't any cookie, or
> if there's a cookie but it doesn't say it's you:
>
>      not mycookie or mycookie.value != 'nikos'

i tried this as you suggested:

if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn|
yandex|13448|spider|crawl)', host ) is None:

but the counter keeps increasing although the cookie named visitor on
my browser exist and also has the valuie of 'nikos'.

Why it keeps increasing? Doesn't the if code "sees" that the cookie
with a value of "nikos" is present!?!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert (unicode) text to image?

2010-08-29 Thread alex23
kj  wrote:
> Example: I went to the docs page for ImageDraw.  There I find that
> the constructor for an ImageDraw.Draw object takes an argument,
> but *what* this argument should be (integer? object? string?) is
> left entirely undefined.  From the examples given I *guessed* that
> it was an object of class Image[...]

The docs say:

  Draw(image) => Draw instance
  Creates an object that can be used to draw in the given image.

It seems pretty obvious that the first argument is an 'image' to me,
and when the lib itself defines an Image class...

You "guessed" this was the case from this prominent example at the top
of the page?

  import Image, ImageDraw

  im = Image.open("lena.pgm")
  draw = ImageDraw.Draw(im)

How much more clear can this be made?

> Sorry for the outburst, but unfortunately, PIL is not alone in
> this.  Python is awash in poor documentation. [...]
> I have to conclude that the problem with Python docs
> is somehow "systemic"...

Yes, if everyone else disagrees with you, the problem is obviously
"systemic".

What helps are concrete suggestions to the package maintainers about
how these improvements could be made, rather than huge sprawling
attacks on the state of Python documentation (and trying to tie it
into the state of Python itself) as a whole. Instead, what we get are
huge pointless rants like yours whenever someone finds that something
isn't spelled out for them in exactly the way that they want.

These people are _volunteering_ their effort and their code, all
you're providing is an over-excess of hyperbole and punctuation. What
is frustrating to me is seeing people like yourself spend far more
time slamming these projects than actually contributing useful changes
back.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:04, MRAB  wrote:

when iam trying to pass a tuple to the execute methos should i pass it
like this?

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


or like

tuple = (page, host, date)

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' % (tuple) )


Or is it the same thing?

> > =
> > I'm asking this to see why
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> > date = '%s' and host = '%s' ''' % (page, date, host) )
>
> > does work, while same thign qithout the quotes
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date
> > = %s and host = %s ''' % (page, date, host) )
>
> > doesn't. Dont know why but quotes somehopw confuse me both in strings
> > and sql_queries as well when it comes to substitutions.
>
> Don't quote the placeholders yourself. Let the method do it.

No, iam taking substitution here not mysql escaping.

Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
date = '%s' and host = '%s' ''' % (page, date, host) )

As it is above it works , with double quotes still works but if i
leave it unquoted it doesn't.

This is because without sigle or double quotes the the method doesn't
know where a value begins and here it ends? That why it needs quoting?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread MRAB

On 30/08/2010 03:07, Nik the Greek wrote:

On 30 Αύγ, 04:51, MRAB  wrote:

On 30/08/2010 02:14, Νίκος wrote:


On 29 Αύγ, 21:44, MRABwrote:

On 29/08/2010 06:34, Νίκος wrote:



On 28 Αύγ, 23:15, MRAB  wrote:

On 28/08/2010 20:37, Íßêïò wrote:



On 22 Áýã, 10:27, Íßêïòwrote:

On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>wrote:



Íßêïò wrote:

# initializecookie
cookie=Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie =cookie.get('visitor')



if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
yandex|13448|spider|crawl)', host ) is None:
blabla...




I checked and Chrome has acookienames visitor with a value ofnikos
within.
So, i have to ask why the if fails?



Maybe it's because != != ==



Iwant ti if code block to be executed only if the browsercookienames
visitor fetched doesnt cotnain the vbalue of 'nikos'



Is there somethign wrong with the way i wrote it?



Please do help me with this too becaus eif i dont solve this my
website keeps count my each visit like iam a guest visitor!



Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
repr(host). Then follow the code yourself to see whether the condition
is True.



print mycookie outputs 'None'



Thts weird because i check with the browser and the cookie is there!



Just because you can see it doesn't mean your code can.



print repr(host) outputs '78-236-176.adsl.cyta.gr'



repr(mycookie.value) (unless mycookie is None)



and also



print mycookie.value gives an error too. Maybe there is not a value
method?



If mycookie is None, then it's not surprising that doesn't have 'value'.



In summary, mycookie is None, so:



   mycookie and mycookie.value != 'nikos'



is false (actually None, which is treated as false).



host == '78-236-176.adsl.cyta.gr', so:



   re.search(r'(cyta|yandex|13448|spider|crawl)', host)



finds 'cyta' and the search returns a match.



false or false == false



blabla... isn't executed.



Lets forget the 2nd or argument, ill put it off



so we have this now



if ( mycookie and mycookie.value != 'nikos' ):
  #do stuff as long as there ins't a cookie names visitor with a
value of nikos in the broswer



What does it mean practically that the mycookie equals to None?
That mycookie doesnt exist?



How should i write this if block to mkake sure it checks whether or
not the cookie exists?


Under what conditions do you want to execute the block?

This:

  mycookie and mycookie.value != 'nikos'

will be true if:

  there _is_ a cookie, but its value isn't 'nikos'

I think that you want is to execute the block if someone else is
visiting. Correct?


Yes that exactyl right!

To make sure a cookie is set i have a script names koukos.py
containing this:

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

import cgitb; cgitb.enable()
import cgi, os, Cookie


# initialize cookie
cookie = Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie = cookie.get('visitor')

htmlBody = []

# if visitor cookie does exist
if ( mycookie and mycookie.value == 'nikos' ):
 htmlBody.append('ΑΠΟ ΤΗΝ ΕΠΟΜΕΝΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ
ΕΠΙΣΚΕΠΤΗ ΑΥΞΑΝΟΝΤΑΣ ΤΟΝ ΜΕΤΡΗΤΗ!')
 cookie['visitor'] = 'nikos'
 cookie['visitor']['expires'] = -1  #this cookie will expire
now
else:
 htmlBody.append('ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ
ΣΕ ΑΚΟΥΣΑ! ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!')
 cookie['visitor'] = 'nikos'
 cookie['visitor']['expires'] = 60*60*24*30*12

htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n')

print(cookie)
print('\n'.join(htmlBody))
=

Which i seicth on and off according to my desire if i want to be
counted or not!


How do you know when it _is_ you? There'll be a cookie which says it's
you?

If so, then you want to execute the block if there isn't any cookie, or
if there's a cookie but it doesn't say it's you:

  not mycookie or mycookie.value != 'nikos'


i tried this as you suggested:

if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn|
yandex|13448|spider|crawl)', host ) is None:

but the counter keeps increasing although the cookie named visitor on
my browser exist and also has the valuie of 'nikos'.

Why it keeps increasing? Doesn't the if code "sees" that the cookie
with a value of "nikos" is present!?!!


Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you
said that host was '78-236-176.adsl.cyta.gr', so it matched.

Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still
'78-236-176.adsl.cyta.gr' then of course it doesn't match, so the
condition is true.
--
http://mail.python.org/mailman/listinfo/python-list


Combining 2 regexes to 1

2010-08-29 Thread Niklasro(.appspot)
Hello, Suspecting it's completely doable combining these 2 regexes to
just 1 expression I'm looking for the working syntax. If you know then
kindly inform. Thanks in advance
('/a/([^/]*)',List), #list
('/a([^/]*)',List), #list
Niklas Rosencrantz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread MRAB

On 30/08/2010 03:33, Nik the Greek wrote:

On 30 Αύγ, 05:04, MRAB  wrote:

when iam trying to pass a tuple to the execute methos should i pass it
like this?

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


or like

tuple = (page, host, date)

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' % (tuple) )


Or is it the same thing?


'tuple' is the name of a built-in. Don't use it.

The first example is clearer.


=
I'm asking this to see why



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



does work, while same thign qithout the quotes



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



doesn't. Dont know why but quotes somehopw confuse me both in strings
and sql_queries as well when it comes to substitutions.


Don't quote the placeholders yourself. Let the method do it.


No, iam taking substitution here not mysql escaping.

Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
date = '%s' and host = '%s' ''' % (page, date, host) )

As it is above it works , with double quotes still works but if i
leave it unquoted it doesn't.

This is because without sigle or double quotes the the method doesn't
know where a value begins and here it ends? That why it needs quoting?


Let the method do the substitution:

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


This is the best way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Combining 2 regexes to 1

2010-08-29 Thread Chris Rebert
On Sun, Aug 29, 2010 at 7:40 PM, Niklasro(.appspot)  wrote:
> Hello, Suspecting it's completely doable combining these 2 regexes to
> just 1 expression I'm looking for the working syntax. If you know then
> kindly inform. Thanks in advance
> ('/a/([^/]*)',List), #list
> ('/a([^/]*)',List), #list

Er,

/a(/?)([^/]*)

?

Cheers,
Chris
--
Parentheses probably extraneous.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:43, MRAB  wrote:
> On 30/08/2010 03:07, Nik the Greek wrote:
>
>
>
>
>
>
>
>
>
> > On 30 Αύγ, 04:51, MRAB  wrote:
> >> On 30/08/2010 02:14, Νίκος wrote:
>
> >>> On 29 Αύγ, 21:44, MRAB    wrote:
>  On 29/08/2010 06:34, Νίκος wrote:
>
> > On 28 Αύγ, 23:15, MRAB      wrote:
> >> On 28/08/2010 20:37, Íßêïò wrote:
>
> >>> On 22 Áýã, 10:27, Íßêïò        wrote:
>  On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>        wrote:
>
> > Íßêïò wrote:
> >> # initializecookie
> >> cookie=Cookie.SimpleCookie()
> >> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> >> mycookie =cookie.get('visitor')
>
> >> if ( mycookie and mycookie.value != 'nikos' ) or re.search( 
> >> r'(cyta|
> >> yandex|13448|spider|crawl)', host ) is None:
> >>         blabla...
> >> 
>
> >> I checked and Chrome has acookienames visitor with a value ofnikos
> >> within.
> >> So, i have to ask why the if fails?
>
> > Maybe it's because != != ==
>
>  Iwant ti if code block to be executed only if the browsercookienames
>  visitor fetched doesnt cotnain the vbalue of 'nikos'
>
>  Is there somethign wrong with the way i wrote it?
>
> >>> Please do help me with this too becaus eif i dont solve this my
> >>> website keeps count my each visit like iam a guest visitor!
>
> >> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
> >> repr(host). Then follow the code yourself to see whether the condition
> >> is True.
>
> > print mycookie outputs 'None'
>
> > Thts weird because i check with the browser and the cookie is there!
>
>  Just because you can see it doesn't mean your code can.
>
> > print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> > repr(mycookie.value) (unless mycookie is None)
>
> > and also
>
> > print mycookie.value gives an error too. Maybe there is not a value
> > method?
>
>  If mycookie is None, then it's not surprising that doesn't have 'value'.
>
>  In summary, mycookie is None, so:
>
>         mycookie and mycookie.value != 'nikos'
>
>  is false (actually None, which is treated as false).
>
>  host == '78-236-176.adsl.cyta.gr', so:
>
>         re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
>  finds 'cyta' and the search returns a match.
>
>  false or false == false
>
>  blabla... isn't executed.
>
> >>> Lets forget the 2nd or argument, ill put it off
>
> >>> so we have this now
>
> >>> if ( mycookie and mycookie.value != 'nikos' ):
> >>>       #do stuff as long as there ins't a cookie names visitor with a
> >>> value of nikos in the broswer
>
> >>> What does it mean practically that the mycookie equals to None?
> >>> That mycookie doesnt exist?
>
> >>> How should i write this if block to mkake sure it checks whether or
> >>> not the cookie exists?
>
> >> Under what conditions do you want to execute the block?
>
> >> This:
>
> >>       mycookie and mycookie.value != 'nikos'
>
> >> will be true if:
>
> >>       there _is_ a cookie, but its value isn't 'nikos'
>
> >> I think that you want is to execute the block if someone else is
> >> visiting. Correct?
>
> > Yes that exactyl right!
>
> > To make sure a cookie is set i have a script names koukos.py
> > containing this:
>
> > ==
> > #!/usr/bin/python
> > # -*- coding: utf-8 -*-
>
> > import cgitb; cgitb.enable()
> > import cgi, os, Cookie
>
> > # initialize cookie
> > cookie = Cookie.SimpleCookie()
> > cookie.load( os.environ.get('HTTP_COOKIE', '') )
> > mycookie = cookie.get('visitor')
>
> > htmlBody = []
>
> > # if visitor cookie does exist
> > if ( mycookie and mycookie.value == 'nikos' ):
> >      htmlBody.append('ΑΠΟ ΤΗΝ ΕΠΟΜΕΝΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ
> > ΕΠΙΣΚΕΠΤΗ ΑΥΞΑΝΟΝΤΑΣ ΤΟΝ ΜΕΤΡΗΤΗ!')
> >      cookie['visitor'] = 'nikos'
> >      cookie['visitor']['expires'] = -1      #this cookie will expire
> > now
> > else:
> >      htmlBody.append('ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ
> > ΣΕ ΑΚΟΥΣΑ! ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!')
> >      cookie['visitor'] = 'nikos'
> >      cookie['visitor']['expires'] = 60*60*24*30*12
>
> > htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n')
>
> > print(cookie)
> > print('\n'.join(htmlBody))
> > =
>
> > Which i seicth on and off according to my desire if i want to be
> > counted or not!
>
> >> How do you know when it _is_ you? There'll be a cookie which says it's
> >> you?
>
> >> If so, then you want to execute the block if there isn't any cookie, or
> >> if there's a cookie but it doesn't say it's you:
>
> >>       not mycookie or mycookie.value != 'nikos'
>
> > i tried this as you suggested:
>
> > if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn|
> > yandex|13448|spider|crawl)', host ) is None:
>
> > but the counter keeps increas

Re: String substitution VS proper mysql escaping

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:48, MRAB  wrote:
> On 30/08/2010 03:33, Nik the Greek wrote:
>
>
>
>
>
>
>
> > On 30 Αύγ, 05:04, MRAB  wrote:
>
> > when iam trying to pass a tuple to the execute methos should i pass it
> > like this?
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
> > date = %s and host = %s ''' % (page, date, host) )
>
> > or like
>
> > tuple = (page, host, date)
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
> > date = %s and host = %s ''' % (tuple) )
>
> > Or is it the same thing?
>
> 'tuple' is the name of a built-in. Don't use it.
>
> The first example is clearer.


ok a_tuple = (page, hist, host)

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

would that syntax be correct? No need to enclose the tuple name inside
parenthesis here right?


> >>> =
> >>> I'm asking this to see why
>
> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> >>> date = '%s' and host = '%s' ''' % (page, date, host) )
>
> >>> does work, while same thign qithout the quotes
>
> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date
> >>> = %s and host = %s ''' % (page, date, host) )
>
> >>> doesn't. Dont know why but quotes somehopw confuse me both in strings
> >>> and sql_queries as well when it comes to substitutions.
>
> >> Don't quote the placeholders yourself. Let the method do it.
>
> > No, iam taking substitution here not mysql escaping.
>
> > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> > date = '%s' and host = '%s' ''' % (page, date, host) )
>
> > As it is above it works , with double quotes still works but if i
> > leave it unquoted it doesn't.
>
> > This is because without sigle or double quotes the the method doesn't
> > know where a value begins and here it ends? That why it needs quoting?
>
> Let the method do the substitution:
>
> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date =
> %s and host = %s ''', (page, date, host) )
>
> This is the best way.

Yes i will i just asked to know if i were to substitute what might be
the problem so to understand why i need the quoting.

why not like that?

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

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


Re: Combining 2 regexes to 1

2010-08-29 Thread MRAB

On 30/08/2010 03:40, Niklasro(.appspot) wrote:

Hello, Suspecting it's completely doable combining these 2 regexes to
just 1 expression I'm looking for the working syntax. If you know then
kindly inform. Thanks in advance
('/a/([^/]*)',List), #list
('/a([^/]*)',List), #list


('/a/?([^/]*)', List), #list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread MRAB

On 30/08/2010 03:55, Nik the Greek wrote:

On 30 Αύγ, 05:43, MRAB  wrote:

On 30/08/2010 03:07, Nik the Greek wrote:










On 30 Αύγ, 04:51, MRABwrote:

On 30/08/2010 02:14, Νίκος wrote:



On 29 Αύγ, 21:44, MRAB  wrote:

On 29/08/2010 06:34, Νίκος wrote:



On 28 Αύγ, 23:15, MRABwrote:

On 28/08/2010 20:37, Íßêïò wrote:



On 22 Áýã, 10:27, Íßêïò  wrote:

On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>  wrote:



Íßêïò wrote:

# initializecookie
cookie=Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie =cookie.get('visitor')



if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
yandex|13448|spider|crawl)', host ) is None:
 blabla...




I checked and Chrome has acookienames visitor with a value ofnikos
within.
So, i have to ask why the if fails?



Maybe it's because != != ==



Iwant ti if code block to be executed only if the browsercookienames
visitor fetched doesnt cotnain the vbalue of 'nikos'



Is there somethign wrong with the way i wrote it?



Please do help me with this too becaus eif i dont solve this my
website keeps count my each visit like iam a guest visitor!



Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
repr(host). Then follow the code yourself to see whether the condition
is True.



print mycookie outputs 'None'



Thts weird because i check with the browser and the cookie is there!



Just because you can see it doesn't mean your code can.



print repr(host) outputs '78-236-176.adsl.cyta.gr'



repr(mycookie.value) (unless mycookie is None)



and also



print mycookie.value gives an error too. Maybe there is not a value
method?



If mycookie is None, then it's not surprising that doesn't have 'value'.



In summary, mycookie is None, so:



mycookie and mycookie.value != 'nikos'



is false (actually None, which is treated as false).



host == '78-236-176.adsl.cyta.gr', so:



re.search(r'(cyta|yandex|13448|spider|crawl)', host)



finds 'cyta' and the search returns a match.



false or false == false



blabla... isn't executed.



Lets forget the 2nd or argument, ill put it off



so we have this now



if ( mycookie and mycookie.value != 'nikos' ):
   #do stuff as long as there ins't a cookie names visitor with a
value of nikos in the broswer



What does it mean practically that the mycookie equals to None?
That mycookie doesnt exist?



How should i write this if block to mkake sure it checks whether or
not the cookie exists?



Under what conditions do you want to execute the block?



This:



   mycookie and mycookie.value != 'nikos'



will be true if:



   there _is_ a cookie, but its value isn't 'nikos'



I think that you want is to execute the block if someone else is
visiting. Correct?



Yes that exactyl right!



To make sure a cookie is set i have a script names koukos.py
containing this:



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



import cgitb; cgitb.enable()
import cgi, os, Cookie



# initialize cookie
cookie = Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie = cookie.get('visitor')



htmlBody = []



# if visitor cookie does exist
if ( mycookie and mycookie.value == 'nikos' ):
  htmlBody.append('ΑΠΟ ΤΗΝ ΕΠΟΜΕΝΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ
ΕΠΙΣΚΕΠΤΗ ΑΥΞΑΝΟΝΤΑΣ ΤΟΝ ΜΕΤΡΗΤΗ!')
  cookie['visitor'] = 'nikos'
  cookie['visitor']['expires'] = -1  #this cookie will expire
now
else:
  htmlBody.append('ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ
ΣΕ ΑΚΟΥΣΑ! ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!')
  cookie['visitor'] = 'nikos'
  cookie['visitor']['expires'] = 60*60*24*30*12



htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n')



print(cookie)
print('\n'.join(htmlBody))
=



Which i seicth on and off according to my desire if i want to be
counted or not!



How do you know when it _is_ you? There'll be a cookie which says it's
you?



If so, then you want to execute the block if there isn't any cookie, or
if there's a cookie but it doesn't say it's you:



   not mycookie or mycookie.value != 'nikos'



i tried this as you suggested:



if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn|
yandex|13448|spider|crawl)', host ) is None:



but the counter keeps increasing although the cookie named visitor on
my browser exist and also has the valuie of 'nikos'.



Why it keeps increasing? Doesn't the if code "sees" that the cookie
with a value of "nikos" is present!?!!


Previously your regex was r'(cyta|yandex|13448|spider|crawl)' and you
said that host was '78-236-176.adsl.cyta.gr', so it matched.

Now your regex is r'(msn|yandex|13448|spider|crawl)'. If host is still
'78-236-176.adsl.cyta.gr' then of course it doesn't match, so the
condition is true.


Thats what i want.

If host doesnt contain substringsa of the regex to execute if block.

Re: Pop return from stack?

2010-08-29 Thread Aahz
In article <40a6bfac-3f4b-43f4-990b-224cb2b65...@i19g2000pro.googlegroups.com>,
Carl Banks   wrote:
>
>FWIW, I think it perfectly reasonable to let an application print a
>traceback on an error.  I've gotten a few bug reports on a little tool
>I maintain where the user copies the traceback to me, it it's helped
>me diagnose their issues a lot.

That only really works for non-GUI applications.  For GUI apps, log files
are the way to go.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 06:12, MRAB  wrote:

> This part:
>
>      ( not mycookie or mycookie.value != 'nikos' )
>
> is false but this part:
>
>      re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> is true because host doesn't contain any of those substrings.

So, the if code does executed because one of the condition is true?

How should i write it?

I cannot think clearly on this at all.

I just wan to tell it to get executed  ONLY IF

the cookie values is not 'nikos'

or ( don't knwo if i have to use and or 'or' here)

host does not contain any of the substrings.

What am i doign wrong?!

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


Re: Queue cleanup

2010-08-29 Thread Steven D'Aprano
On Sun, 29 Aug 2010 17:52:38 -0700, Paul Rubin wrote:

>> That's a problem with the CPython API, not reference counting. The
>> problem is that the CPython API is written at too low a level, beneath
>> that at which the garbage collector exists, so naturally you have to
>> manually manage memory.
> 
> Care to give an example of a reference counted system that's written any
> other way?

The complexity of the ref counter is invisible when writing pure Python 
code, and I believe it is also invisible when writing code in Cython. The 
difficulty of dealing with ref counts is abstracted away.

The argument that "it will work if we always do this" means that it won't 
work is a nice quip, but it doesn't stand up. It's possible to defeat 
even Pascal compilers' type checking and do unsafe things by dropping 
down into assembly. So don't do it! It's not hard to not do something, 
although sometimes you might choose to do it anyway, because otherwise 
there is no way to get the code you need/want. But such code should be a 
rare exception.

I'm not saying that ref counting systems can avoid incrementing and 
decrementing the ref counts. That would be silly. But I'm saying that it 
is an accident of implementation that writing C extensions requires you 
to manually manage the counts yourself. That's a side-effect of 
permitting coders to write C extensions in pure C, rather than in some 
intermediate language which handles the ref counts for you but otherwise 
compiles like C. If people cared enough, they could (probably) make the C 
compiler handle it for them, just as it currently handles incrementing 
and decrementing the return stack. 

There's nothing *fundamental* to the idea of ref counting that says that 
you must handle the counts manually -- it depends on how well insulated 
you are from the underlying machine.



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


Re: Helper app for intranet site

2010-08-29 Thread Lawrence D'Oliveiro
In message
<45e0772c-24a8-4cbb-a4fc-74a1b6c25...@n19g2000prf.googlegroups.com>, 
kevinlcarlson wrote:

> I'm exploring the possibility of developing a helper app for an
> existing internal company website.  Basically, it would automatically
> scan the current page contents, including prepopulated forms, and
> provide context-related business rule comments to the user, via a stay-
> on-top wxPython panel.

Seems like a roundabout way of doing it. Can’t you integrate into the server 
code which is generating the page contents, instead of trying to reverse-
engineer those contents?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-29 Thread Lawrence D'Oliveiro
In message <7x4oeftuk4@ruckus.brouhaha.com>, Paul Rubin wrote:

> I'd say [reference-counting is] not real gc because 1) it's unsound
> (misses reference cycles), and 2) it requires constant attention from the
> mutator to incr and decr the reference counts.  So developing modules for
> the CPython API means endlessly finding and fixing refcount bugs that lead
> to either crashes/security failures, or memory leaks.

I don’t see why that should be so. It seems a very simple discipline to 
follow: initialize, allocate, free. Here’s an example snippet from my DVD 
Menu Animator :

static void GetBufferInfo
  (
PyObject * FromArray,
unsigned long * addr,
unsigned long * len
  )
  /* returns the address and length of the data in a Python array object. */
  {
PyObject * TheBufferInfo = 0;
PyObject * AddrObj = 0;
PyObject * LenObj = 0;
do /*once*/
  {
TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", "");
if (TheBufferInfo == 0)
break;
AddrObj = PyTuple_GetItem(TheBufferInfo, 0);
LenObj = PyTuple_GetItem(TheBufferInfo, 1);
if (PyErr_Occurred())
break;
Py_INCREF(AddrObj);
Py_INCREF(LenObj);
*addr = PyInt_AsUnsignedLongMask(AddrObj);
*len = PyInt_AsUnsignedLongMask(LenObj);
if (PyErr_Occurred())
break;
  }
while (false);
Py_XDECREF(AddrObj);
Py_XDECREF(LenObj);
Py_XDECREF(TheBufferInfo);
  } /*GetBufferInfo*/

It’s quite easy to assure yourself that this is never going to leak memory. 
More complicated examples can simply nest constructs like these one within 
the other to arbitrary depth, while still giving the same assurance at every 
level. In short, this technique scales well.

> If you program the Java JNI or a typical Lisp FFI, you'll find that real
> gc is a lot simpler to use since you avoid all the refcount maintenance
> hassles.  You allocate memory and shut your eyes, and the gc takes care of
> freeing it when it figures out that you are done.

And how do you run such an application? You have to limit it to a 
predetermined amount of memory to begin with, otherwise it would easily 
gobble up everything you have.

In the old days of “classic” MacOS, every application had to run in a fixed-
size application heap. I have no wish to return to those days.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combining 2 regexes to 1

2010-08-29 Thread Niklasro(.appspot)
Many thanks. It works. You also helped me refactor these

('/([0-9]*)/?([^/]*)',AById),#id2a
('/([0-9]*)',AById)

to just 1

('/([0-9]*)/?([^/]*)',AById),#id2a

It's from the appspot framework.
Sincerely
Niklas R
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert (unicode) text to image?

2010-08-29 Thread ru...@yahoo.com
On 08/29/2010 08:21 PM, alex23 wrote:
> kj  wrote:
snip
>> Sorry for the outburst, but unfortunately, PIL is not alone in
>> this.  Python is awash in poor documentation. [...]
>> I have to conclude that the problem with Python docs
>> is somehow "systemic"...
>
> Yes, if everyone else disagrees with you, the problem is obviously
> "systemic".

No, not everyone disagrees with him.  There are many people who
absolutely agree with him.

> What helps are concrete suggestions to the package maintainers about
> how these improvements could be made, rather than huge sprawling
> attacks on the state of Python documentation (and trying to tie it
> into the state of Python itself) as a whole. ]

Nothing you quoted of what he wrote attempted to "tie it into the
state of Python itself"

> Instead, what we get are
> huge pointless rants like yours whenever someone finds that something
> isn't spelled out for them in exactly the way that they want.

He never complained about spelling choices.

> These people are _volunteering_ their effort and their code,

Yes, we all know that.

> all
> you're providing is an over-excess of hyperbole

It is hardly convincing when one criticizes hyperbole with hyperbole.

> and punctuation. What
> is frustrating to me is seeing people like yourself spend far more
> time slamming these projects than actually contributing useful changes
> back.

Face the facts dude.  The Python docs have some major problems.
They were pretty good when Python was a new, cool, project used
by a handful of geeks.  They are good relative to the "average"
(whatever that is) open source project -- but that bar is so low
as to be a string lying on the ground.

Your overly defensive and oppressive response does not help.
All it (combined with similar knee-jerk responses) does is
act to suppress any criticism leaving the impression that
the Python docs are really great, an assertion commonly made
here and often left unchallenged.  Responses like yours
create a force that works to maintain the status quo.


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


Re: Queue cleanup

2010-08-29 Thread Paul Rubin
Lawrence D'Oliveiro  writes:
>> the CPython API means endlessly finding and fixing refcount bugs that lead
>> to either crashes/security failures, or memory leaks.
>
> I don’t see why that should be so. It seems a very simple discipline to 
> follow: initialize, allocate, free. Here’s an example snippet from my DVD 
> Menu Animator :

In practice it has been a problem.  If it hasn't happened to you yet,
you're either burning a bunch of effort that programmers of more
automatic systems can put to more productive uses, or else you just
haven't written enough such code to have gotten bitten yet.

>> You allocate memory and shut your eyes, and the gc takes care of
>> freeing it when it figures out that you are done.
>
> And how do you run such an application? You have to limit it to a 
> predetermined amount of memory to begin with, otherwise it would easily 
> gobble up everything you have.

No that's usually not a problem-- the runtime system (generational gc)
can figure out enough from your allocation pattern to prevent the heap
from getting overlarge.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for open source python project

2010-08-29 Thread Brian Curtin
On Sat, Aug 28, 2010 at 19:50, mo reina  wrote:

> looking for a python project (preferably something a bit small) that
> is looking for contributors. the small bit is because i've never
> worked in a team before and haven't really read source code that's
> 1000s of lines long, so i'm not too sure i can keep up.
>
> my python fu is decent (i think), i recently wrote a small archive/
> grimoire program (command line only) that can store multiline text
> with title, tags, and basic search functionality (not using curses so
> the entry, once entered, can't be modified), entries are stored in a
> pickle file.
>
> anybody have any suggestions? i'm keen to work on something with
> others, both for learning and i'd like to do something a bit
> meaningful, plus i'm sure it's fun.


Check out http://bugs.python.org along with the pages of the Python
development area at http://www.python.org/dev/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-29 Thread Paul Rubin
Lawrence D'Oliveiro  writes:
> static void GetBufferInfo
>   ( ...
> do /*once*/
>   {
> TheBufferInfo = PyObject_CallMethod(FromArray, "buffer_info", "");
> if (TheBufferInfo == 0)
> break;
> AddrObj = PyTuple_GetItem(TheBufferInfo, 0);
> LenObj = PyTuple_GetItem(TheBufferInfo, 1);
> if (PyErr_Occurred())
> break;
> ...
> Py_INCREF(AddrObj);
> Py_INCREF(LenObj);
>   }
> while (false);
> Py_XDECREF(AddrObj);
> Py_XDECREF(LenObj);
> Py_XDECREF(TheBufferInfo);
>   } /*GetBufferInfo*/
>
> It’s quite easy to assure yourself that this is never going to leak memory. 

Actually that code looks suspicious.  Suppose in

 AddrObj = PyTuple_GetItem(TheBufferInfo, 0);
 LenObj = PyTuple_GetItem(TheBufferInfo, 1);

the first PyTuple_GetItem succeeds and the second one fails.  Then
AddrObj is a borrowed reference to the first tuple element and LenObj is
null, the error flag is set, so you break out of the do/while.  You then
decrement the refcount of AddrObj even though you didn't increment it.
Maybe there's an explanation that makes it ok somehow, but it still
looks messy.  This is the kind of problem I'm referring to in general.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance: sets vs dicts.

2010-08-29 Thread Raymond Hettinger
On Aug 29, 12:12 pm, John Nagle  wrote:
>     Is the "in" test faster for a dict or a set?
> Is "frozenset" faster than "set"?  Use case is
> for things like applying "in" on a list of 500 or so words
> while checking a large body of text.

There is no significant difference.
All three are implemented using substantially the same code.


Raymond

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


Passing variable to SQL statement when using psycopg2

2010-08-29 Thread Julia Jacobson

Dear python users,

For passing a variable to a SQL query for psycopg2, I use:

 >>> my_var = xyz
 >>> print cur.mogrify("SELECT my_values FROM my_table WHERE my_column 
= %s",(my_var,))


This returns:

 >>> SELECT my_values FROM my_table WHERE my_column = E'xyz'

Where does the "E" in front of 'xyz' come from? It's probably the 
reason, why my query doesn't work.


Thanks in advance,
Julia
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tag parsing in python

2010-08-29 Thread agnibhu
On Aug 29, 5:43 pm, Paul McGuire  wrote:
> On Aug 28, 11:23 pm, Paul McGuire  wrote:
>
>
>
> > On Aug 28, 11:14 am, agnibhu  wrote:
>
> > > Hi all,
>
> > > I'm a newbie in python. I'm trying to create a library for parsing
> > > certain keywords.
> > > For example say I've key words like abc: bcd: cde: like that... So the
> > > user may use like
> > > abc: How are you bcd: I'm fine cde: ok
>
> > > So I've to extract the "How are you" and "I'm fine" and "ok"..and
> > > assign them to abc:, bcd: and cde: respectively.. There may be
> > > combination of keyowords introduced in future. like abc: xy: How are
> > > you
> > > So new keywords qualifying the other keywords so on..
>
> I got to thinking more about your keywords-qualifying-keywords
> example, and I thought this would be a good way to support locale-
> specific tags.  I also thought how one might want to have tags within
> tags, to be substituted later, requiring a "abc::" escaped form of
> "abc:", so that the tag is substituted with the value of tag "abc:" as
> a late binding.
>
> Wasn't too hard to modify what I posted yesterday, and now I rather
> like it.
>
> -- Paul
>
> # tag_substitute.py
>
> from pyparsing import (Combine, Word, alphas, FollowedBy, Group,
> OneOrMore,
>     empty, SkipTo, LineEnd, Optional, Forward, MatchFirst, Literal,
> And, replaceWith)
>
> tag = Combine(Word(alphas) + ~FollowedBy("::") + ":")
> tag_defn = Group(OneOrMore(tag))("tag") + empty + SkipTo(tag |
> LineEnd())("body") + Optional(LineEnd().suppress())
>
> # now combine macro detection with substitution
> macros = {}
> macro_substitution = Forward()
> def make_macro_sub(tokens):
>     # unescape '::' and substitute any embedded tags
>     tag_value =
> macro_substitution.transformString(tokens.body.replace("::",":"))
>
>     # save this tag and value (or overwrite previous)
>     macros[tuple(tokens.tag)] = tag_value
>
>     # define overall macro substitution expression
>     macro_substitution << MatchFirst(
>             [(Literal(k[0]) if len(k)==1
>                 else And([Literal(kk) for kk in
> k])).setParseAction(replaceWith(v))
>                     for k,v in macros.items()] ) + ~FollowedBy(tag)
>
>     # return empty string, so macro definitions don't show up in final
>     # expanded text
>     return ""
>
> tag_defn.setParseAction(make_macro_sub)
>
> # define pattern for macro scanning
> scan_pattern = macro_substitution | tag_defn
>
> sorry = """\
> nm: Dave
> sorry: en: I'm sorry, nm::, I'm afraid I can't do that.
> sorry: es: Lo siento nm::, me temo que no puedo hacer eso.
> Hal said, "sorry: en:"
> Hal dijo, "sorry: es:" """
> print scan_pattern.transformString(sorry)
>
> Prints:
>
> Hal said, "I'm sorry, Dave, I'm afraid I can't do that."
> Hal dijo, "Lo siento Dave, me temo que no puedo hacer eso."

Thanks all for giving me great solutions. I'm happy to see the
respones.
Will try out these and post the reply soon.

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


Re: Performance: sets vs dicts.

2010-08-29 Thread Peter Otten
Seth Rees wrote:

> On 08/29/10 14:43, Peter Otten wrote:
>> John Nagle wrote:
>>
>>>  Is the "in" test faster for a dict or a set?
>>> Is "frozenset" faster than "set"?  Use case is
>>> for things like applying "in" on a list of 500 or so words
>>> while checking a large body of text.
>>
>> As Arnaud suspects: no significant difference:
>>
>> $ python dictperf.py
>> dict -->  0.210289001465
>> set -->  0.202902793884
>> frozenset -->  0.198950052261
>>
>> $ cat dictperf.py
>> import random
>> import timeit
>>
>> with open("/usr/share/dict/words") as instream:
>>  words = [line.strip() for line in instream]
>>
>> #random.seed(42)
>> sample = random.sample(words, 501)
>>
>> n = sample.pop()
>> y = random.choice(sample)
>>
>> d = dict.fromkeys(sample)
>> s = set(sample)
>> f = frozenset(sample)
>>
>>
>> for lookup in d, s, f:
>>  print type(lookup).__name__, "-->", timeit.timeit(
>>  "n in lookup; y in lookup",
>>  "from __main__ import lookup, n, y")
>>
>> Peter
> What about lists versus tuples?

You trade O(1) for O(N) with both, a bad idea for all but the smallest 
lists/tuples.

$ python dictperf.py
dict --> 0.221934080124
set --> 0.220952987671
frozenset --> 0.225043058395
list --> 21.5041530132
tuple --> 20.8655071259

By the way, the script will run on your computer, too ;)

Peter

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


Re: in place functions from operator module

2010-08-29 Thread Raymond Hettinger
On Aug 29, 8:33 am, Arnaud Delobelle  wrote:
> ernest  writes:
> > Hi,
>
> > The operator module provides separate functions for
> > "in place" operations, such as iadd(), isub(), etc.
> > However, it appears that these functions don't really
> > do the operation in place:
>
> > In [34]: a = 4
>
> > In [35]: operator.iadd(a, 3)
> > Out[35]: 7
>
> > In [36]: a
> > Out[36]: 4
>
> > So, what's the point? If you have to make the
> > assignment yourself... I don't understand.
>
> > Cheers,
> > Ernest
>
> That's because
>
>    a += b
>
> is executed as:
>
>    a = a.__iadd__(b)
>
> For immutable objects, (such as integers), a.__iadd__(b) returns a + b
> *and then* this value is assigned to a (or rather 'a' is bound to the
> value).  So for immutables objects, iadd(a, b) is the same as a + b
>
> For mutable objects (such as lists), a.__iadd__(b) mutates the object
> *and then* returns self so that when the assignement is executed, 'a'
> will still be bound the the same object.  E.g. if a = [1, 2] then
>
>     a += [3]
>
> will first append 3 to the list and then reassign the list to 'a' (it is
> unnecessary in this case but if this step was omitted, the "in place"
> operators wouldn't work on immutables types).

This is an excellent explanation.
Perhaps, you can submit a documentation
patch for the operator module so this
doesn't get lost.


Raymond


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


Re: PyGeo

2010-08-29 Thread L

On 30/08/10 05:00, Thomas Jollans wrote:

On Sunday 29 August 2010, it occurred to L to exclaim:
   

has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu
10.04) ,
the site says

   http://www.wspiegel.de/pymaxima/index_en.html

"Note: The installation of PyGeo work's only under Python 2.4 (The
further development of pygeo seems to be stopped)"

is this to do with re-org of site-packages, dist_packages etc.

any help most appreciated.
 

I don't know. I haven't tried. Maybe somebody else here has, but don't count
on it. Have you tried it? If not, then why not? Try it. Maybe it just works.
As far as I know, distutils haven't changed much, carefully avoiding any
changes that could break packages.

I think it's entirely possible that the web page author claiming "the
installation" doesn't work was referring only to the Windows installer.

Have fun,
Thomas
   



I have tried it and as soon as you try any of the examples  in the 
examples dir it cannot find numpy etc


I have manually move the pygeo dirs and contents to 
/usr/lib/python2.6/dis-packages,


 (this is the directory where numpy, numeric and scipy were installed 
when using synaptic )


 made sure thatread and write permissions set for ALL FILES and 
DIRECTORIES to RW using sudo chmod 777


any ideas.



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