[SQL] Pick random rows from SELECT?

2009-09-21 Thread Threader Slash
Here is a simple and quick solution --

Generate a random number
"random.shuffle(x[, random])¶Shuffle the sequence x in place. The optional
argument random is a 0-argument function returning a random float in [0.0,
1.0); by default, this is the function random()."
http://docs.python.org/library/random.html

Multiple the random value returned by the maxnumber of your table primary
key index.
http://www.tizag.com/mysqlTutorial/mysqlmax.php

Then use the result in your query as

randID = MAX(id) * random()

SELECT objectname FROM products WHERE objectID = randID

Hope this help.
Cheers... Threader


-- Forwarded message --
From: Dennis Lee Bieber 
To: python-list@python.org
Date: Mon, 21 Sep 2009 21:40:02 -0700
Subject: Re: [SQL] Pick random rows from SELECT?
On Mon, 21 Sep 2009 10:59:38 +0200, Gilles Ganault 
declaimed the following in gmane.comp.python.general:

> Since this list is quite big and the site is the bottleneck, I'd like
> to run multiple instances of this script, and figured a solution would
> be to pick rows at random from the dataset, check in my local database
> if this item has already been taken care of, and if not, download
> details from the remote web site.
>
   You really think making MULTIPLE, overlapping requests to a web site
is going to be more efficient than just suffering the single transfer
time of one large query?

> If someone's done this before, should I perform the randomization in
> the SQL query (SQLite using the APSW wrapper
> http://code.google.com/p/apsw/), or in Python?
>
   Pardon, I thought you implied the bottleneck is the web-site
database -- I'd worry about any web-site that exposes a file-server
based database to direct user access.

> Here's some simplified code:
>
> sql = 'SELECT id,label FROM companies WHERE activity=1'
> rows=list(cursor.execute(sql))
> for row in rows:
>   id = row[0]
>   label = row[1]
>
>   print strftime("%H:%M")
>   url = "http://www.acme.com/details.php?id=%s"; % id
>   req = urllib2.Request(url, None, headers)
>   response = urllib2.urlopen(req).read()
>
>   name = re_name.search(response)
>   if name:
>   name = name.group(1)
>   sql = 'UPDATE companies SET name=? WHERE id=?'
>   cursor.execute(sql, (name,id) )

   Ah... You mean you are retrieving the names from a local database,
and then requesting web-site details based upon that name.

   No matter how you look at it, you appear to want to process the
entire local list of companies... Multiple randomized local queries will
just add to the final run-time as you start to get duplicates -- and
have to reject that one to query for another random name.

   I'd suggest either a pool of threads -- 5-10, each reading company
names from a shared QUEUE, which is populated by the main thread
(remember to commit() so that you don't block on database updates by the
threads). OR... determine how many companies there are, and start
threads feeding them  and  (length being #names /
#threads, round up -- start then being 0*length+1, 1*length+1, etc...)
and use those in thread specific selects using "... limit 
offset "... This way each thread retrieves its own limited set of
companies (make sure to use the same sorting criteria).
--
   Wulfraed Dennis Lee Bieber   KD6MOG
   wlfr...@ix.netcom.com
HTTP://wlfraed.home.netcom.com/




-- Forwarded message --
From: greg 
To: python-list@python.org
Date: Tue, 22 Sep 2009 17:07:33 +1200
Subject: Re: Comparison of parsers in python?
Nobody wrote:

 What I want: a tokeniser generator which can take a lex-style grammar (not
> necessarily lex syntax, but a set of token specifications defined by
> REs, BNF, or whatever), generate a DFA, then run the DFA on sequences of
> bytes. It must allow the syntax to be defined at run-time.
>

You might find my Plex package useful:

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/

It was written some time ago, so it doesn't know about
the new bytes type yet, but it shouldn't be hard to
adapt it for that if you need to.

 What I don't want: anything written by someone who doesn't understand the
> field (i.e. anything which doesn't use a DFA).
>

Plex uses a DFA.

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


Re: easy question, how to double a variable

2009-09-21 Thread Processor-Dev1l
On Sep 20, 10:27 pm, daggerdvm  wrote:
>  Write the definition of a function  twice , that receives an  int
> parameter and returns an  int that is twice the value of the
> parameter.
>
> how can i do this

I will stop this theatre...
as you should know, you want your function to make arithmetic
operation n*2.
Everything you have to do is to define some function with parameter n
and make this function to return n*2.
If you are not jerk, you can make the whole code you need from the
previous sentence :)))
-- 
http://mail.python.org/mailman/listinfo/python-list


Solved - Python: automate input to MySQL query

2009-09-21 Thread Threader Slash
-- Forwarded message --
> From: Philip Semanchuk 
> To: "Python-list (General)" 
> Date: Mon, 21 Sep 2009 08:49:27 -0400
> Subject: Re: Python: automate input to MySQL query
>
> On Sep 21, 2009, at 5:18 AM, Threader Slash wrote:
>
>  Hi Everybody...
>>
>> I have a query that works as follows:
>>
>> Code:
>>
>> db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
>> (traveler INNER JOIN takenvaccine ON traveler.travelerID =
>> takenvaccine.travelerID)
>>   INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
>>   INNER JOIN requiredvaccine ON
>> vaccine.vaccineID=requiredvaccine.requiredvaccineID
>>   INNER JOIN city ON requiredvaccine.cityID = city.cityID
>> WHERE traveler.travelerFirstName = 'John'""")
>>
>> The output gives me all vaccines taken by a given employee. To allow the
>> user to choose different names when running the system, I am trying to use
>> a
>> variable, named *person*:
>>
>> Code:
>>
>> person = "John"
>>
>> db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
>> (traveler INNER JOIN takenvaccine ON traveler.travelerID =
>> takenvaccine.travelerID)
>>   INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
>>   INNER JOIN requiredvaccine ON
>> vaccine.vaccineID=requiredvaccine.requiredvaccineID
>>   INNER JOIN city ON requiredvaccine.cityID = city.cityID
>> WHERE traveler.travelerFirstName = 'person'""")
>>
>> Then I run the query inside my python program. The first version without
>> variable works fine. But the second, using variable, doesn't give me any
>> output. What I am missing here about the python variable sintaxe to make
>> the
>> MySQL work with variable ... Any suggestion?
>>
>
> In your second query you've got "person" hardcoded as a string. You're
> looking for a traveler with the actual first name of person.
>
> Change this line:
>
>> WHERE traveler.travelerFirstName = 'person'""")
>>
>
> to this:
>
>> WHERE traveler.travelerFirstName = %s""")
>>
>
> and pass person as a list of params to db.query(). Something like this
> should work:
>
> sql = """SELECT blah blah blah WHERE traveler.travelerFirstName = %s"""
> db.query(sql, [person])
>
> See the Python DB API documentation for specifics. This might look like the
> same thing as string interpolation, but it isn't.
>
> Good luck
> Philip
>

Hi Philip,

Thanks for comments and suggestions.

Now it works! Here is the solution:

 Code:


self.db = MySQLdb.connect(hostname,username,passwd,dbname)
self.cursor=self.db.cursor();

name="John"
runQuery="SELECT traveler.travelerFirstName,vaccine.vaccineName from
traveler INNER JOIN takenvaccine ON traveler.travelerID =
takenvaccine.travelerID INNER JOIN vaccine ON
takenvaccine.vaccineID=vaccine.vaccineID INNER JOIN requiredvaccine ON
vaccine.vaccineID=requiredvaccine.requiredvaccineID INNER JOIN site ON
requiredvaccine.siteID = site.siteID WHERE traveler.travelerFirstName
= %s"

self.cursor.execute(runQuery,(name,))

print "tell vaccines taken for a chosen traveler\n"

for row in self.cursor.fetchall():
 print row


Note: you need to declare the whole query in the same line to it take effect
in the variable "runQuery".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-21 Thread Tim Roberts
daggerdvm  wrote:
>
>carl banks.you are a dork

What are you, eleven years old?

Look, you asked us to answer for you what is CLEARLY a homework question.
It is unethical for you to ask that, and it is unethical for us to answer
it.

As others have said, show us what you TRIED, and we can help you make it
work.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter - Text - bullets

2009-09-21 Thread Thomas Lehmann
> This is probably why you had all these alignment problems. But it's
> weird, because the script I posted is copied and pasted from a really
> script that I've run, and which doesn't cause any error. What is the
> version of tcl/tk used by your Tkinter module? And what is your Python
> version?

Using python 2.5 (with Tcl/Tk 8.4):

Traceback (most recent call last):
  File "Text1.py", line 10, in 
txt.tag_configure('bulleted_list', font=('Times', 18),
lmargin1='10m', lmargin2='15m', tabs=['15m'])
  File "E:\Python25\lib\lib-tk\Tkinter.py", line 3066, in
tag_configure
return self._configure(('tag', 'configure', tagName), cnf, kw)
  File "E:\Python25\lib\lib-tk\Tkinter.py", line 1188, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: bad screen distance "['15m']"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-deprecated equivalent of rfc822.AddressList

2009-09-21 Thread Cameron Simpson
On 21Sep2009 10:49, Jason Tackaberry  wrote:
| On Wed, 2009-09-16 at 14:49 -0400, Jason Tackaberry wrote:
| > Since the rfc822 module was removed in Python 3, and is deprecated in
| > 2.3, I am obviously trying to avoid using it.
| > 
| > But I'm having a hard time finding an equivalent to rfc822.AddressList
| > in the email module, which I want to use to parse a _list_ of addresses:
| [...]
| > Is there some non-deprecated method I can use to parse an RFC 2822
| > address list?
| 
| No takers?  Should I file a bug?

Hmm. My address gathering program starts with:

  from email.utils import parseaddr, getaddresses, formataddr

See the pydoc for email.utils; it's very easy to use.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Reason #173 to fear technology:

o   o   o   o   o   o  
   ^|\ ^|^ v|^ v|v |/v |X|  \|  |
/\  >\ /<   >\ /<   >\ /<   >\

o>  o   o   o   o   o   o   o
\   x<\> <)>  |\
   /<   >\ /<   >\ /<   >\  >>  L

 Mr. email does the Macarena.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding application data after install - a solution?

2009-09-21 Thread Wolodja Wentland
On Mon, Sep 21, 2009 at 23:52 -0300, Gabriel Genellina wrote:
> En Sat, 19 Sep 2009 12:03:52 -0300, Wolodja Wentland
>  escribió:
> 
> >reliably finding distribution data from your program seems to be an
> >unsolved issue for programs packaged with distutils.

[...]

> Isn't pkgutil.get_data() what you're looking for?
> I'm not sure it covers all your use cases though.

No that pkgutil.get_data() is exactly *not* what I am looking for ;-)

I have a library which *could* use external data and use this additional
information to cover more cases, but works perfectly fine without this
data. The data could change more frequently than i want to release the
library.

I use distutils data_files=... to have the data installed, but there
is/was (until the recipe I posted here) no way to find that data again,
because the admin could define arbitrary prefixes for libs, scripts and
data. That means that there might be absolutely no relation between the
module path and the data file path.

I want to:

1. Give administrators the freedom to install the data wherever they
   want
2. Adhere to the FHS (installing data within modules breaks it)
3. Be able to find that data again regardless of the installation
  scheme used

1 and 2 are easily solved... It was just not possible to find the data
again. The snippet in the original code solves that.

I still don't think that relying on these internal structures within
distutils is supported, but can't think of a better way.

so long and thanks for all the fish

Wolodja


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison of parsers in python?

2009-09-21 Thread greg

Nobody wrote:


What I want: a tokeniser generator which can take a lex-style grammar (not
necessarily lex syntax, but a set of token specifications defined by
REs, BNF, or whatever), generate a DFA, then run the DFA on sequences of
bytes. It must allow the syntax to be defined at run-time.


You might find my Plex package useful:

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/

It was written some time ago, so it doesn't know about
the new bytes type yet, but it shouldn't be hard to
adapt it for that if you need to.


What I don't want: anything written by someone who doesn't understand the
field (i.e. anything which doesn't use a DFA).


Plex uses a DFA.

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


Re: on package import, have it conditionally import a subpackage

2009-09-21 Thread Gabriel Genellina
En Sat, 19 Sep 2009 17:06:11 -0300, Gabriel Rossetti  
 escribió:



Hello everyone,

I'd like to ba able to import a package and have it's __init__  
conditionally import a subpackage. Suppose that you have this structure :


mybase/
mybase/__init__.py
mybase/mypkg
mybase/mypkg/__init__.py
mybase/mypkg/module0.py
mybase/mypkg/type1
mybase/mypkg/type1/__init__.py
mybase/mypkg/type1/module1.py
mybase/mypkg/type1/module2.py
mybase/mypkg/type2
mybase/ mypkg/type2/__init__.py
mybase/ mypkg/type2/module1.py
mybase/ mypkg/type2/module2.py

I'd like to do something like th following in my code

 >>> import mybase
 >>> mybase.setType("type1")
 >>> from mybase.mypkg import module0, module1, module2
 >>> module0.__file__
'mybase/mypkg/module0.pyc'
 >>> module1.__file__
'mybase/mypkg/type1/module1.pyc'
 >>> module2.__file__
'mybase/mypkg/type1/module2.pyc'

but I can't figure out how to do this.


That depends on how dynamic you want/have to be.

(inside mybase/mypkg.__init__py):

def setType(type_):
  global module1, module2
  if type_ == 'type1':
from .type1 import module1, module2
  elif type_ == 'type2':
from .type2 import module1, module2
  else:
raise ValueError, 'unknown type: %s' % type_

A more generic version:

def setType(type_):
  global module1, module2
  t = __import__(type_, globals(), locals(), ['module1','module2'], 1)
  module1 = t.module1
  module2 = t.module2

--
Gabriel Genellina

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


Re: easy question, how to double a variable

2009-09-21 Thread Grant Edwards
On 2009-09-21, David C Ullrich  wrote:
> On Sun, 20 Sep 2009 13:27:07 -0700, daggerdvm wrote:
>
>> Write the definition of a function  twice , that receives an  int
>> parameter and returns an  int that is twice the value of the parameter.
>> 
>> how can i do this
>
> I don't think this can be done in Python.
>
> Looking at the Subject line I thought your problem was going
> to be easy: There's only one float type in Python, so at least
> in most implementations simply converting to float will
> suffice to "double" a variable.
>
> But you actually want to return twice the value. I don't see
> how to do that.

It's easy:

def twice(i):
return i
return i

-- 
Grant

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


Re: Non-deprecated equivalent of rfc822.AddressList

2009-09-21 Thread Gabriel Genellina
En Mon, 21 Sep 2009 11:49:15 -0300, Jason Tackaberry   
escribió:

On Wed, 2009-09-16 at 14:49 -0400, Jason Tackaberry wrote:



Since the rfc822 module was removed in Python 3, and is deprecated in
2.3, I am obviously trying to avoid using it.

But I'm having a hard time finding an equivalent to rfc822.AddressList
in the email module, which I want to use to parse a _list_ of addresses:

[...]

Is there some non-deprecated method I can use to parse an RFC 2822
address list?


No takers?  Should I file a bug?


Seems so...

--
Gabriel Genellina

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


where is ctrl+newline handled in pywin editor?

2009-09-21 Thread C or L Smith
I use the pywin environment on Windows for python code editing and interactive 
environment. 

I've been able to find the place in the editor files where the enter key is 
handled and where the whitespace is stripped from a line and I've been able to 
get it to not leave any white space when a double return is entered. But what I 
would like to be able to do is find the place where ctrl+enter is handled so I 
could have it strip any trailing space from the current line before going back 
to the left margin. Is anyone acquainted enough with the pywin editor to be 
able to help with this?

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


Re: Finding application data after install - a solution?

2009-09-21 Thread Gabriel Genellina
En Sat, 19 Sep 2009 12:03:52 -0300, Wolodja Wentland  
 escribió:



reliably finding distribution data from your program seems to be an
unsolved issue for programs packaged with distutils.

I have seen a lot of code that manipulates mod.__file__ to solve this
problem, but this *will* break for some installation schemes and has the
following problems:

* it breaks if the user specified '--install-data' to have a different
  value than '--install-{pure,plat}lib'
* it makes the life of linux distribution package maintainers
  unneccessarily hard, because they have to patch your code so it works
  with their file system hierarchy.
* it does not work inside eggs
* it is ugly ;-)


Isn't pkgutil.get_data() what you're looking for?
I'm not sure it covers all your use cases though.

--
Gabriel Genellina

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


Re: easy question, how to double a variable

2009-09-21 Thread Tim Chase

But you actually want to return twice the value. I don't see
how to do that.



Ah, I think I see...returning more than once is done with the 
"yield" keyword:


  def f(param):
yield param
yield param

That returns twice the integer parameter... :-D

However, the OP was instructed to "Write the definition of a 
function twice" which means I'd have to copy & paste the final 
function definition a second time to make sure it was done twice 
(as Carl suggested).


Then again as David notices, the subject lines asks how to double 
a variable, in which case one might want


  import struct
  def f(param):
return struct.pack('f', param)

which doubles the parameter... :-S

-tkc




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


Re: using python 2.5

2009-09-21 Thread Sean DiZazzo
On Sep 21, 4:42 pm, "kunal.k"  wrote:
> I have installed python 2.5 for a particular code. Now i have 2.6
> already installed. How do i direct this code to use the 2.5 modules??

I don't think you do.  You should install the modules for python 2.6.
You could try to hand copy the modules, and some might work, but it's
crap shoot.

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


Re: easy question, how to double a variable

2009-09-21 Thread Steven D'Aprano
On Mon, 21 Sep 2009 13:50:23 -0500, David C Ullrich wrote:

> But you actually want to return twice the value. I don't see how to do
> that.

What?

Seriously? You're not just yanking the OP's chain???


-- 
Steven
who normally does quite well detecting sarcasm in writing
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OK to memoize re objects?

2009-09-21 Thread Steven D'Aprano
On Mon, 21 Sep 2009 13:33:05 +, kj wrote:

> I find the docs are pretty confusing on this point.  They first make the
> point of noting that pre-compiling regular expressions is more
> efficient, and then *immediately* shoot down this point by saying that
> one need not worry about pre-compiling in most cases. From the docs:
> 
> ...using compile() and saving the resulting regular expression
> object for reuse is more efficient when the expression will be used
> several times in a single program.
> 
> Note: The compiled versions of the most recent patterns passed to
> re.match(), re.search() or re.compile() are cached, so programs that
> use only a few regular expressions at a time needn't worry about
> compiling regular expressions.
> 
> Honestly I don't know what to make of this...  I would love to see an
> example in which re.compile was unequivocally preferable, to really
> understand what the docs are saying here...

I find it entirely understandable. If you have only a few regexes, then 
there's no need to pre-compile them yourself, because the re module 
caches them. Otherwise, don't rely on the cache -- it may help, or it may 
not, no promises are made.

The nature of the cache isn't explained because it is an implementation 
detail. As it turns out, the current implementation is a single cache in 
the re module, so every module "import re" shares the one cache. The 
cache is also completely emptied if it exceeds a certain number of 
objects, so the cache may be flushed at arbitrary times out of your 
control. Or it might not.



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


Re: How to change string or number passed as argument?

2009-09-21 Thread Gabriel Genellina

En Sat, 19 Sep 2009 22:59:21 -0300, Peng Yu  escribió:


I know that strings or numbers are immutable when they passed as
arguments to functions. But there are cases that I may want to change
them in a function and propagate the effects outside the function. I
could wrap them in a class, which I feel a little bit tedious. I am
wondering what is the common practice for this problem.


In addition to all previous responses: Sometimes, you have a function that
should return more than one piece of information. On other languages, you
have to choose *one* of them as *the* function return value, and the
others become out parameters. In Python you simply return all of them:

def decode_index(index):
  "convert linear index into row, col coordinates"
  return index // width, index % width # divmod would be better...

row, col = decode_index(index)

(Tecnically, you're still returning ONE object - a tuple. But since
packing and unpacking of values is done automatically, you may consider it
as returning multiple values at the same time).

--
Gabriel Genellina

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


expy 0.2 released!

2009-09-21 Thread Yingjie Lan
Hi, 

This is to announce the release of expy 0.2.


What's new?


1. fixed the 'const char*' bug.
2. introduced the 'raw_type'.

What is expy?
--
 
expy is an expressway to extend Python!
 
For more details, visit 

http://expy.sf.net/

Have a nice one!

Yingjie


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


Re: An assessment of the Unicode standard

2009-09-21 Thread Emile van Sebille

On 9/19/2009 11:33 PM Greg Ewing said...

It's possible that some individuals do this more
frequently than others, e.g. mathematicians and other
people who are in the habit of exploring new ideas may
be less influenced by the constraints of language
than the general population.



As I recall Shakespeare (to use one of his many spellings) is one of the 
largest contributers of new words to the English language...


Emile

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


using python 2.5

2009-09-21 Thread kunal.k
I have installed python 2.5 for a particular code. Now i have 2.6
already installed. How do i direct this code to use the 2.5 modules??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An assessment of the Unicode standard

2009-09-21 Thread Gabriel Genellina
En Sun, 20 Sep 2009 03:33:47 -0300, Greg Ewing  
 escribió:

Hendrik van Rooyen wrote:

In any case, it doesn't affect my point, which was that
I was thinking about something that I didn't have a word,
or even a convenient phrase for.

That is probably true, but on the other hand, it is not totally rubbish  
either, as it is hard to think of stuff you have never heard of,  
whether you have an undefined word for it or not.


I quite agree that there is *some* interaction between
the language we use and the way we think, but it's a
two-way process. As a species, we're quite capable of
thinking about new things and inventing words to express
them when the need arises.

It's possible that some individuals do this more
frequently than others, e.g. mathematicians and other
people who are in the habit of exploring new ideas may
be less influenced by the constraints of language
than the general population.


Anyway, they're still constrained by the language.

In ancient Greece many wise men made remarkable progress in geometry,  
arithmetic, and other areas - but could not develop algebra. Why not?  
Algebra requires abstract names for unknowns - x,y,z that we use today.  
The greek number system used letters to represent numbers themselves -  
α=1, β=2, etc. - so no one would think on using letters for designating  
unknown quantities; it was just out of their mental frame.


Diophantus created some kind of algebra notation, so he was able to write  
x**n (for 2<=n<=6, basically combining the expressions for x² and x³) and  
could express some equations in short (or abridged) form, instead of the  
full prose that were used normally. But he was simply not able to develop  
symbolic algebra. And nothing happened for 15 centuries in this regard in  
Europe.


The Arabians brought the Indian number system (and the idea of zero as a  
number) to Europe. And it's not a coincidence that Arabians also developed  
symbolic Algebra at the same time [2]; they *could* develop Algebra  
because they had a language into which symbolic names could be expressed.


[1] Colerus, Egmont. Historia de la Matemática. De Pitágoras a Hilbert.  
Bs. As, Ediciones Progreso y Cultura, 1943


[2] BTW, the very name 'algebra' comes from a book of Abu Ja'far Muhammad  
ibn Musa Al-Khwarizmi, "al-jabr w'al-muqabala". And guess where  
'algorithm' comes from?


--
Gabriel Genellina

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


Re: easy question, how to double a variable

2009-09-21 Thread Sean DiZazzo
On Sep 21, 1:46 pm, daggerdvm  wrote:
> u don't want to answerthen why post?...get lost.

I eat children...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Zac Burns
On Mon, Sep 21, 2009 at 2:10 PM, Rob Williscroft  wrote:
>  wrote in news:mailman.216.1253565002.2807.python-l...@python.org in
> comp.lang.python:
>
>>>Niether of the CPython versions (2.5 and 3.0 (with modified code))
>>>exibited any memory increase between "allocated 1 meg + " and "end"
>>
>> You bumped into a special case that CPython optimizes.  s[:] is s.  If
>> you repeat your test with s[1:], you'll see memory climb as one might
>> normally expect.
>>
>
> Thanks for the correction (to Jack also)
>
> Rob.
> --
> http://www.victim-prime.dsl.pipex.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks! The buffer object was exactly the 'slice view' that I was
looking for to fix my version of the algorithm.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-21 Thread Ethan Furman

daggerdvm wrote:

u don't want to answerthen why post?...get lost.


On the contrary!  We *do* want to answer.  Prizes are awarded based on 
the most outlandish yet correct answer, on the most literal answer, and 
on the funniest answer!


Ridiculous questions like yours are what make the daily checking of the 
mailing list worth while.


Now, if you have a _real_ question, that's not homework, check out 
http://catb.org/~esr/faqs/smart-questions.html and then try again.


Happy Coding!

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


Re: specify max width to reportlab.canvas.drawString

2009-09-21 Thread juanefren
On Sep 18, 3:20 am, Robin Becker  wrote:
> juanefren wrote:
> > I am usingreportlabto create pdf documents, everything looks fine,
> > how ever, is there a way to specify a max width to drawString
> > function ? I mean cut the sentence and continue a step down...
>
> > Cheers
>
> You'll get better results asking at thereportlabuser group
>
> reportlab-us...@reportlab.com
>
> but there are some ways to do what you want just with simple string 
> manipulation.
>
> Assuming you know the initial x, y and have setup a canvas with the font and
> sizeand the maximum width you want.
>
> fromreportlab.lib.utils import simpleSplit
> L = simpleSplit(text,canv._fontname,canv._fontsize,maxWidth)
>
> for t in L:
>         canv.drawString(x,y,t)
>         y -= canv._leading
>
> I haven't tested this code, but that's the principle anyway for direct drawing
> to the canvas.
> --
> Robin Becker

It worked very good, thank you :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Rob Williscroft
 wrote in news:mailman.216.1253565002.2807.python-l...@python.org in 
comp.lang.python:

>>Niether of the CPython versions (2.5 and 3.0 (with modified code))
>>exibited any memory increase between "allocated 1 meg + " and "end"
> 
> You bumped into a special case that CPython optimizes.  s[:] is s.  If 
> you repeat your test with s[1:], you'll see memory climb as one might 
> normally expect.
> 

Thanks for the correction (to Jack also)

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plotting wav file

2009-09-21 Thread Rami Chowdhury

On Mon, 21 Sep 2009 12:53:44 -0700, Maggie  wrote:


I am by far more acquainted with R and generally would use it in this
case, however, this particular experiment does require a lot of AFNI
work, therefore I am a bit lost.
the .wav was generated via --

waver -WAV -TR 2.5 -tstim `cat a_STD_W.1D`  > a_STD_W.WAV



Could you post a small snippet of the .wav file itself? My understanding  
is that it's simply a column of numbers, in which case it should be fairly  
simple to plot them.




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-21 Thread daggerdvm
carl banks.you are a dork
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-21 Thread daggerdvm
u don't want to answerthen why post?...get lost.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Jack Diederich
On Mon, Sep 21, 2009 at 4:00 PM, Rob Williscroft  wrote:
> AIUI, as a python string is imutable, a slice of a string is a
> new string which points (C char *) to the start of the slice data
> and with a length that is the length of the slice, about 8 bytes
> on 32 bit machine.

Not in CPython.  While some special strings are re-used (empty string,
single letters) if you take a slice of an existing string a new buffer
is allocated and the slice memcpy'd into it.

> So even though a slice assignment new_s = s[:] appears to a python
> programmer to make a "copy" of s, its only the a few bytes of
> metadata (the pointer and the length) that is really copied, the
> strings character data stays where it is.

There is a special case for copy in CPython that avoids copying the
string bytes, BUT in that case it just INCREFs the existing object and
returns it.  There are no new allocations at all.

Be very careful recommending optimizations based on how you think the
underlying implementation works without double checking with the code
first.

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


Re: socket send O(N**2) complexity

2009-09-21 Thread exarkun

On 08:00 pm, r...@freenet.co.uk wrote:
Zac Burns wrote in news:mailman.211.1253559803.2807.python- 
l...@python.org

in comp.lang.python:

The mysocket.mysend method given at
http://docs.python.org/howto/sockets.html has an (unwitting?) O(N**2)
complexity for long msg due to the string slicing.

I've been looking for a way to optimize this, but aside from a pure
python 'string slice view' that looks at the original string I can't
think of anything. Perhaps start and end keywords could be added to
send? I can't think of a reason for the end keyword,  but it would be
there for symmetry.


I ran this script on various versions of python I have access to:

#encoding: utf-8
raw_input( "start" )

s = 'x' * 100
r = [None] * 1000

raw_input( "allocated 1 meg + " )

for i in xrange(1000):
 r[i] = s[:]

raw_input( "end" )

Niether of the CPython versions (2.5 and 3.0 (with modified code))
exibited any memory increase between "allocated 1 meg + " and "end"


You bumped into a special case that CPython optimizes.  s[:] is s.  If 
you repeat your test with s[1:], you'll see memory climb as one might 
normally expect.

pypy-c (1.0.0) showed a 30k jump, and IronPython 2.0 showed a few megs
jump.

AIUI, as a python string is imutable, a slice of a string is a
new string which points (C char *) to the start of the slice data
and with a length that is the length of the slice, about 8 bytes
on 32 bit machine.

So even though a slice assignment new_s = s[:] appears to a python
programmer to make a "copy" of s, its only the a few bytes of
metadata (the pointer and the length) that is really copied, the
strings character data stays where it is.

So the code you cite is in fact O(N) as the copy is constant size.


This all (basically) valid for the special case of s[:].  For any other 
string slicing, though, the behavior is indeed O(N**2).


To the OP, you can get view-like behavior with the "buffer" builtin. 
Here's an example of its usage from Twisted, where it is employed for 
exactly the reason raised here:


http://twistedmatrix.com/trac/browser/trunk/twisted/internet/abstract.py#L93

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


Re: Plotting wav file

2009-09-21 Thread Rami Chowdhury

On Mon, Sep 21, 2009 at 4:11 PM, Rami Chowdhury
 wrote:

On Mon, 21 Sep 2009 12:53:44 -0700, Maggie  wrote:


I am by far more acquainted with R and generally would use it in this
case, however, this particular experiment does require a lot of AFNI
work, therefore I am a bit lost.
the .wav was generated via --

waver -WAV -TR 2.5 -tstim `cat a_STD_W.1D`  > a_STD_W.WAV



Could you post a small snippet of the .wav file itself? My  
understanding is

that it's simply a column of numbers, in which case it should be fairly
simple to plot them.


On Mon, 21 Sep 2009 13:14:08 -0700, Maggie  wrote:


You're correct! This is the beginning of the .wav file.

0
0
0.19385
6.79566
7.62695
1.91679
-1.71133

[snip]

and so on..



That seems fairly straightforward -- assuming the .wav file is small  
enough, I'd suggest simply reading the values into a list, and then using  
one of the many Python plotting packages  
(http://wiki.python.org/moin/NumericAndScientific/Plotting) to graph them  
however you need. If you're familiar with R, I might suggest using RPy  
(http://rpy.sourceforge.net/rpy.html), although I've not used it myself.


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


Re: socket send O(N**2) complexity

2009-09-21 Thread Rob Williscroft
Zac Burns wrote in news:mailman.211.1253559803.2807.python-l...@python.org 
in comp.lang.python:

> The mysocket.mysend method given at
> http://docs.python.org/howto/sockets.html has an (unwitting?) O(N**2)
> complexity for long msg due to the string slicing.
> 
> I've been looking for a way to optimize this, but aside from a pure
> python 'string slice view' that looks at the original string I can't
> think of anything. Perhaps start and end keywords could be added to
> send? I can't think of a reason for the end keyword,  but it would be
> there for symmetry.
> 

I ran this script on various versions of python I have access to:

#encoding: utf-8
raw_input( "start" )

s = 'x' * 100
r = [None] * 1000

raw_input( "allocated 1 meg + " )

for i in xrange(1000):
  r[i] = s[:]

raw_input( "end" )

Niether of the CPython versions (2.5 and 3.0 (with modified code))
exibited any memory increase between "allocated 1 meg + " and "end"

pypy-c (1.0.0) showed a 30k jump, and IronPython 2.0 showed a few megs
jump.

AIUI, as a python string is imutable, a slice of a string is a
new string which points (C char *) to the start of the slice data
and with a length that is the length of the slice, about 8 bytes
on 32 bit machine.

So even though a slice assignment new_s = s[:] appears to a python
programmer to make a "copy" of s, its only the a few bytes of 
metadata (the pointer and the length) that is really copied, the 
strings character data stays where it is.

So the code you cite is in fact O(N) as the copy is constant size.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket send O(N**2) complexity

2009-09-21 Thread Mike
On Sep 21, 2:03 pm, Zac Burns  wrote:
> The mysocket.mysend method given 
> athttp://docs.python.org/howto/sockets.htmlhas an (unwitting?) O(N**2)
> complexity for long msg due to the string slicing.
>
> I've been looking for a way to optimize this, but aside from a pure
> python 'string slice view' that looks at the original string I can't
> think of anything. Perhaps start and end keywords could be added to
> send? I can't think of a reason for the end keyword,  but it would be
> there for symmetry.

for ch in msg: add to current buffer or start another buffer
for buf in buffers: send(...buf)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plotting wav file

2009-09-21 Thread Rami Chowdhury

On Mon, 21 Sep 2009 12:13:30 -0700, Maggie  wrote:


On Sep 21, 3:07 pm, "Rami Chowdhury"  wrote:

On Mon, 21 Sep 2009 11:58:30 -0700, Maggie  wrote:
> What would be the best way to plot a small .wav file in python? If
> there are any tutorials or sample code, I would really appreciate it!

I'm sorry, what are you hoping to plot about the .wav file?



.wav file was generated from .1D file that contained times of
occurrence of a stimulus within the experiment. The y-axis is the TR
and the x-axis is supposed to be the length of y. I am hoping to see
plot representation of .wav file so i can align it to time series fMRI
data via independent component analysis.
this is the sample .1D file that was converted into the .wav file --

2.625:2.855 46.125:46.355   92.125:92.355   150.125:150.355
179.125:179.355 239.625:239.855 304.75:304.98   321.75:321.98
382.25:382.48   396.75:396.98   408.75:408.98   515.25:515.48
549.375:549.605 609.875:610.105 621.875:622.105 691.875:692.105
740.375:740.605 752.375:752.605 825:825.23  851.5:851.73866:866.23
955.5:955.73984.5:984.731042.5:1042.73  1071.625:1071.855
1115.125:1115.355   1158.625:1158.855   1221.625:1221.855
1248.125:1248.355   1274.625:1274.855   1374.25:1374.48 1398.25:1398.48
1427.25:1427.48 1500.25:1500.48 1529.25:1529.48 1558.25:1558.48
1611.375:1611.605   1666.875:1667.105   1698.375:1698.605
1715.375:1715.605   1773.375:1773.605   1833.875:1834.105   
1848.5:1848.73
1947.5:1947.73  1964.5:1964.73  1981.5:1981.73  1996:1996.23
2085.5:2085.73  2114.625:2114.855   2126.625:2126.855   
2138.625:2138.855
2288.625:2288.855   2317.625:2317.855   2334.625:2334.855   
2387.75:2387.98
2421.75:2421.98 2433.75:2433.98 2518.25:2518.48 2549.75:2549.98
2564.25:2564.48



Ah, thank you for the clarification.  When I've seen the '.wav' suffix  
used, it's usually indicated an audio file -- hence my confusion. I don't  
know the first thing about neuro-imaging, but a quick search revealed a  
few things. I presume you're using a program like  
http://cnl.web.arizona.edu/waver.htm to generate your .wav file?




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: OK to memoize re objects?

2009-09-21 Thread Ethan Furman

Nobody wrote:

On Mon, 21 Sep 2009 07:11:36 -0700, Ethan Furman wrote:



Looking in the code for re in 2.5:




_MAXCACHE = 100




On the other hand, I (a
re novice, to be sure) have only used between two to five in any one
program... it'll be a while before I hit _MAXCACHE!



Do you know how many REs import-ed modules are using? The cache isn't
reserved for __main__.



As a matter of fact, I haven't got a clue.  :-)

Fortunately, I always use .compile to save my re's.  Seems simpler to me 
that way.


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


Re: Plotting wav file

2009-09-21 Thread Maggie
On Sep 21, 3:07 pm, "Rami Chowdhury"  wrote:
> On Mon, 21 Sep 2009 11:58:30 -0700, Maggie  wrote:
> > What would be the best way to plot a small .wav file in python? If
> > there are any tutorials or sample code, I would really appreciate it!
>
> I'm sorry, what are you hoping to plot about the .wav file?
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" --
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)

.wav file was generated from .1D file that contained times of
occurrence of a stimulus within the experiment. The y-axis is the TR
and the x-axis is supposed to be the length of y. I am hoping to see
plot representation of .wav file so i can align it to time series fMRI
data via independent component analysis.
this is the sample .1D file that was converted into the .wav file --

2.625:2.855 46.125:46.355   92.125:92.355   150.125:150.355
179.125:179.355 239.625:239.855 304.75:304.98   321.75:321.98
382.25:382.48   396.75:396.98   408.75:408.98   515.25:515.48
549.375:549.605 609.875:610.105 621.875:622.105 691.875:692.105
740.375:740.605 752.375:752.605 825:825.23  851.5:851.73866:866.23
955.5:955.73984.5:984.731042.5:1042.73  1071.625:1071.855
1115.125:1115.355   1158.625:1158.855   1221.625:1221.855
1248.125:1248.355   1274.625:1274.855   1374.25:1374.48 1398.25:1398.48
1427.25:1427.48 1500.25:1500.48 1529.25:1529.48 1558.25:1558.48
1611.375:1611.605   1666.875:1667.105   1698.375:1698.605
1715.375:1715.605   1773.375:1773.605   1833.875:1834.105   
1848.5:1848.73
1947.5:1947.73  1964.5:1964.73  1981.5:1981.73  1996:1996.23
2085.5:2085.73  2114.625:2114.855   2126.625:2126.855   
2138.625:2138.855
2288.625:2288.855   2317.625:2317.855   2334.625:2334.855   
2387.75:2387.98
2421.75:2421.98 2433.75:2433.98 2518.25:2518.48 2549.75:2549.98
2564.25:2564.48

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


Re: Plotting wav file

2009-09-21 Thread Rami Chowdhury

On Mon, 21 Sep 2009 11:58:30 -0700, Maggie  wrote:


What would be the best way to plot a small .wav file in python? If
there are any tutorials or sample code, I would really appreciate it!


I'm sorry, what are you hoping to plot about the .wav file?


--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


socket send O(N**2) complexity

2009-09-21 Thread Zac Burns
The mysocket.mysend method given at
http://docs.python.org/howto/sockets.html has an (unwitting?) O(N**2)
complexity for long msg due to the string slicing.

I've been looking for a way to optimize this, but aside from a pure
python 'string slice view' that looks at the original string I can't
think of anything. Perhaps start and end keywords could be added to
send? I can't think of a reason for the end keyword,  but it would be
there for symmetry.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Plotting wav file

2009-09-21 Thread Maggie
What would be the best way to plot a small .wav file in python? If
there are any tutorials or sample code, I would really appreciate it!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-21 Thread David C Ullrich
On Sun, 20 Sep 2009 13:27:07 -0700, daggerdvm wrote:

> Write the definition of a function  twice , that receives an  int
> parameter and returns an  int that is twice the value of the parameter.
> 
> how can i do this

I don't think this can be done in Python.

Looking at the Subject line I thought your problem was
going to be easy: There's only one float type in Python,
so at least in most implementations simply converting to
float will suffice to "double" a variable.

But you actually want to return twice the value. I don't
see how to do that.









  


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


Re: entry widget won't validate

2009-09-21 Thread Mike
On Sep 21, 12:47 pm, Peter Otten <__pete...@web.de> wrote:
> Mike wrote:
> > I'm trying to arrange for an Entry widget to check whether its data
> > is all digits and whether the number represented is small enough.
> > The validate function seem to be called once at startup and not
> > afterwards:


> > The print statement run 3 times at startup.
> > Editing an Entry does not cause any printing.
> > Any ideas?
>
> Quotinghttp://www.tcl.tk/man/tcl8.5/TkCmd/entry.htm#M12:
>
> """
> In general, the textVariable and validateCommand can be dangerous to mix.
> Any problems have been overcome so that using the validateCommand will not
> interfere with the traditional behavior of the entry widget. Using the
> textVariable for read-only purposes will never cause problems. The danger
> comes when you try set the textVariable to something that the
> validateCommand would not accept, which causes validate to become none (the
> invalidCommand will not be triggered). The same happens when an error occurs
> evaluating the validateCommand.
> """
>
> You can verify that this is indeed your problem by changing the Levels.vc()
> method to always return True for the moment.

Returning True does seems to cause vc to be called more often.
I'm still not getting the data I want though.
The variable always gives me the pre-change string.
I gather I need to do something with "%P".
google gave me hints that I should use something called "register",
but I'm not at all clear on what I should do with them.
I don't know how to translate from Tcl to python.

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


Re: entry widget won't validate

2009-09-21 Thread Peter Otten
Mike wrote:

> I'm trying to arrange for an Entry widget to check whether its data
> is all digits and whether the number represented is small enough.
> The validate function seem to be called once at startup and not
> afterwards:
> 
> import sys, Tkinter, tkFileDialog, tkMessageBox
> 
> tk=Tkinter
> tkfd=tkFileDialog
> 
> ...
> class Functor :
> def __init__(self, func, data) :
> self.func=func
> self.data=data
> def __call__(self) : return self.func(self.data)
> 
> ...
> class Levels(tk.Frame) :
> def __init__(self, parent) :
> tk.Frame.__init__(self, parent)
> self.tv=[]
> for rgb in range(3) :
> self.tv.append(tk.StringVar())
> e=tk.Entry(self, textvariable=self.tv[rgb], width=5,
>validate='all',
>validatecommand=Functor(self.vc, self.tv
> [rgb]) )
> self.tv[rgb].set(str(levels_av_max))
> e.grid(row=2, column=rgb)
> lab=tk.Label(self, text='RGB'[rgb])
> lab.grid(row=1, column=rgb)
> doit=tk.Button(self, text='set levels', command=self.pushed)
> doit.grid(row=0, column=0, columnspan=3)
> 
> def vc(self, arg2=None) :
> print 'vc:', arg2.get()
> 
> The print statement run 3 times at startup.
> Editing an Entry does not cause any printing.
> Any ideas?

Quoting http://www.tcl.tk/man/tcl8.5/TkCmd/entry.htm#M12:

"""
In general, the textVariable and validateCommand can be dangerous to mix. 
Any problems have been overcome so that using the validateCommand will not 
interfere with the traditional behavior of the entry widget. Using the 
textVariable for read-only purposes will never cause problems. The danger 
comes when you try set the textVariable to something that the 
validateCommand would not accept, which causes validate to become none (the 
invalidCommand will not be triggered). The same happens when an error occurs 
evaluating the validateCommand.
"""

You can verify that this is indeed your problem by changing the Levels.vc() 
method to always return True for the moment.

Peter

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


entry widget won't validate

2009-09-21 Thread Mike
I'm trying to arrange for an Entry widget to check whether its data
is all digits and whether the number represented is small enough.
The validate function seem to be called once at startup and not
afterwards:

import sys, Tkinter, tkFileDialog, tkMessageBox

tk=Tkinter
tkfd=tkFileDialog

...
class Functor :
def __init__(self, func, data) :
self.func=func
self.data=data
def __call__(self) : return self.func(self.data)

...
class Levels(tk.Frame) :
def __init__(self, parent) :
tk.Frame.__init__(self, parent)
self.tv=[]
for rgb in range(3) :
self.tv.append(tk.StringVar())
e=tk.Entry(self, textvariable=self.tv[rgb], width=5,
   validate='all',
   validatecommand=Functor(self.vc, self.tv
[rgb]) )
self.tv[rgb].set(str(levels_av_max))
e.grid(row=2, column=rgb)
lab=tk.Label(self, text='RGB'[rgb])
lab.grid(row=1, column=rgb)
doit=tk.Button(self, text='set levels', command=self.pushed)
doit.grid(row=0, column=0, columnspan=3)

def vc(self, arg2=None) :
print 'vc:', arg2.get()

The print statement run 3 times at startup.
Editing an Entry does not cause any printing.
Any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-deprecated equivalent of rfc822.AddressList

2009-09-21 Thread Aahz
In article ,
Jason Tackaberry   wrote:
>On Wed, 2009-09-16 at 14:49 -0400, Jason Tackaberry wrote:
>> Since the rfc822 module was removed in Python 3, and is deprecated in
>> 2.3, I am obviously trying to avoid using it.
>> 
>> But I'm having a hard time finding an equivalent to rfc822.AddressList
>> in the email module, which I want to use to parse a _list_ of addresses:
>[...]
>> Is there some non-deprecated method I can use to parse an RFC 2822
>> address list?
>
>No takers?  Should I file a bug?

Maybe try email-...@python.org?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"I won't accept a model of the universe in which free will, omniscient
gods, and atheism are simultaneously true."  --M
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing object between classes

2009-09-21 Thread Jean-Michel Pichavant

daved170 wrote:

On Sep 21, 1:44 pm, Duncan Booth  wrote:
  

daved170  wrote:


Hi everybody,
I built my owen log obj as a class.
I'm passing it to another object (actually to a thread).
When I run my app it raise error at the line when I'm using that log
obj. is there any problem with the concept of passing object as I do
it?
How can I do that?
  
class A:

def foo1:
myLog = cLog()
myYhread = cThread(myLog)
myThread.start()
  
class cThread:

def __init__(self,in_myLog):
sel.LogObj = in_myLog
  
def run():

   sel.LogObj.writeLine("HI")
  
thanks

Dave
  

Please always post real code and state the exact error you get. That will
maximise the chance that you get a useful answer.

The code you posted will fail for numerous reasons and I can't guess
whether you have a problem with indentation, a problem because you
misspelled 'self' as 'sel', or because you missed out the 'self' parameter
altogether on a method, or perhaps your LogObj simply doesn't have a
writeLine method.

--
Duncan Boothhttp://kupuguy.blogspot.com- Hide quoted text -

- Show quoted text -



Hi Duncan,
You are right, I should have put the entire code but my question was
more theroretical and I know that the code that I posted won't work.

Let me simplified my question, I need to be able to write to the same
log file from different classes. and even more, from different
threads.
Is there any existing python Log object that do so? I no, I created my
own Log object that only open file and write a line to it, how can I
make it be global? Should I use it as a static object? will it work?
(offcurse in the case of the threads I'll use utex)

Thanks again,
DaveD
  

I have a theoretical answer to your theoretical question :

Use the standard python module logging for logging activities.
http://docs.python.org/library/logging.html

It's very powerful, standard, thread safe and time-saving.

cheers,

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


Re: recommendation for webapp testing?

2009-09-21 Thread Aahz
In article <2053e5e2-763e-44fb-854e-c17204518...@z34g2000vbl.googlegroups.com>,
Schif Schaf   wrote:
>
>I need to do some basic website testing (log into account, add item to
>cart, fill out and submit forms, check out, etc.). What modules would
>be good to use for webapp testing like this?

Windmill is an option, but I haven't tried it myself; Selenium is good.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"I won't accept a model of the universe in which free will, omniscient
gods, and atheism are simultaneously true."  --M
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OK to memoize re objects?

2009-09-21 Thread Nobody
On Mon, 21 Sep 2009 07:11:36 -0700, Ethan Furman wrote:

> Looking in the code for re in 2.5:

> _MAXCACHE = 100

> On the other hand, I (a
> re novice, to be sure) have only used between two to five in any one
> program... it'll be a while before I hit _MAXCACHE!

Do you know how many REs import-ed modules are using? The cache isn't
reserved for __main__.

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


Re: Comparison of parsers in python?

2009-09-21 Thread Nobody
On Sat, 19 Sep 2009 13:21:58 -0700, Peng Yu wrote:

> I did a google search and found various parser in python that can be
> used to parse different files in various situation. I don't see a page
> that summarizes and compares all the available parsers in python, from
> simple and easy-to-use ones to complex and powerful ones.
> 
> I am wondering if somebody could list all the available parsers and
> compare them.

I have a similar question.

What I want: a tokeniser generator which can take a lex-style grammar (not
necessarily lex syntax, but a set of token specifications defined by
REs, BNF, or whatever), generate a DFA, then run the DFA on sequences of
bytes. It must allow the syntax to be defined at run-time.

What I don't want: anything written by someone who doesn't understand the
field (i.e. anything which doesn't use a DFA).

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


Re: Granularity of OSError

2009-09-21 Thread kj
In  MRAB 
 writes:

>kj wrote:
>> In  MRAB 
>>  writes:
>> 
>>> If, for example, you're
>>> going to copy a file, it's a good idea to check beforehand that there's
>>> enough space available for the copy.
>> 
>> How do you do that?
>> 
>There's os.statvfs(...), although that's Unix only.

Thanks!

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


Re: Non-deprecated equivalent of rfc822.AddressList

2009-09-21 Thread Jason Tackaberry
On Wed, 2009-09-16 at 14:49 -0400, Jason Tackaberry wrote:
> Since the rfc822 module was removed in Python 3, and is deprecated in
> 2.3, I am obviously trying to avoid using it.
> 
> But I'm having a hard time finding an equivalent to rfc822.AddressList
> in the email module, which I want to use to parse a _list_ of addresses:
[...]
> Is there some non-deprecated method I can use to parse an RFC 2822
> address list?

No takers?  Should I file a bug?

Cheers,
Jason.

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


Re: OK to memoize re objects?

2009-09-21 Thread Ethan Furman

kj wrote:

In  Robert Kern 
 writes:



kj wrote:


My Python code is filled with assignments of regexp objects to
globals variables at the top level; e.g.:

_spam_re = re.compile('^(?:ham|eggs)$', re.I)

Don't like it.  My Perl-pickled brain wishes that re.compile was
a memoizing method, so that I could use it anywhere, even inside
tight loops, without ever having to worry about the overhead of
regexp compilation.




Just use re.search(), etc. They already memoize the compiled regex objects.



Thanks.

I find the docs are pretty confusing on this point.  They first
make the point of noting that pre-compiling regular expressions is
more efficient, and then *immediately* shoot down this point by
saying that one need not worry about pre-compiling in most cases.

From the docs:


...using compile() and saving the resulting regular expression
object for reuse is more efficient when the expression will be
used several times in a single program.

Note: The compiled versions of the most recent patterns passed
to re.match(), re.search() or re.compile() are cached, so
programs that use only a few regular expressions at a time
needn't worry about compiling regular expressions.

Honestly I don't know what to make of this...  I would love to see
an example in which re.compile was unequivocally preferable, to
really understand what the docs are saying here...

kynn


Looking in the code for re in 2.5:
.
.
.
_MAXCACHE = 100
.
.
.
if len(_cache) >= _MAXCACHE:
_cache.clear()
.
.
.

so when you fill up, you lose the entire cache.  On the other hand, I (a 
re novice, to be sure) have only used between two to five in any one 
program... it'll be a while before I hit _MAXCACHE!


~Ethan~

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


Re: passing object between classes

2009-09-21 Thread daved170
On Sep 21, 1:44 pm, Duncan Booth  wrote:
> daved170  wrote:
> > Hi everybody,
> > I built my owen log obj as a class.
> > I'm passing it to another object (actually to a thread).
> > When I run my app it raise error at the line when I'm using that log
> > obj. is there any problem with the concept of passing object as I do
> > it?
> > How can I do that?
>
> > class A:
> > def foo1:
> >     myLog = cLog()
> >     myYhread = cThread(myLog)
> >     myThread.start()
>
> > class cThread:
> > def __init__(self,in_myLog):
> >     sel.LogObj = in_myLog
>
> > def run():
> >    sel.LogObj.writeLine("HI")
>
> > thanks
> > Dave
>
> Please always post real code and state the exact error you get. That will
> maximise the chance that you get a useful answer.
>
> The code you posted will fail for numerous reasons and I can't guess
> whether you have a problem with indentation, a problem because you
> misspelled 'self' as 'sel', or because you missed out the 'self' parameter
> altogether on a method, or perhaps your LogObj simply doesn't have a
> writeLine method.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com- Hide quoted text -
>
> - Show quoted text -

Hi Duncan,
You are right, I should have put the entire code but my question was
more theroretical and I know that the code that I posted won't work.

Let me simplified my question, I need to be able to write to the same
log file from different classes. and even more, from different
threads.
Is there any existing python Log object that do so? I no, I created my
own Log object that only open file and write a line to it, how can I
make it be global? Should I use it as a static object? will it work?
(offcurse in the case of the threads I'll use utex)

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


Re: OK to memoize re objects?

2009-09-21 Thread kj
In  Robert Kern 
 writes:

>kj wrote:
>> 
>> My Python code is filled with assignments of regexp objects to
>> globals variables at the top level; e.g.:
>> 
>> _spam_re = re.compile('^(?:ham|eggs)$', re.I)
>> 
>> Don't like it.  My Perl-pickled brain wishes that re.compile was
>> a memoizing method, so that I could use it anywhere, even inside
>> tight loops, without ever having to worry about the overhead of
>> regexp compilation.

>Just use re.search(), etc. They already memoize the compiled regex objects.

Thanks.

I find the docs are pretty confusing on this point.  They first
make the point of noting that pre-compiling regular expressions is
more efficient, and then *immediately* shoot down this point by
saying that one need not worry about pre-compiling in most cases.
>From the docs:

...using compile() and saving the resulting regular expression
object for reuse is more efficient when the expression will be
used several times in a single program.

Note: The compiled versions of the most recent patterns passed
to re.match(), re.search() or re.compile() are cached, so
programs that use only a few regular expressions at a time
needn't worry about compiling regular expressions.

Honestly I don't know what to make of this...  I would love to see
an example in which re.compile was unequivocally preferable, to
really understand what the docs are saying here...

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


Re: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Laszlo Nagy

Christian Heimes írta:

Laszlo Nagy wrote:
  
The building and installation went find. But I cannot "import 
kinterbasdb" because I get a "DLL load failed" error. I figured out that 
has something to do with msvcr90 and "_ftime". Can you please give me 
some advice how to solve this problem?



I know from experience that it's sometimes hard to compile Python
extensions with MinGW32. Have you tried the official builds from the new
download page  http://www.firebirdsql.org/index.php?op=devel&sub=python ?
  
Haven't because I have to use Firebird 1.5. There is no official binary 
distribution for firebird 1.5 + python 2.6. (I'll try to build this with 
MSVC later today).


Thank you


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


Re: Python: automate input to MySQL query

2009-09-21 Thread Philip Semanchuk


On Sep 21, 2009, at 5:18 AM, Threader Slash wrote:


Hi Everybody...

I have a query that works as follows:

Code:

db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
(traveler INNER JOIN takenvaccine ON traveler.travelerID =
takenvaccine.travelerID)
   INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
   INNER JOIN requiredvaccine ON
vaccine.vaccineID=requiredvaccine.requiredvaccineID
   INNER JOIN city ON requiredvaccine.cityID = city.cityID
WHERE traveler.travelerFirstName = 'John'""")

The output gives me all vaccines taken by a given employee. To allow  
the
user to choose different names when running the system, I am trying  
to use a

variable, named *person*:

Code:

person = "John"

db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
(traveler INNER JOIN takenvaccine ON traveler.travelerID =
takenvaccine.travelerID)
   INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
   INNER JOIN requiredvaccine ON
vaccine.vaccineID=requiredvaccine.requiredvaccineID
   INNER JOIN city ON requiredvaccine.cityID = city.cityID
WHERE traveler.travelerFirstName = 'person'""")

Then I run the query inside my python program. The first version  
without
variable works fine. But the second, using variable, doesn't give me  
any
output. What I am missing here about the python variable sintaxe to  
make the

MySQL work with variable ... Any suggestion?


In your second query you've got "person" hardcoded as a string. You're  
looking for a traveler with the actual first name of person.


Change this line:

WHERE traveler.travelerFirstName = 'person'""")


to this:

WHERE traveler.travelerFirstName = %s""")


and pass person as a list of params to db.query(). Something like this  
should work:


sql = """SELECT blah blah blah WHERE traveler.travelerFirstName = %s"""
db.query(sql, [person])

See the Python DB API documentation for specifics. This might look  
like the same thing as string interpolation, but it isn't.


Good luck
Philip


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


Re: raise errors

2009-09-21 Thread Benjamin Kaplan
On Mon, Sep 21, 2009 at 5:17 AM, daved170  wrote:
> Hi everybody,
> I need help with exceptions raising.
> My goal is to print at the outer functions all the errors including
> the most inner one.
>
> For example:
>
> def foo1(self):
>   try:
>        foo2()
>   except ? :
>         print "outer Err at foo1" + ??
>
> def foo2(self):
>   try:
>        error occured
>   except ? :
>         raise "inner Err at foo2"
>
>
> the ? remarks that I have no idea what to use.
>
> I would like the print to be : outer Err at foo1 , inner Err at foo1
>
> thanks
> daved
> --

First of all, what version of Python are you using? String exceptions
are deprecated in Python 2.5 and removed in 2.6. You should switch to
using Exceptions. In particular, you'll probably want to subclass
Exception.

String exceptions use the syntax "except 'exception string':" which
means you need to know the string ahead of time. You'll instead want
to do this.

def foo1() :
   try :
 foo2()
   except Exception, e :
  print "outer exception at foo1, %s" % str(e)

def foo2() :
   raise Exception("inner exception at foo2")

In Python 3.x, the syntax changed to "except Exception as e" but that
syntax isn't available in versions prior to 2.6


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


Re: passing object between classes

2009-09-21 Thread Duncan Booth
daved170  wrote:

> Hi everybody,
> I built my owen log obj as a class.
> I'm passing it to another object (actually to a thread).
> When I run my app it raise error at the line when I'm using that log
> obj. is there any problem with the concept of passing object as I do
> it?
> How can I do that?
> 
> class A:
> def foo1:
> myLog = cLog()
> myYhread = cThread(myLog)
> myThread.start()
> 
> class cThread:
> def __init__(self,in_myLog):
> sel.LogObj = in_myLog
> 
> def run():
>sel.LogObj.writeLine("HI")
> 
> thanks
> Dave
> 

Please always post real code and state the exact error you get. That will 
maximise the chance that you get a useful answer.

The code you posted will fail for numerous reasons and I can't guess 
whether you have a problem with indentation, a problem because you 
misspelled 'self' as 'sel', or because you missed out the 'self' parameter 
altogether on a method, or perhaps your LogObj simply doesn't have a 
writeLine method.



-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Athens Python User Group - Meeting September 9, 2009, 19:00.

2009-09-21 Thread Orestis Markou

Blogged about the results of the meeting here:

http://orestis.gr/blog/2009/09/21/athens-python-ug-1st-meeting-results/

Also announcing a dedicated maling list: 
http://mail.python.org/mailman/listinfo/pyathens

Orestis


On 04 Σεπ 2009, at 7:42 μ.μ., Orestis Markou wrote:


== Announcing the 1st meeting of the Athens Python User Group ==

If you live near Athens, Greece and are interested in meeting fellow  
Python programmers, meet us for a friendly chat at the  
Eleftheroudakis Bookstore café, on Wednesday 9 September, 7:00pm.


If you plan to attend, please add a comment here: 
http://orestis.gr/blog/2009/09/01/athens-python-user-group/

Orestis




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


passing object between classes

2009-09-21 Thread daved170
Hi everybody,
I built my owen log obj as a class.
I'm passing it to another object (actually to a thread).
When I run my app it raise error at the line when I'm using that log
obj. is there any problem with the concept of passing object as I do
it?
How can I do that?

class A:
def foo1:
myLog = cLog()
myYhread = cThread(myLog)
myThread.start()

class cThread:
def __init__(self,in_myLog):
sel.LogObj = in_myLog

def run():
   sel.LogObj.writeLine("HI")

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


Re: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Christian Heimes
Laszlo Nagy wrote:
> The building and installation went find. But I cannot "import 
> kinterbasdb" because I get a "DLL load failed" error. I figured out that 
> has something to do with msvcr90 and "_ftime". Can you please give me 
> some advice how to solve this problem?

I know from experience that it's sometimes hard to compile Python
extensions with MinGW32. Have you tried the official builds from the new
download page  http://www.firebirdsql.org/index.php?op=devel&sub=python ?

Christian

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


Re: [SQL] Pick random rows from SELECT?

2009-09-21 Thread Peter Otten
Gilles Ganault wrote:

> I have a working Python script that SELECTs rows from a database to
> fetch a company's name from a web-based database.
> 
> Since this list is quite big and the site is the bottleneck, I'd like
> to run multiple instances of this script, and figured a solution would
> be to pick rows at random from the dataset, check in my local database
> if this item has already been taken care of, and if not, download
> details from the remote web site.
> 
> If someone's done this before, should I perform the randomization in
> the SQL query (SQLite using the APSW wrapper
> http://code.google.com/p/apsw/), or in Python?
> 
> Thank you.
> 
> Here's some simplified code:
> 
> sql = 'SELECT id,label FROM companies WHERE activity=1'
> rows=list(cursor.execute(sql))
> for row in rows:
> id = row[0]
> label = row[1]
> 
> print strftime("%H:%M")
> url = "http://www.acme.com/details.php?id=%s"; % id
> req = urllib2.Request(url, None, headers)
> response = urllib2.urlopen(req).read()
> 
> name = re_name.search(response)
> if name:
> name = name.group(1)
> sql = 'UPDATE companies SET name=? WHERE id=?'
> cursor.execute(sql, (name,id) )
 
I don't think you need to randomize the requests. Instead you could control 
a pool of worker processes using

http://docs.python.org/library/multiprocessing.html

Peter

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


Re: raise errors

2009-09-21 Thread Peter Otten
daved170 wrote:

> I need help with exceptions raising.
> My goal is to print at the outer functions all the errors including
> the most inner one.
> 
> For example:
> 
> def foo1(self):
>try:
> foo2()
>except ? :
>  print "outer Err at foo1" + ??
> 
> def foo2(self):
>try:
> error occured
>except ? :
>  raise "inner Err at foo2"
> 
> 
> the ? remarks that I have no idea what to use.
> 
> I would like the print to be : outer Err at foo1 , inner Err at foo1

Have a look at the traceback module. Example:

>>> def foo():
... try:
... oops
... except:
... traceback.print_exc()
... raise
...
>>> def bar():
... try:
... foo()
... except:
... traceback.print_exc()
...
>>> import traceback
>>> bar()
Traceback (most recent call last):
  File "", line 3, in foo
NameError: global name 'oops' is not defined
Traceback (most recent call last):
  File "", line 3, in bar
  File "", line 3, in foo
NameError: global name 'oops' is not defined

Peter

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


Re: Is there a concerted effort afoot to improve the Python Wiki?

2009-09-21 Thread Paul Boddie
On 21 Sep, 02:52, s...@pobox.com wrote:
> I've noticed over the past few weeks a huge increase in the frequency of
> edits in the Python wiki.  Many of those are due to Carl Trachte's work on
> non-English pages about Python.  There are plenty of other pages going under
> the knife as well though.  Is there some community movement people are aware
> of to wrangle the wiki into better shape?

I see that the SiteImprovements page has seen some action:

http://wiki.python.org/moin/SiteImprovements

I've added a few things which have been on the "to do" list for a
while now.

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


Re: raise errors

2009-09-21 Thread Ulrich Eckhardt
daved170 wrote:
> I need help with exceptions raising.
> My goal is to print at the outer functions all the errors including
> the most inner one.
> 
> For example:
> 
> def foo1(self):
>try:
> foo2()
>except ? :
>  print "outer Err at foo1" + ??
> 
> def foo2(self):
>try:
> error occured
>except ? :
>  raise "inner Err at foo2"
> 
> 
> the ? remarks that I have no idea what to use.
> 
> I would like the print to be : outer Err at foo1 , inner Err at foo1

Take a look at the builtin debugger facility, i.e. 'import pdb'. There, you
have a traceback module which might already give you what you want.

One more advise though: Do not catch exceptions you don't handle! Make sure
they can pass through your code without hurting anything and then catch and
log them in a place where you actually can handle them. In particular,
don't wrap each and every tiny morsel of code into try/except handlers as
you would (have to) do if you were using return values.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: I look for proxy cache like apt-proxy (for Debian Package) but for python eggs package…

2009-09-21 Thread KLEIN Stéphane
Le Sun, 20 Sep 2009 18:33:10 +0200, Klein Stéphane a écrit :

> Hi,
> 
> I look for a tools to do proxy cache like apt-proxy (for Debian Package)
> but for python eggs package.
> 
> Can a easy-install option perform this feature ?

I found somethings to do that :

http://pypi.python.org/pypi/collective.eggproxy/0.3.1

Regards,
Stephane

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


raise errors

2009-09-21 Thread daved170
Hi everybody,
I need help with exceptions raising.
My goal is to print at the outer functions all the errors including
the most inner one.

For example:

def foo1(self):
   try:
foo2()
   except ? :
 print "outer Err at foo1" + ??

def foo2(self):
   try:
error occured
   except ? :
 raise "inner Err at foo2"


the ? remarks that I have no idea what to use.

I would like the print to be : outer Err at foo1 , inner Err at foo1

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


Python: automate input to MySQL query

2009-09-21 Thread Threader Slash
Hi Everybody...

I have a query that works as follows:

 Code:

db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
(traveler INNER JOIN takenvaccine ON traveler.travelerID =
takenvaccine.travelerID)
INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
INNER JOIN requiredvaccine ON
vaccine.vaccineID=requiredvaccine.requiredvaccineID
INNER JOIN city ON requiredvaccine.cityID = city.cityID
WHERE traveler.travelerFirstName = 'John'""")

The output gives me all vaccines taken by a given employee. To allow the
user to choose different names when running the system, I am trying to use a
variable, named *person*:

 Code:

person = "John"

db.query("""SELECT traveler.travelerFirstName,vaccine.vaccineName from
(traveler INNER JOIN takenvaccine ON traveler.travelerID =
takenvaccine.travelerID)
INNER JOIN vaccine ON takenvaccine.vaccineID=vaccine.vaccineID
INNER JOIN requiredvaccine ON
vaccine.vaccineID=requiredvaccine.requiredvaccineID
INNER JOIN city ON requiredvaccine.cityID = city.cityID
WHERE traveler.travelerFirstName = 'person'""")

Then I run the query inside my python program. The first version without
variable works fine. But the second, using variable, doesn't give me any
output. What I am missing here about the python variable sintaxe to make the
MySQL work with variable ... Any suggestion?

All comments or suggestions are highly appreciated!

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


Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Threader Slash
I have spent two week working with MinGW. The conclusion I came after a lot
of headaches and making the project getting late is: MinGW doesn't work
properly on MS Windows -- there are many conflicting variables and functions
with similar names on MinGW libs and MS Libs, e.g. windows.h, etc, etc. My
suggestion... avoid it. If you really need a C compiler to work on MS, try
anything else.



--  --
From: Laszlo Nagy 
To: "python-list (General)" 
Date: Mon, 21 Sep 2009 08:53:06 +0430
Subject: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed
This is what I did so far:

#1. Install Python 2.6, Firebird 1.5 server (with libs and headers), egenix
mx base and mingw C compiler
#2. put "c:\MinGW\bin"  on the PATH (or wherever it is)
#3. extract kinterbasdb source to a temp folder
#4. hack setup.cfg. Change the build section:

[build]
compiler=mingw32

#5. hack setup.py

Replace this:
  customCompilerName = 'msvc'
With this:
  customCompilerName = 'mingw32-gcc'

#6. run "python setup.py install"

The building and installation went find. But I cannot "import kinterbasdb"
because I get a "DLL load failed" error. I figured out that has something to
do with msvcr90 and "_ftime". Can you please give me some advice how to
solve this problem?

Thanks,

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


Re: easy question, how to double a variable

2009-09-21 Thread Tim Chase

Steven D'Aprano wrote:

Write the definition of a function  twice , that receives an  int
parameter and returns an  int that is twice the value of the parameter.

how can i do this


Yes, that certainly is an easy question.

Here's my solution:

class MultiplierFactory(object):

[snip a marvel of abstruse code]


twice = MultiplierFactory(2)()

It needs some error checking, but otherwise should work.


Tsk...no docstrings?  no unit tests or doctests?  no parameter 
validation?  no copyright notice?  no revision-tracking nor 
authorship comments?  what sort of bad example are you setting 
here?  You want this kid to fail?!  With such poor instruction, 
it's no wonder the economy is going to shambles, the educational 
system is falling apart, there's global warming, terrorism, spam, 
and reality television. Your piteous code make Paris Hilton cry. 
[shakes head in disappointment]


;-)

-tkc





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


[SQL] Pick random rows from SELECT?

2009-09-21 Thread Gilles Ganault
Hello

I have a working Python script that SELECTs rows from a database to
fetch a company's name from a web-based database.

Since this list is quite big and the site is the bottleneck, I'd like
to run multiple instances of this script, and figured a solution would
be to pick rows at random from the dataset, check in my local database
if this item has already been taken care of, and if not, download
details from the remote web site.

If someone's done this before, should I perform the randomization in
the SQL query (SQLite using the APSW wrapper
http://code.google.com/p/apsw/), or in Python?

Thank you.

Here's some simplified code:

sql = 'SELECT id,label FROM companies WHERE activity=1'
rows=list(cursor.execute(sql))
for row in rows:
id = row[0]
label = row[1]

print strftime("%H:%M")
url = "http://www.acme.com/details.php?id=%s"; % id
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()

name = re_name.search(response)
if name:
name = name.group(1)
sql = 'UPDATE companies SET name=? WHERE id=?'
cursor.execute(sql, (name,id) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension vs generator expression memory allocation

2009-09-21 Thread candide
Duncan Booth a écrit :

> Why are you slicing the result of range? Why not just pass appropriate 
> arguments to range or xrange directly?
> 

Why ? Guilty ignorance ;)


> def f(a,b,m):
>   return xrange((a+m-1)//m*m, b, m)
> 


Nice code, furthermore giving the best execution time, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An assessment of the Unicode standard

2009-09-21 Thread Mel
Dennis Lee Bieber wrote:

> A one-eyed, one-horned, flying purple people eater?
> 
> {Which brings up the confusing question... Is the eater purple, or does
> it eat purple people (which is why it is so rare... it only eats people
> caught in the last stages of suffocation )}

Since we're spending so much time -- from the text (with Pythonic nested 
quotes:)

'''I said "Tell me Mister People Eater, what's your line?"
He said "Eatin' purple people, and it sure is fine."'''


Mel.

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


Pythons in Florida (training next month)

2009-09-21 Thread Mark Lutz
Don't miss your chance to attend our first Florida
Python training session next month.  This 3-day class
is being held October 20-22, in Sarasota, Florida.
It is open to both individual and group enrollments.

For more details on the class, as well as registration
instructions, please visit the class web page:

http://home.earthlink.net/~python-training/2009-public-classes.htm

If you are unable to attend in October, our next
Sarasota class is already scheduled for January 19-21.

Thanks, and we hope to see you in sunny Florida soon.

--Mark Lutz at Python Training Services


*Prerequisite reading:
http://edition.cnn.com/2009/US/03/30/python.patrol/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)

2009-09-21 Thread Ben Morrow
[This is not a Perl question. F'ups set to c.l.python.]

Quoth Schif Schaf :
> The other day I needed to convert a date like "August 2009" into a
> "seconds-since-epoch" value (this would be for the first day of that
> month, at the first second of that day).

Note that this is not unique: you need to at least specify a time zone.

Ben

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


Re: testing code in python source package

2009-09-21 Thread Ben Finney
Peng Yu  writes:

> I'm wondering if the development of python is test driven. If it is,
> where in the Python-2.6.2 source directory is the test code for the
> modules in ./Lib?

A great majority of your many questions in this forum are already
answered in the available documentation online. You seem to leap
immediately to asking here rather than demonstrating that you have first
tried and failed to find answers in existing documentation.

You would save yourself a lot of time, not to mention social capital, if
you would invest the effort to learn how to research your answers at
http://docs.python.org/> and http://www.python.org/dev/>.

-- 
 \  “Any intelligent fool can make things bigger and more complex… |
  `\It takes a touch of genius – and a lot of courage – to move in |
_o__)the opposite direction.” —Albert Einstein |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension vs generator expression memory allocation

2009-09-21 Thread Duncan Booth
candide  wrote:

> Each of the following two functions mult1() and mult2() solves the
> question :
> 
> 
> # -
> def mult1(a,b,m):
> return (x for x in range(a,b)[(m-a%m)%m:b:m])
> 
> def mult2(a,b,m):
> return range(a,b)[(m-a%m)%m:b:m]
> # -
> 
> 
Why are you slicing the result of range? Why not just pass appropriate 
arguments to range or xrange directly?

def f(a,b,m):
return xrange((a+m-1)//m*m, b, m)

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


Re: Substitute for KConfig in Qt4

2009-09-21 Thread nusch
On Sep 19, 3:53 am, David Boddie  wrote:
> On Thursday 17 September 2009 13:04, nusch wrote:
>
> > I want to remove pyKDE dependencies from my app to make it pure PyQt.
> > What will be the best substitute for KConfig?
>
> What exactly do you use KConfig for in your application?
>
> David

e.g storing dock window positions, fields choosen in QComboBox etc.
But I Dont want to use normal config files for it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re:OT - people eaters - was: An assessment of the Unicode standard

2009-09-21 Thread Cousin Stanley


> On Friday 18 September 2009 06:39:57 Dennis Lee Bieber wrote:
>
>>  A one-eyed, one-horned, flying purple people eater?
>>
>> {Which brings up the confusing question... Is the eater purple, or does
>> it eat purple people (which is why it is so rare... it only eats people
>> caught in the last stages of suffocation )}
>
> Snap (sort of). 
> Does anybody know where the concept of the purple people eater comes from?
> I mean is there a children's book or something?
>
> - Hendrik

  Shep Wooley ( 1958 )
  http://www.youtube.com/watch?v=X9H_cI_WCnE

-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


SQLObject 0.11.1

2009-09-21 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.11.1, a minor bugfix release of 0.11 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.11.1

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.11.0
-

* Fixed a bug: Sybase tables with identity column fire two identity_inserts.

* Fixed a bug: q.startswith(), q.contains() and q.endswith() escape (with a
  backslash) all special characters (backslashes, underscores and percent
  signs).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/p...@phd.pp.ru
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Paul Rudin
Laszlo Nagy  writes:

>>> The building and installation went find. But I cannot "import kinterbasdb"
>>> because I get a "DLL load failed" error. I figured out that has something to
>>> do with msvcr90 and "_ftime". Can you please give me some advice how to
>>> solve this problem?
>>> 
>>
>> Download Microsoft Visual C++.2008 Express Edition
>>   
>
> Its license does not allow us to create services for internet if we
> charge fees. At least this is what I was told. Does this mean that
> using kinterbasdb (compiled with MSVC express) I'm forbidden to write
> commercial internet services? :-s

Is the license for the SDK (which includes the command line c++
compiler) the same? You only need the command line compiler, not the gui
that comes with the express edition.

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


Re: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Gerhard Häring
Laszlo Nagy wrote:
> 
>>> The building and installation went find. But I cannot "import
>>> kinterbasdb"
>>> because I get a "DLL load failed" error. I figured out that has
>>> something to
>>> do with msvcr90 and "_ftime". Can you please give me some advice how to
>>> solve this problem?
>>> 
>>
>> Download Microsoft Visual C++.2008 Express Edition
>>   
> 
> Its license does not allow us to create services for internet if we
> charge fees. At least this is what I was told. Does this mean that using
> kinterbasdb (compiled with MSVC express) I'm forbidden to write
> commercial internet services? :-s

I see three options:

1) Ask a laywer.

2) Download the MSVC express compiled version from somewhere else. ;
adhere to the kinterbasdb license; let MS license issues not be your
problem - or at least now having "plausible deniability".

3) F*ck license issues. You're not redistributing anything, who will
know what software compiled with which compilers you're using?

Well, or just use mingw.

-- Gerhard

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


Re: easy question, how to double a variable

2009-09-21 Thread Carl Banks
On Sep 20, 1:27 pm, daggerdvm  wrote:
>  Write the definition of a function  twice , that receives an  int
> parameter and returns an  int that is twice the value of the
> parameter.
>
> how can i do this

Simple:

Once you define the function, "copy" it using your editor commands,
then "paste" it right below the original.


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


Re: Python-list Digest, Vol 72, Issue 210

2009-09-21 Thread Threader Slash
Hi Roman,

I am using MySQL with Python -- in Windows XP for a contract.

I hope my comments can be useful:

When dealing with installation on Python, I noticed that tiny details can
make a difference -- e.g. first I installed the latest version of Python
3.x, but it did not attend what I am looking for: the need to put MySQLdb
and Python to communicate together.

Then what I need to do was to downgrade the Python version to Python 2.5
which works nicely with the MySQLdb2.5 package. I also installed the
ActivePython-2.6 to get it working with win32com. The ActivePython looks to
me a more complete version of Python compiler.

Then, in the sequence I configured it to compile using Eclipse IDE.

Threader.

-- Forwarded message --
From: Roman Gorbunov 
To: python-list@python.org
Date: Sat, 19 Sep 2009 08:18:31 -0700 (PDT)
Subject: How to install pysqlite?
Hi all,

I am trying to install pysqlite (Python interface to the SQLite). I
downloaded the file with the package (pysqlite-2.5.5.tar.gz). And I
did the following:

gunzip pysqlite-2.5.5.tar.gz
tar xvf pysqlite-2.5.5.tar
cd pysqlite-2.5.5
python setup.py install

At the last step I have a problem. I get the following error message:
error: command 'gcc' failed with exit status 1

I found that other peoples also had this problem. For example here:
http://forums.opensuse.org/applications/400363-gcc-fails-during-pysqlite-install.html

As far as I understood in the person had a problem because sqlite2 was
not installed. But in my case, I have sqlite3 (I can run it from
command line).

May be I should change some paths in "setup.cfg"? At the moment I have
there:
#define=
#include_dirs=/usr/local/include
#library_dirs=/usr/local/lib
libraries=sqlite3
define=SQLITE_OMIT_LOAD_EXTENSION

And if I type "which sqlite3" I get:
/usr/bin/sqlite3

Can anybody pleas help me with that problem.

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


Re: explicit call to __init__(self) in subclass needed?

2009-09-21 Thread Bruno Desthuilliers

Andrew MacKeith a écrit :



Bruno Desthuilliers wrote:

Andrew MacKeith a écrit :

I create a class like this in Python-2.6

 >>> class Y(str):
...   def __init__(self, s):
...  pass
...
 >>> y = Y('giraffe')
 >>> y
'giraffe'
 >>>

How does the base class (str) get initialized with the value passed 
to Y.__init__() ?


It happens in the __new__ method (which is the proper "constructor")

class Y(str):
def __new__(cls, value, foo="foo"):
instance = str.__new__(cls, value)
instance.foo = foo
return instance

def __repr__(self):
return "<%s(%s, %s)>" % (type(self).__name__, self, self.foo)



Is this behavior specific to the str type,  or do base classes not need
to be explicitly initialized?


When you override a method in a derived class, it's your 
responsability to call on the parent(s) class(es) implementation. 
__init__ is not an exception to that rule. The point is that since 
__init__ works by mutating the newly created instance, it makes no 
sense to have a distinct __init__ for immutable types - which have 
their "value" set once for all at creation time.


Thanks for the explanation, Bruno.

I have been successfully using a class derived from str, and in that
class I add a lot of extra data to the derived class instance in the
__init__ method of the derived class, so it is possible to mutate the
derived class __dict__, even if the base class data remains immutable.


Indeed. What I said was that Python builtins immutable types didn't use 
the initializer, not that you couldn't use an initializer in derived 
classes. I gave an example using __new__ because, quite often when 
subclassing immutable types, peoples want to access the initial value 
_before_ the call to the base class.




See example below.

The __init__ must have the same arguments as the base class.


The initializer (__init__) must have the same arguments as the 
constructor (__new__). This is true for all and every classes.


(snip)



But you can get bitten if you do something that returns a new object

 >>> y += 'Tail'
 >>> y
'ParrotTail'
 >>> y.color
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'color'
 >>>
 >>> y.__class__

 >>>


You need to override a couple other __magic_methods__ to make this work. 
You'll find relevant documentation here:


http://docs.python.org/reference/datamodel.html#special-method-names

In the above case, you want to override at least the __add__ method:

class Y(str):
def __new__(cls, value, foo="foo"):
instance = str.__new__(cls, value)
instance.foo = foo
return instance

def __repr__(self):
return "<%s(%s, %s)>" % (type(self).__name__, self, self.foo)

def __add__(self, other):
return type(self)(str(self) + other, self.foo)

>>> y = Y("foo", foo="bar")
>>> y

>>> y += "baaz"
>>> y

>>>

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


Re: Compile kinterbasdb with mingw32 and python 2.6 - DLL load failed

2009-09-21 Thread Laszlo Nagy



The building and installation went find. But I cannot "import kinterbasdb"
because I get a "DLL load failed" error. I figured out that has something to
do with msvcr90 and "_ftime". Can you please give me some advice how to
solve this problem?



Download Microsoft Visual C++.2008 Express Edition
  


Its license does not allow us to create services for internet if we 
charge fees. At least this is what I was told. Does this mean that using 
kinterbasdb (compiled with MSVC express) I'm forbidden to write 
commercial internet services? :-s


  L



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


Re: Tkinter - Text - bullets

2009-09-21 Thread eb303
On Sep 19, 5:53 pm, Thomas Lehmann  wrote:
> > Something like this maybe?
> > 
> > from Tkinter import *
>
> > root = Tk()
> > txt = Text(root, wrap='word')
> > txt.pack()
>
> > txt.tag_configure('text_body', font=('Times', 18), lmargin1=0,
> > lmargin2=0)
> > txt.tag_configure('bulleted_list', font=('Times', 18), lmargin1='10m',
> > lmargin2='15m', tabs=['15m'])
>
> > txt.insert(END, u"This is a normal paragraph. Let's make it a bit long
> > to see that it wraps as expected.\n", 'text_body')
> > txt.insert(END, u"\u00B7\tThis is the first item in the list.\n",
> > 'bulleted_list')
> > txt.insert(END, u"\u00B7\tThis is the second item in the list. Let's
> > make this one quite long too to see how it wraps.\n", 'bulleted_list')
>
> Thank you very much!
> However, the result is not that pretty as I have expected. The bullets
> are really small. When separating bullet and text then I can increase
> the font size for the bullet but then it does not fit to the text -
> vertical alignment is wrong. Also it's pretty unhandy to adjust the
> margins so that the text continues on next line starting at the same
> position as the first character from previous line.
>
> But it is a starting. I will check whether it is possible to place an
> image for a bullet. The size and position handling will be still there
> then -  I think so.

You can also use another font for bullets:

from Tkinter import *
import tkFont

root = Tk()

txt = Text(root, wrap='word')
txt.pack()

txt.tag_configure('text_body', font=('Times', 18), lmargin1=0,
lmargin2=0)
txt.tag_configure('bulleted_list', font=('Times', 18), lmargin1='10m',
lmargin2='15m', tabs=['15m'])
txt.tag_configure('bullets', font=('Dingbats', 18))

txt.insert(END, u"This is a normal paragraph. Let's make it a bit long
to see that it wraps as expected.\n", 'text_body')
txt.insert(END, u'\u25C6', 'bullets')
txt.insert(END, u"\tThis is the first item in the list.\n",
'bulleted_list')
txt.insert(END, u'\u25C6', 'bullets')
txt.insert(END, u"\tThis is the second item in the list. Let's make
this one quite long too to see how it wraps.\n", 'bulleted_list')

root.mainloop()


> Also note: The tab value from your example has not been accepted (s.th
> like. "invalid screen distance")

This is probably why you had all these alignment problems. But it's
weird, because the script I posted is copied and pasted from a really
script that I've run, and which doesn't cause any error. What is the
version of tcl/tk used by your Tkinter module? And what is your Python
version?
-- 
http://mail.python.org/mailman/listinfo/python-list


Reset Your LinkedIn Password

2009-09-21 Thread LinkedIn Password
LinkedIn



We have received your request to reset your LinkedIn password. Please use this 
secure URL to reset your password within 5 days:
https://www.linkedin.com/e/pwr/26793251/OGWCdFSS/

To reset your password, please enter your new password twice on the page that 
opens.

Thank you for using LinkedIn!

- The LinkedIn Team
http://www.linkedin.com/
-- 
http://mail.python.org/mailman/listinfo/python-list