Quixote cookies

2008-01-20 Thread [EMAIL PROTECTED]
Hi, guys
I'm trying to use cookies in Quixote.
This is the code:

env = copy(os.environ)
req = HTTPRequest(sys.stdin, env)
req.response.set_cookie("xxx","666")
cc = req.get_cookie("xxx");

For some reason it cc is always None. What am I doing wrong?

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


Re: Excess whitespace in my soup

2008-01-20 Thread John Machin
Remco Gerlich wrote:
> Not sure if this is sufficient for what you need, but how about
>
> import re
> re.sub(u'[\s\xa0]+', ' ', s)
>
> That should replace all occurances of 1 or more whitespace or \xa0 
> characters, by a single space.
>
It does indeed, and so does
re.sub(u'\s\+', ' ', s)
because u'\xa0' *IS* whitespace in the Python unicode world, but it's 
not whitespace in the HTML sense and it must be preserved.

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


Re: Hebrew in idle ans eclipse (Windows)

2008-01-20 Thread iu2
On Jan 17, 10:35 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > import pymssql
>
> > con =
> > pymssql.connect(host='192.168.13.122',user='sa',password='',database='tempd­b')
> > cur = con.cursor()
> > cur.execute('select firstname, lastname from [users]')
> > lines = cur.fetchall()
>
> > print lines
>
> > or
>
> > print lines[0]
>
> > 'lines' is a list containing tuples of 2 values, for firstname and
> > lastname. The names areHebrewand their code looks different when I'm
> > runnig it fromIDLEthan when running it from Windows shell or
> >eclipse, as I described in my first post.
>
> Ok. Please understand that there are different ways to represent
> characters as bytes; these different ways are called "encodings".
>
> Please also understand that you have to make a choice of encoding
> every time you represent characters as bytes: if you read it from a
> database, and if you print it to a file or to the terminal.
>
> Please further understand that interpreting bytes in an encoding
> different from the one they were meant for results in a phenomenon
> called "moji-bake" (from Japanese, "ghost characters"). You get
> some text, but it makes no sense (or individual characters are incorrect).
>
> So you need to find out
> a) what the encoding is that your data have in MySQL
> b) what the encoding is that is used when printing inIDLE
> c) what the encoding is that is used when printing into
>    a terminal window.
>
> b) and c) are different on Windows; the b) encoding is called
> the "ANSI code page", and c) is called the "OEM code page".
> What the specific choice is depends on your specific Windows
> version and local system settings.
>
> As for a: that's a choice somebody made when the database
> was created; I don't know how to figure out what encoding
> MySQL uses.
>
> In principle, rather than doing
>
>   print lines[0]
>
> you should do
>
>   print lines[0].decode("").encode("")
>
> when printing to the console. Furtenately, you can also write
> this as
>
>   print lines[0].decode("")
>
> as Python will figure out the console encoding by itself, but
> it can't figure out the MySQL encoding (or atleast doesn't,
> the way you use MySQL).
>
> Regards,
> Martin- Hide quoted text -
>
> - Show quoted text -

Thanks for the detailed explanation. I'll try that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Excess whitespace in my soup

2008-01-20 Thread John Machin
Stefan Behnel wrote:
> John Machin wrote:
>   
>> On Jan 19, 11:00 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> 
>>> John Machin wrote:
>>>   
 I'm happy enough with reassembling the second item. The problem is in
 reliably and  correctly collapsing the whitespace in each of the above
 
>>>  > fiveelements. The standard Python idiom of u' '.join(text.split())
>>>  > won't work because the text is Unicode and u'\xa0' is whitespace
>>>
>>>   
 and would be converted to a space.
 
>>> would this (or some variation of it) work?
>>>
>>>  >>> re.sub("[ \n\r\t]+", " ", u"foo\n  frab\xa0farn")
>>> u'foo frab\xa0farn'
>>>
>>> 
>>>   
>> Yes, partially. Leading and trailing whitespace has to be removed
>> entirely, not replaced by one space.
>> 
>
> Sounds like adding a .strip() to me ...
>
>
>   

Sounds like adding a .strip(u' ') to me, otherwise any leading/trailing 
u'\xa0' gets blown away and this must not happen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
Hi all,

I am newbie in Python, my wish would be to create python applications
for both Linux/Win32.

I am stucked on creating a function to get the Python install
directory (and site-packages directory) with a 100% reliable method...

My goal is to verify if an/several extension(s) are installed and to
automatically install the missing ones on Linux or Win32.

I have tested sys.executable and sys.path, but I am not sure to be
able to get what I need on different versions of Python and different
platforms.

Google was not a good friend on this, so I am very interested on how
you implement such a function.

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Christian Heimes
pythonewbie wrote:
> I am stucked on creating a function to get the Python install
> directory (and site-packages directory) with a 100% reliable method...

Only one method is 100% reliable:

try:
import yourextension
except ImportError:
available = False
else:
available = True

Christian

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


Re: finding memory leak in edgewall trac 0.11

2008-01-20 Thread rupert.thurner
On Jan 19, 10:31 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Jeroen Ruigrok van der Werven wrote:
>
> > Hi Christian,
>
> > -On [20080119 16:16], Christian Heimes ([EMAIL PROTECTED]) wrote:
> >> I forgot one important point in my reply. The GC module contains some
> >> useful methods for debugging. Check gc.garbage. It should be empty.
>
> > Yeah, we're messing around with that stuff as well as many other ways of
> > trying to track issues, but it can really be looking for a needle in a
> > haystack to be honest.
> > There's so much output that, I guess, make sense only when you're semi-deep
> > into the Python internals to even make heads or tails out of it. =\
> > And even third-party code is not helping much to reduce the clutter and
> > provide insight.
>
> Under normal circumstances gc.garbage should be an empty list. In
> general it's a bad sign if gc.garbage contains lots of objects.
>
> I found several potential leaks in trac:
>
> $ find -name \*.py | xargs grep __del__
> ./trac/versioncontrol/svn_fs.py:    def __del__(self):
> ./trac/versioncontrol/svn_fs.py:    def __del__(self):
> ./trac/db/pool.py:    def __del__(self):
>
> $ find -name \*.py | xargs grep frame
> ./trac/web/main.py:
> [...]
> ./trac/core.py:        frame = sys._getframe(1)
> ./trac/core.py:        locals_ = frame.f_locals
>
> I recommend that you either replace __del__ with a weak reference
> callback or to remove it. Referencing a frame, traceback or f_locals is
> going to leak, too. You *must* explicitly del every frame and locals
> variable.
>
> Christian

many thanks! as the main change was replacing clearsilver with genshi,
this means one could do the same thing with genshi, http://genshi.edgewall.org/?

$ find -name \*.py | xargs grep frame
./genshi/filters/html.py:'dir', 'disabled', 'enctype', 'for',
'frame', 'headers', 'height',
./genshi/input.py:_EMPTY_ELEMS = frozenset(['area', 'base',
'basefont', 'br', 'col', 'frame',
./genshi/output.py:'http://www.w3.org/TR/html4/frameset.dtd'
./genshi/output.py:'http://www.w3.org/TR/xhtml1/DTD/xhtml1-
frameset.dtd'
./genshi/output.py: * "html-transitional" for the HTML 4.01
frameset DTD
./genshi/output.py: * "xhtml-frameset" for the XHTML 1.0
frameset DTD
./genshi/output.py:'html-frameset': DocType.HTML_FRAMESET,
./genshi/output.py:'xhtml-frameset': cls.XHTML_FRAMESET,
./genshi/output.py:_EMPTY_ELEMS = frozenset(['area', 'base',
'basefont', 'br', 'col', 'frame',
./genshi/template/base.py:_ctxt2dict = lambda ctxt: ctxt.frames[0]
./genshi/template/base.py:self.frames = deque([data])
./genshi/template/base.py:self.pop = self.frames.popleft
./genshi/template/base.py:self.push = self.frames.appendleft
./genshi/template/base.py:return repr(list(self.frames))
./genshi/template/base.py:for frame in self.frames:
./genshi/template/base.py:if key in frame:
./genshi/template/base.py:del frame[key]
./genshi/template/base.py:value, frame = self._find(key)
./genshi/template/base.py:if frame is None:
./genshi/template/base.py:self.frames[0][key] = value
./genshi/template/base.py:"""Retrieve a given variable's value
and the frame it was found in.
./genshi/template/base.py:for frame in self.frames:
./genshi/template/base.py:if key in frame:
./genshi/template/base.py:return frame[key], frame
./genshi/template/base.py:for frame in self.frames:
./genshi/template/base.py:if key in frame:
./genshi/template/base.py:return frame[key]
./genshi/template/base.py:for frame in self.frames:
./genshi/template/base.py:keys += [key for key in frame if
key not in keys]
./genshi/template/directives.py:# Store the function reference
in the bottom context frame so that it
./genshi/template/directives.py:ctxt.frames[-1][self.name] =
function
./genshi/template/directives.py:frame = {}
./genshi/template/directives.py:ctxt.push(frame)
./genshi/template/tests/directives.py:frame =
exc_traceback.tb_next
./genshi/template/tests/directives.py:frames = []
./genshi/template/tests/directives.py:while frame.tb_next:
./genshi/template/tests/directives.py:frame =
frame.tb_next
./genshi/template/tests/directives.py:
frames.append(frame)
./genshi/template/tests/directives.py:
frames[-1].tb_frame.f_code.co_name)
./genshi/template/tests/directives.py:
frames[-1].tb_frame.f_code.co_filename)
./genshi/template/tests/directives.py:self.assertEqual(2,
frames[-1].tb_lineno)
./genshi/template/tests/eval.py:frame =
exc_traceback.tb_next
./genshi/template/tests/eval.py:frames = []
./genshi/template/tests/eval.py:while frame.tb_next:
./genshi/template/tests/eval.py:frame = frame.tb_next
./genshi/template/tests/eval.py: 

Re: finding memory leak in edgewall trac 0.11

2008-01-20 Thread rupert.thurner
On Jan 20, 12:40 pm, "rupert.thurner" <[EMAIL PROTECTED]>
wrote:
> On Jan 19, 10:31 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Jeroen Ruigrok van der Werven wrote:
>
> > > Hi Christian,
>
> > > -On [20080119 16:16], Christian Heimes ([EMAIL PROTECTED]) wrote:
> > >> I forgot one important point in my reply. The GC module contains some
> > >> useful methods for debugging. Check gc.garbage. It should be empty.
>
> > > Yeah, we're messing around with that stuff as well as many other ways of
> > > trying to track issues, but it can really be looking for a needle in a
> > > haystack to be honest.
> > > There's so much output that, I guess, make sense only when you're 
> > > semi-deep
> > > into the Python internals to even make heads or tails out of it. =\
> > > And even third-party code is not helping much to reduce the clutter and
> > > provide insight.
>
> > Under normal circumstances gc.garbage should be an empty list. In
> > general it's a bad sign if gc.garbage contains lots of objects.
>
> > I found several potential leaks in trac:
>
> > $ find -name \*.py | xargs grep __del__
> > ./trac/versioncontrol/svn_fs.py:    def __del__(self):
> > ./trac/versioncontrol/svn_fs.py:    def __del__(self):
> > ./trac/db/pool.py:    def __del__(self):
>
> > $ find -name \*.py | xargs grep frame
> > ./trac/web/main.py:
> > [...]
> > ./trac/core.py:        frame = sys._getframe(1)
> > ./trac/core.py:        locals_ = frame.f_locals
>
> > I recommend that you either replace __del__ with a weak reference
> > callback or to remove it. Referencing a frame, traceback or f_locals is
> > going to leak, too. You *must* explicitly del every frame and locals
> > variable.
>
> > Christian
>
> many thanks! as the main change was replacing clearsilver with genshi,
> this means one could do the same thing with 
> genshi,http://genshi.edgewall.org/?
>
> $ find -name \*.py | xargs grep frame
> ./genshi/filters/html.py:        'dir', 'disabled', 'enctype', 'for',
...
>
> - Show quoted text -

i forgot to mention that i cannot see any explicit sys._getframe(), or
__del__ in the genshi code, while the ones in trac-core seemed to be
there in 0.10.4.

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


Re: convivenza

2008-01-20 Thread Sergio
crxor 666 wrote:
> 
>> Evidentemente equivocherò sul termine "potenza di un linguaggio", ma 
>> dubito che io possa scrivere un device driver in Python, 
>> indipendentemente dalla potenza processore o dall'esistenza di un 
>> compilatore Python (ho preso per esempio il Python ma potevo usare molti
>> altri linguaggi).
> E perchè? In particolare questa è una questione di libreria più che di
> linguaggio. Questo oggetto per dire ti fa scrivere driver per oggetti
> USB in Python:
> 
Per prima cosa non è scritta in Python ma in C, ma in ogni caso mi pare 
una libreria per l'accesso a dispositivi USB, non una libreria per 
scrivere driver in Python, che sono due cose ben diverse.
Il fatto che le librerie Python (come quelle di altri linguaggi) siano 
scritte per la maggior parte in un linguaggio diverso non dipende solo 
da questioni prestazionali, ma anche dal fatto che certe cose sono 
impossibili in Python.

> 
Come sopra, il kernel non è in Python.

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


Re: Okay I got a question regarding Tkinter and Labels

2008-01-20 Thread Fredrik Lundh
Lamonte Harris wrote:

> Okay I've created a script and basically when I loop through a folder it 
> is supposed to change the Label everytime it updates a file then again 
> it doesn't do nothing but shows the last file edited, whats the best way 
> to loop through files and display that file name in a Label's text 
> without skipping to the last one when the loop is finished?

Tkinter is event-driven, and you need to keep the event loop running to 
make sure that changes to the widgets makes it to the screen.

Usually, this is handled by the "mainloop" function, but if you're 
spending considerable time at the Python level, you need to call the 
"update" or "update_idletasks" methods from time to time to give Tkinter 
a chance to process incoming events.  In your case, you can simply call 
the method after you've modified the label:

 label.config(text="something")
 label.update()

Hope this helps!



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


Re: Memory errors with imaplib

2008-01-20 Thread Fredrik Lundh
Martey wrote:

> I am trying to use imaplib to download messages, but I keep getting
> memory errors when I try to download a large message (i.e. one with
> attachments). Here is my test code (similar to the example in the
> imaplib documentation):

 > /.../

> I am using Mac OS X 10.5 and Python 2.5.1 (downloaded from
> python.org). I think it is possible that it is  issue1092502>, but the workarounds suggested there do not seem to work
> for me. Is this an actual Python bug, or am I doing something wrong?

looks like a known bug in imaplib:

 http://bugs.python.org/issue1389051

 "In a worst case scenario, you'll need some 13 gigabytes of
 virtual memory to read a 15 megabyte message..."



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


Re: Efficient processing of large nuumeric data file

2008-01-20 Thread Jorgen Grahn
On Fri, 18 Jan 2008 09:15:58 -0800 (PST), David Sanders <[EMAIL PROTECTED]> 
wrote:
> Hi,
>
> I am processing large files of numerical data.  Each line is either a
> single (positive) integer, or a pair of positive integers, where the
> second represents the number of times that the first number is
> repeated in the data -- this is to avoid generating huge raw files,
> since one particular number is often repeated in the data generation
> step.
>
> My question is how to process such files efficiently to obtain a
> frequency histogram of the data (how many times each number occurs in
> the data, taking into account the repetitions).  My current code is as
> follows:

...

> The data files are large (~100 million lines), and this code takes a
> long time to run (compared to just doing wc -l, for example).

I don't know if you are in control of the *generation* of data, but
I think it's often better and more convenient to pipe the raw data
through 'gzip -c' (i.e. gzip-compress it before it hits the disk)
than to figure out a smart application-specific compression scheme.

Maybe if you didn't have a homegrown file format, there would have
been readymade histogram utilities?  Or at least a good reason to
spend the time writing an optimized C version.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I don't understand what is happening in this threading code

2008-01-20 Thread Nir
On Jan 19, 2:43 am, Matthew Wilson <[EMAIL PROTECTED]> wrote:
> In this code, I tried to kill my thread object by setting a variable on it
> to False.
>
> Inside the run method of my thread object, it checks a different
> variable.
>
> I've already rewritten this code to use semaphores, but I'm just curious
> what is going on.
>
> Here's the code:
>
> import logging, threading, time
> logging.basicConfig(level=logging.DEBUG,
> format="%(threadName)s: %(message)s")
>
> class Waiter(threading.Thread):
> def __init__(self, hot_food):
> super(Waiter, self).__init__()
> self.should_keep_running = True
> self.hot_food = hot_food
>
> def run(self):
> while self.should_keep_running:
> logging.debug("Inside run, the id of should_keep_running is %s."
>   % id(self.should_keep_running))
> self.hot_food.acquire()
>
> def cook_food(hot_food):
> i = 5
> while i >= 0:
> logging.debug("I am cooking food...")
> time.sleep(1)
> hot_food.release()
> logging.debug("Andiamo!")
> i -= 1
>
> def main():
>
> hot_food = threading.Semaphore(value=0)
>
> chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, ))
> chef.start()
>
> w = Waiter(hot_food)
> logging.debug("Initially, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
> w.start()
> logging.debug("After start, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
>
> # Wait for the chef to finish work.
> chef.join()
>
> # Now try to kill off the waiter by setting a variable inside the waiter.
> w.should_keep_running = False
> logging.debug("Now, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
>
> if __name__ == "__main__":
> main()
>
> And here's what I get when I execute it.  I have to suspend the process
> with CTRL=Z and then kill -9 it.
>
> $ python foo.py
> MainThread: Initially, the id of w.should_keep_running is 135527852.
> MainThread: After start, the id of w.should_keep_running is 135527852.
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> MainThread: Now, the id of w.should_keep_running is 135527840.
>
> [1]+  Stopped python foo.py
>
> $ kill -9 %1
>
> [1]+  Stopped python foo.py
>
> The memory address of should_keep_running seems to change when I set it
> from True to False, and inside the run method, I keep checking the old
> location.
>
> I am totally baffled what this means.
>
> Like I said earlier, I already rewrote this code to use semaphores, but
> I just want to know what is going on here.
>
> Any explanation is welcome.
>
> TIA
>
> Matt

It does not check a different variable.
You can open a Python session and try the following:

Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = True
>>> id(a)
135527852
>>> a = False
>>> id(a)
135527840

The problem is that the waiter is locked waiting for new food and
never looks at the variable.
You should add hot_food.release() after you set the keep running flag
to False.

Nir

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


Re: finding memory leak in edgewall trac 0.11

2008-01-20 Thread Christian Heimes
rupert.thurner wrote:
> i forgot to mention that i cannot see any explicit sys._getframe(), or
> __del__ in the genshi code, while the ones in trac-core seemed to be
> there in 0.10.4.

Does the code keep a reference to a traceback object or an attribute of
a traceback object?

Christian

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


bitmap problem

2008-01-20 Thread Robin Becker
I'm having trouble with defining a completely transparent bitmap
for use as a stipple in a canvas


import Tkinter
Tkinter._default_root.tk.call('image','create', 'bitmap', 'gray0',
 '-background', '',
'-data', '#define gray0_width 1\n#define gray0_height 1\nstatic 
char 
gray0_bits[] = {\n0x0\n};')
print 'image names', self.tk.call('image','names')
print 'image type', self.tk.call('image','type','gray0')
self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i",
  fill="blue",activestipple='gray0')


the prints seem to indicate that the bitmap is defined, but the canvas 
create_rectangle fails

image names gray0
image type bitmap
Traceback (most recent call last):
   File "C:\Tmp\test.py", line 67, in 
 main()
   File "C:\Tmp\test.py", line 62, in main
 top = PDFMU()
   File "C:\Tmp\test.py", line 59, in __init__
 self.createWidgets()
   File "C:\Tmp\test.py", line 44, in createWidgets
 self.canv.create_rectangle("10i", "10i", "13.5i", "13.5i", 
fill="blue",activestipple='gray0')
   File "C:\Python\lib\lib-tk\Tkinter.py", line 2166, in create_rectangle
 return self._create('rectangle', args, kw)
   File "C:\Python\lib\lib-tk\Tkinter.py", line 2145, in _create
 *(args + self._options(cnf, kw
_tkinter.TclError: bitmap "gray0" not defined

if I change gray0 to one of the predefined names eg gray12 then the 
create_rectangle succeeds. The tk manual seems to suggest I should be 
able to do this, but it doesn't seem to work even in tk. Is there a way 
to define a stipple without a file?
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing Python in Emacs

2008-01-20 Thread Jorgen Grahn
["Followup-To:" header set to comp.lang.python.]

On Sat, 19 Jan 2008 17:51:50 +0100, Terry Jones <[EMAIL PROTECTED]> wrote:
>> "Richard" == Richard Szopa <[EMAIL PROTECTED]> writes:
>
>Richard> I am a devoted Emacs user and I write a lot in Python.
>
> Me too.
>
>Richard> I need the following features:
>
>Richard> 1) Tab completion, ideally Slime like. That is, when there's not
>Richard> enough letters to unambiguously complete a symbol, I want it to
>Richard> show a buffer (w/o taking the focus) w/ the possible
>Richard> completions. In an ideal world, it would be able to complete
>Richard> fo.ba to foo.bar. I imagine this would require quite tight
>Richard> Emacs-Python integration.
>
> I know this is not what you want, but I use hippie expand (M-/) to cycle
> through possible completions. It's not Python aware, but it is of some use.

Also known as dabbrev-expand, and tied to Ctrl-TAB.

I like it *a lot*, and I like it even more because it *isn't* Python
aware. I can use the same function no matter what I am typing, often
with files noone would dream of writing a mode for.

...
>Richard> 4) (optional) I would like to see the definition of a function
>Richard> function or class by hitting M-. on its name. (I understand that
>Richard> this may be impossible for methods, as Emacs would have to
>Richard> automagically infer the type of the object).
>
> This is just an emacs tag file need. Have you googled for something like
> emacs tags python?

Tags works fine, or at least as well as can be expected.  I use the
'etags' which comes with 'ctags', apparently.

> If you have the time, please summarize your findings. The emacs/python
> world has always seemed quite amorphous to me too.

I don't know; python-mode colorizes well and it knows how to help me
keep the indentation sane.  The Eclipse users I have seen seem to have
more problems than I have, for example.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory errors with imaplib

2008-01-20 Thread Grant Edwards
On 2008-01-20, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> looks like a known bug in imaplib:
>
>  http://bugs.python.org/issue1389051
>
>  "In a worst case scenario, you'll need some 13 gigabytes of
>  virtual memory to read a 15 megabyte message..."

The problem and the one-line soulution have been known for over
two years and it's still an open bug?

-- 
Grant Edwards   grante Yow!  Yow! Is my fallout
  at   shelter termite proof?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Core Python Programming . . .

2008-01-20 Thread Jorgen Grahn
On Sat, 19 Jan 2008 08:57:24 -0500, Yu-Xi Lim <[EMAIL PROTECTED]> wrote:
> FireNWater wrote:
>
>> I guess I'm not fully up to speed on what constitutes an IP address.
>> Does the term 'octet' refer to an 8-bit (xFF) number?
>
> Yes, it somewhat archaic though.

It's more precise than byte, like you say. I don't think its archaic
though; it's a fairly common term when you are talking data
communication in general and IP-based protocols in particular.

> It's used when "byte" is ambiguous. On 
> some ancient (by computing standards) computers, the size of a byte may 
> be as small as 6 bits or as big as 9.

On ancient computers and in some embedded processors. I have a Texas
Instruments DSP in my cellphone with 16-bit words. A C "char" is 16
bits in that environment.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Homework Helper and College Companion Websites

2008-01-20 Thread BJ
In 1996 I started BJ Pinchbeck's Homework Helper at www.bjpinchbeck.com
which became quite popular among young students throughout the
country.

Now that I am 20 years old and attending Drexel University in
Philadelphia, Pennsylvania, I decided it was time to start a new site,
BJ Pinchbeck's College Companion at www.bjpinchbeck.net that could
help students prepare for and survive the college experience. College
has been a very positive experience for me, but it would have been
nice to have more materials readily available to me prior to attending
college.

Please feel free to link to either site.

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


Re: Bug in __init__?

2008-01-20 Thread Bart Ogryczak
On 2008-01-18, citizen Zbigniew Braniecki testified:
> It's really a nice pitfall, I can hardly imagine anyone expecting this, 

AFAIR, it's described in Diving Into Python.
It's quiet elegant way of creating cache.

def calculate(x,_cache={}):
try:
return _cache[x]
except KeyError:
_cache[x] = result = _lotsa_slow_calculations(x)
return result

bart
-- 
This signature is intentionally left blank.
http://candajon.azorragarse.info/ http://azorragarse.candajon.info/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing Python in Emacs

2008-01-20 Thread Rob Wolfe
Terry Jones <[EMAIL PROTECTED]> writes:

>> "Richard" == Richard Szopa <[EMAIL PROTECTED]> writes:

I don't see Richard's original post, so I reply to Terry.

>
> Richard> I am a devoted Emacs user and I write a lot in Python.
>
> Me too.

The good news is that I managed to configure completion for Python 
in Emacs using pymacs, python-mode.el, pycomplete.el and pycomplete.py.
For contents of my pycomplete.el, pycomplete.py and necessary
settings in .emacs see below.

>
> Richard> I need the following features:
>
> Richard> 1) Tab completion, ideally Slime like. That is, when there's not
> Richard> enough letters to unambiguously complete a symbol, I want it to
> Richard> show a buffer (w/o taking the focus) w/ the possible
> Richard> completions. In an ideal world, it would be able to complete
> Richard> fo.ba to foo.bar. I imagine this would require quite tight
> Richard> Emacs-Python integration.

Works for me.

[...]

> Richard> 2) Sending the toplevel definition (class or function) to the Python
> Richard> buffer.

That feature is defined in python-mode.el:
"\e\C-x"'py-execute-def-or-class
"\C-c|" 'py-execute-region


[...]

> Richard> 3) Hints on function/method arguments. IDLE has this done nearly
> Richard> right, but the hints are a bit too intrusive for me. I would like to
> Richard> see them in the minibuffer.

Works for me, but only for pure python functions 
(`inspect.getargspec` constraint).

[...]

> Richard> I have tried a couple of times both python-modes (the one shipped w/
> Richard> Python and the one shipped w/ Emacs), pymacs and stuff like that...
> Richard> And, as I said, never got it right. But, maybe I just cannot find the
> Richard> way to configure it, and some configuration hints will be enough...

I mixed solutions found around the net and finally got it working:
- hitting TAB complete function/method name
- f1 shows description of object at point
- hitting '(' and ',' shows function parameters

Copy `pycomplete.py` on your PYTHONPATH (e.g. /usr/lib/python2.5/site-packages)
and `pycomplete.el` on your Emacs load_path (e.g. /usr/share/emacs/site-lisp).
Copy my settings to your `.emacs` file and hopefully it will work. ;)

My files:

# .emacs
(require 'pycomplete)
(setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)

(autoload 'pymacs-load "pymacs" nil t)
(autoload 'pymacs-eval "pymacs" nil t)
(autoload 'pymacs-apply "pymacs")
(autoload 'pymacs-call "pymacs")

(setq interpreter-mode-alist(cons '("python" . python-mode) 
  interpreter-mode-alist))
(setq python-mode-hook
  '(lambda () (progn
(set-variable 'py-python-command "/usr/bin/python2.5")
(set-variable 'py-indent-offset 4)
(set-variable 'py-smart-indentation nil)
(set-variable 'indent-tabs-mode nil
# end of .emacs


# pycomplete.el
(require 'pymacs)
(require 'python-mode)

(pymacs-load "pycomplete")


;;check if prev character is blank-type
(defun char-before-blank ()
  (save-excursion
  (forward-char -1)
  (looking-at "[\n\t\r]")))

(defun py-complete ()
  (interactive)
  (let ((pymacs-forget-mutability t))
(if (and 
 (and (eolp) (not (bolp)) 
 (not (char-before-blank
  (insert (pycomplete-pycomplete (py-symbol-near-point) 
(py-find-global-imports)))
  (indent-for-tab-command

(defun py-find-global-imports ()
  (save-excursion
(let ((imports nil))
  (goto-char (point-min))
  (while (re-search-forward
  "\\(import \\|from \\([A-Za-z_][A-Za-z_0-9\\.]*\\) import \\).*"
  nil t)
(setq imports 
  (append imports (list (buffer-substring
 (match-beginning 0) 
 (match-end 0))
  imports)))


(defun py-complete-python-dotexpr-begin nil
  (interactive)
  (re-search-backward "[^a-zA-Z_0-9\\.]")
  (forward-char))


(defun py-complete-python-dotexpr-end nil
  (interactive)
  (re-search-forward "[a-zA-Z_0-9\\.]*"))

(put 'python-dotexpr 'beginning-op 'py-complete-python-dotexpr-begin)
(put 'python-dotexpr 'end-op 'py-complete-python-dotexpr-end)


(defun py-complete-show (string)
  (display-message-or-buffer string "*PythonHelp*"))


(defun py-complete-help (string)
  "get help on a python expression"
  (let ((help-string 
 (pycomplete-pyhelp string (py-find-global-imports
(if (and help-string (> (length help-string) 300))
(with-output-to-temp-buffer "*Python Help*"
  (print help-string))
  (py-complete-show help-string


(defun py-complete-help-thing-at-point nil
  (interactive)
  (require 'thingatpt)
  (let ((sym (thing-at-point 'python-dotexpr)))
(if sym
(py-complete-help sym


(set 'py-complete-current-signature nil)

(defun py-complete-signature (function)
  "get signature of a python function or method"
  

Re: too long float

2008-01-20 Thread Bart Ogryczak
On 2008-01-18, citizen J. Peng testified:
> hello,
>
> why this happened on my python?

 a=3.9
 a
> 3.8999

>>> a = 3.9
>>> print a
3.9

bart
-- 
"PLEASE DO *NOT* EDIT or poldek will hate you." - packages.dir (PLD)
http://candajon.azorragarse.info/ http://azorragarse.candajon.info/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in __init__?

2008-01-20 Thread Bart Ogryczak
On 2008-01-18, citizen Zbigniew Braniecki testified:
> I found a bug in my code today, and spent an hour trying to locate it 
> and then minimize the testcase.
>
> Once I did it, I'm still confused about the behavior and I could not 
> find any reference to this behavior in docs.
>
> testcase:
>
> class A():
>
>def add (self, el):
>  self.lst.extend(el)
>
>def __init__ (self, val=[]):
>  print val
>  self.lst = val

What you want probably is:
def __init__ (self, val=None):
if(val == None):
self.lst = []
else:
from copy import copy
### see also deepcopy
self.lst = copy(val)

> def test ():
>x = A()
>x.add(["foo1","foo2"])
>b = A()
>
>
> So, what I would expect here is that I will create two instances of 
> class A with empty self.lst property. Right?

Wrong. default value for val gets evaluated only once, creating a list 
(initialy empty). The same list for all of A's instances. 

>>> a = A()
>>> id(a.lst)
13188912

>>> b = A()
>>> id(b.lst)
13188912

Moreover, self.lst = val, does not copy val, rather it creates binding 
between self.list and val. So whatever you do to self.list, it affects 
val (and vice-versa).

>>> x = []
>>> c = A(x)
>>> id(x)
10508368
>>> id(c.lst)
10508368
>>> c.lst.append('wrong')
>>> x
['wrong']

bart
-- 
"We're coming in low out of raising sun and about mile up we'll put on music"
http://candajon.azorragarse.info/ http://azorragarse.candajon.info/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory errors with imaplib

2008-01-20 Thread Christian Heimes
Grant Edwards wrote:
> The problem and the one-line soulution have been known for over
> two years and it's still an open bug?

Nobody was interested to provide a patch. I raised the level of the bug.
It's going to be fixed soonish.

Christian

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


Re: TopSort in Python?

2008-01-20 Thread Mike C. Fletcher
Paddy wrote:
...
> I searched for dependancy sort, and later dependency sort (cos I
> couldn't spell). I had convinced that I was using the right term and
> was flummoxed by the lack of hits. Even today the term topological
> sort means far less than what it describes: sorting items based on
> their interdependencies.
>   
"dependency sort python" typed into Google today gives a post pointing
to http://www.vrplumber.com/programming/ (which has Tim and my
algorithms (toposort.py)) as the second link... vagaries of Google I
suppose.
> Is this a case of something being named after its mathematical/
> technical description and so obscuring its wider practical use cases?
>   
Could be, I tried to make sure that the word dependency was in the
description on the download page (since I had the same problem starting
out (I implemented the algorithm before I knew the name IIRC)).
> P.S. we have revived a thread started in 1999!
>   
For some of us 1999 is well into our Pythonic life-cycle :)

Have fun,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: Bug in __init__?

2008-01-20 Thread Arnaud Delobelle
On Jan 20, 3:39 pm, Bart Ogryczak <[EMAIL PROTECTED]
to.invalid> wrote:
> On 2008-01-18, citizen Zbigniew Braniecki testified:
>
> > It's really a nice pitfall, I can hardly imagine anyone expecting this,
>
> AFAIR, it's described in Diving Into Python.

Still there seems to be about one message a week about this.  Indeed I
reckon the greatest benefit of early binding of default function
arguments is that it attracts lots of new people to comp.lang.python.

> It's quiet elegant way of creating cache.

IMHO, calling it 'elegant' is pushing it too far!

--
Arnaud

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


RE: HTTP POST uploading large files

2008-01-20 Thread Brian Smith
Wolfgang Draxinger wrote:
> The problem is, that videos, by nature are rather big files, 
> however urllib2 wants it's Request objects being prepared 
> beforehand, which would mean to first load the whole file to memory.

Try using mmap. Here is some untested code:

map = mmap(file.fileno(), len(file), access=ACCESS_READ)
try:
data = mmap.read() 
request = Request(url, data, headers)
...
finally:
map.close()


- Brian

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


Looping through the gmail dot trick

2008-01-20 Thread Joshua Gilman
So I have a very interesting task ahead of me and it is to loop through an
email using the 'gmail dot trick'. Essentially this trick puts periods
throughout your email to make it look different. Even though it has periods
gmail will replace them all and send it to that email.

So [EMAIL PROTECTED] is the same as [EMAIL PROTECTED]

My task is this: Loop through an email and create as many combinations of
periods as possible. So all the combinations for blah would be:

b.lah
bl.ah
bla.h
b.l.ah
b.la.h
bl.a.h

I'm still rather new to python so this is turning out to be rather tricky.
My current code is as follows:

for d in range(1, len(email)):
> for i in range(1, len(email)):
> y = i
> temail = email
> for x in range(d):
> if email[y] == '.': break
> temail = temail.replace(email[y], '.' + email[y])
> if not y > len(email) - 2: y += 1
> print temail
>

It's not looking too bad except for some reason it's making emails like
bl..ah which is invalid. So can anyone help me out with getting this to
work? Thanks.

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

Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
> pythonewbie wrote:
> > I am stucked on creating a function to get the Python install
> > directory (and site-packages directory) with a 100% reliable method...
>
> Only one method is 100% reliable:
>
> try:
> import yourextension
> except ImportError:
> available = False
> else:
> available = True
>
> Christian

Hi Christian,

OK thanks, interesting to detect if an extension is available or not.

But for different reasons I also want to get the absolute path of
Python install directory (not only the executable under Linux) and
site-packages directory.

How could I proceed ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in __init__?

2008-01-20 Thread Bart Ogryczak
On 2008-01-20, citizen Arnaud Delobelle testified:
> On Jan 20, 3:39 pm, Bart Ogryczak <[EMAIL PROTECTED]
> to.invalid> wrote:
>> On 2008-01-18, citizen Zbigniew Braniecki testified:
>>
>> > It's really a nice pitfall, I can hardly imagine anyone expecting this,
>>
>> AFAIR, it's described in Diving Into Python.
>
> Still there seems to be about one message a week about this.  Indeed I
> reckon the greatest benefit of early binding of default function
> arguments is that it attracts lots of new people to comp.lang.python.

Generally there's lot of confusion about assigments of objects. 
I guess, there are lot of ppl, who started with languages like PHP,
where $a = $b, translates to Python's a = copy(b).

>> It's quiet elegant way of creating cache.
>
> IMHO, calling it 'elegant' is pushing it too far!

Ok, maybe that's not a good choice of word.
Not elegant, minimalist.

bart
-- 
"The first version of iBook looked a bit too much like toilet seat" (c)Newsweek 
http://candajon.azorragarse.info/ http://azorragarse.candajon.info/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP POST uploading large files

2008-01-20 Thread Paul Rubin
Wolfgang Draxinger <[EMAIL PROTECTED]> writes:
> Am I just blind for some urllib2/httplib feature, or some other
> library? Or do I really have to fiddle around with sockets
> myself (I hope not...).

I did something like that by just opening a socket and writing the
stuff with socket.sendall.  It's only about 5 lines of code and it's
pretty straightforward.
-- 
http://mail.python.org/mailman/listinfo/python-list


Just for fun: Countdown numbers game solver

2008-01-20 Thread dg . google . groups
Ever since I learnt to program I've always loved writing solvers for
the Countdown numbers game problem in different languages, and so now
I'm wondering what the most elegant solution in Python is.

If you don't know the game, it's simple: you're given six randomly
chosen positive integers, and a target (another randomly chosen
positive integer), and you have to make the target using only the
numbers you're given, and +,-,* and / (and any number of brackets you
like). You're not allowed fractions as intermediate values. So, given
2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21.

So what's the best algorithm? And, what's the most elegant way to code
it in Python? I've posted my most elegant version below (I have a
faster version which is slightly less elegant). Can anyone do better?

Refs:

* This academic paper describes an implementation of an algorithm to
solve the problem in Haskell. I found it after I'd written mine but it
uses a very similar algorithm. http://www.cs.nott.ac.uk/~gmh/countdown.pdf
* My web page where I put both versions of my code: 
http://thesamovar.net/countdownnumbers
* The web page of the TV show the problem is based on:
http://www.channel4.com/entertainment/tv/microsites/C/countdown/index.html

My version:

class InvalidExpressionError(ValueError):
pass

subtract = lambda x,y: x-y
def add(x,y):
if x<=y: return x+y
raise InvalidExpressionError
def multiply(x,y):
if x<=y or x==1 or y==1: return x*y
raise InvalidExpressionError
def divide(x,y):
if not y or x%y or y==1:
raise InvalidExpressionError
return x/y

add.display_string = '+'
multiply.display_string = '*'
subtract.display_string = '-'
divide.display_string = '/'

standard_operators = [ add, subtract, multiply, divide ]

class Expression(object): pass

class TerminalExpression(Expression):
def __init__(self,value,remaining_sources):
self.value = value
self.remaining_sources = remaining_sources
def __str__(self):
return str(self.value)
def __repr__(self):
return str(self.value)

class BranchedExpression(Expression):
def __init__(self,operator,lhs,rhs,remaining_sources):
self.operator = operator
self.lhs = lhs
self.rhs = rhs
self.value = operator(lhs.value,rhs.value)
self.remaining_sources = remaining_sources
def __str__(self):
return '('+str(self.lhs)+self.operator.display_string
+str(self.rhs)+')'
def __repr__(self):
return self.__str__()

def
ValidExpressions(sources,operators=standard_operators,minimal_remaining_sources=0):
for value, i in zip(sources,range(len(sources))):
yield TerminalExpression(value=value,
remaining_sources=sources[:i]+sources[i+1:])
if len(sources)>=2+minimal_remaining_sources:
for lhs in
ValidExpressions(sources,operators,minimal_remaining_sources+1):
for rhs in ValidExpressions(lhs.remaining_sources,
operators, minimal_remaining_sources):
for f in operators:
try: yield BranchedExpression(operator=f, lhs=lhs,
rhs=rhs, remaining_sources=rhs.remaining_sources)
except InvalidExpressionError: pass

def TargetExpressions(target,sources,operators=standard_operators):
for expression in ValidExpressions(sources,operators):
if expression.value==target:
yield expression

def FindFirstTarget(target,sources,operators=standard_operators):
for expression in ValidExpressions(sources,operators):
if expression.value==target:
return expression
raise IndexError, "No matching expressions found"

if __name__=='__main__':
import time
start_time = time.time()
target_expressions = list(TargetExpressions(923,[7,8,50,8,1,3]))
target_expressions.sort(lambda x,y:len(str(x))-len(str(y)))
print "Found",len(target_expressions),"solutions, minimal string
length was:"
print target_expressions[0],'=',target_expressions[0].value
print
print "Took",time.time()-start_time,"seconds."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP POST uploading large files

2008-01-20 Thread Wolfgang Draxinger
Paul Rubin wrote:

> Wolfgang Draxinger <[EMAIL PROTECTED]> writes:
>> Am I just blind for some urllib2/httplib feature, or some
>> other library? Or do I really have to fiddle around with
>> sockets myself (I hope not...).
> 
> I did something like that by just opening a socket and writing
> the
> stuff with socket.sendall.  It's only about 5 lines of code and
> it's pretty straightforward.

Well, for YouTube you've to fiddle around with cookies,
form/multipart data and stuff like that. It's a bit more than
just opening a socket, there's some serious HTTP going on.

However I found a solution: The curl program, that comes with
libcurl and can be found on most *nix systems allows to do
pretty sophisticated HTTP requests, among them also sending
files by POST. So instead of using urllib2 or sockets from
Python, now my program just generates the appropriate calls to
curl, provides the in memory storage of cookies and does the
neccesary HTML parsing*. 

Wolfgang Draxinger

*) YouTube uploads videos in a two part process: First you set
the various video options, in return you get a form with some
hidden input fields, some of them providing a handle to the
already sent video information. That data has to be extracted
from the form and be put into the POST that also transfers the
video file.

-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Diez B. Roggisch
pythonewbie schrieb:
> On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
>> pythonewbie wrote:
>>> I am stucked on creating a function to get the Python install
>>> directory (and site-packages directory) with a 100% reliable method...
>> Only one method is 100% reliable:
>>
>> try:
>> import yourextension
>> except ImportError:
>> available = False
>> else:
>> available = True
>>
>> Christian
> 
> Hi Christian,
> 
> OK thanks, interesting to detect if an extension is available or not.
> 
> But for different reasons I also want to get the absolute path of
> Python install directory (not only the executable under Linux) and
> site-packages directory.
> 
> How could I proceed ?

Maybe sys.path is a starter?

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


Re: bitmap problem

2008-01-20 Thread Robin Becker
Robin Becker wrote:
> I'm having trouble with defining a completely transparent bitmap
> for use as a stipple in a canvas
> 
> 
...
after a bit of searching I find that stipples cannot be created with the 
tk image command; for non-standard stipples you need to use a file.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Michael L Torrie
pythonewbie wrote:
> Hi all,
> 
> I am newbie in Python, my wish would be to create python applications
> for both Linux/Win32.
> 
> I am stucked on creating a function to get the Python install
> directory (and site-packages directory) with a 100% reliable method...
> 
> My goal is to verify if an/several extension(s) are installed and to
> automatically install the missing ones on Linux or Win32.
> 
> I have tested sys.executable and sys.path, but I am not sure to be
> able to get what I need on different versions of Python and different
> platforms.
> 
> Google was not a good friend on this, so I am very interested on how
> you implement such a function.

On both windows and Linux, installing stuff into the python install dir
requires root or administrative privileges, something most linux users
won't have unless they sudo.  So if the extensions you need are missing,
and you are distributing them yourself, why not just add them into the
path at runtime, rather than messing with the user's system?

As for obtaining the installation path, the setup.py that often comes
with python modules like ldaptor, seems to be able to figure it out.
I'd check there.  I think setup.py is created with distutils.


> 
> Cheers.

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 20 jan, 19:50, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> pythonewbie schrieb:
>
>
>
> > On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
> >> pythonewbie wrote:
> >>> I am stucked on creating a function to get the Python install
> >>> directory (and site-packages directory) with a 100% reliable method...
> >> Only one method is 100% reliable:
>
> >> try:
> >> import yourextension
> >> except ImportError:
> >> available = False
> >> else:
> >> available = True
>
> >> Christian
>
> > Hi Christian,
>
> > OK thanks, interesting to detect if an extension is available or not.
>
> > But for different reasons I also want to get the absolute path of
> > Python install directory (not only the executable under Linux) and
> > site-packages directory.
>
> > How could I proceed ?
>
> Maybe sys.path is a starter?
>
> Diez

Yes, it is, but my problem is that I am not sure to find the
information I need at the same position of the list generated by
sys.path.

I explain, for Win32, I find install directory using sys.path[6] and
site-package directory using sys.path[7], for Linux I find install
directory using sys.path[2] and site-package directory using
sys.path[6].

For my tests, I have used XP Pro and Ubuntu Gutsy.

I am not sure to find these information at the same position in the
sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD
and using Python v2.1 2.2 2.3 etc ?

This why I'm asking experienced programmers of this usenet group for
advices.
-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe and modules question

2008-01-20 Thread azrael
I'm working on an  application and i'm having some questions. I am
working with python 2.5, numpy and PIL. does anyone know if there are
some problems while compiling the source because of the modules.. It
has to be closed source.
I didn't try Py2exe but I heard about it. Is there any other and
better way to compile the source.

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Diez B. Roggisch
pythonewbie schrieb:
> On 20 jan, 19:50, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> pythonewbie schrieb:
>>
>>
>>
>>> On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
 pythonewbie wrote:
> I am stucked on creating a function to get the Python install
> directory (and site-packages directory) with a 100% reliable method...
 Only one method is 100% reliable:
 try:
 import yourextension
 except ImportError:
 available = False
 else:
 available = True
 Christian
>>> Hi Christian,
>>> OK thanks, interesting to detect if an extension is available or not.
>>> But for different reasons I also want to get the absolute path of
>>> Python install directory (not only the executable under Linux) and
>>> site-packages directory.
>>> How could I proceed ?
>> Maybe sys.path is a starter?
>>
>> Diez
> 
> Yes, it is, but my problem is that I am not sure to find the
> information I need at the same position of the list generated by
> sys.path.
> 
> I explain, for Win32, I find install directory using sys.path[6] and
> site-package directory using sys.path[7], for Linux I find install
> directory using sys.path[2] and site-package directory using
> sys.path[6].
> 
> For my tests, I have used XP Pro and Ubuntu Gutsy.
> 
> I am not sure to find these information at the same position in the
> sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD
> and using Python v2.1 2.2 2.3 etc ?
> 
> This why I'm asking experienced programmers of this usenet group for
> advices.

Sorry, I missed your first post. However, I don't see what your problem 
actually is. If you want to look for any extension, you need to consider 
whatever can be seen in the sys.path. So what do you care about the 
order of them?

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread marek . rocki
Nice challenge! I came up with something like this:

def find_repr(target, numbers):
org_reprs = dict((number, str(number)) for number in numbers)
curr_reprs = org_reprs
while target not in curr_reprs:
old_reprs, curr_reprs = curr_reprs, {}
for x in old_reprs:
for y in org_reprs:
repr_x, repr_y = old_reprs[x], old_reprs[y]
curr_reprs[x + y] = '(%s)+(%s)' % (repr_x, 
repr_y)
curr_reprs[x - y] = '(%s)-(%s)' % (repr_x, 
repr_y)
curr_reprs[x * y] = '(%s)*(%s)' % (repr_x, 
repr_y)
if y <> 0 and x % y == 0:
curr_reprs[x // y] = '(%s)/(%s)' % 
(repr_x, repr_y)
curr_reprs.update(old_reprs)
return curr_reprs[target]

print '21 =', find_repr(21, [2, 3, 5])
print '923 =', find_repr(923, [7, 8, 50, 8, 1, 3])

Unfortunately, this yields solutions that are a bit lispish (as in
'lots of superfluous parentheses' in the result). Nothing a simple
regex or two wouldn't fix ;-) And the solution found would be minimal
not with respect to the string length, but rather to the number of
operations to be performed.

Apart from that, I find it quite elegant. I'd like to know if it has
any flaws.

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Gabriel Genellina
En Sun, 20 Jan 2008 18:06:57 -0200, <[EMAIL PROTECTED]> escribi�:

> Nice challenge! I came up with something like this:

A nice solution too!

-- 
Gabriel Genellina

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

Re: Looping through the gmail dot trick

2008-01-20 Thread Gabriel Genellina
En Sun, 20 Jan 2008 14:38:06 -0200, Joshua Gilman <[EMAIL PROTECTED]>  
escribi�:

> My task is this: Loop through an email and create as many combinations of
> periods as possible. So all the combinations for blah would be:
>
> b.lah
> bl.ah
> bla.h
> b.l.ah
> b.la.h
> bl.a.h

I'd use a recursive generator (the divide-and-conquer approach):

def genalldots(txt):
   if len(txt)<=1:
 yield txt
   else:
 head, tail = txt[0], txt[1:]
 for item in genalldots(tail):
 yield head+item
 yield head+'.'+item

print sorted(genalldots('blah'))

(I got your six spellings above, plus 'blah' and 'b.l.a.h')

> I'm still rather new to python so this is turning out to be rather  
> tricky.
> My current code is as follows:
>
> for d in range(1, len(email)):
>> for i in range(1, len(email)):
>> y = i
>> temail = email
>> for x in range(d):
>> if email[y] == '.': break
>> temail = temail.replace(email[y], '.' + email[y])
>> if not y > len(email) - 2: y += 1
>> print temail

The replace function is dangerous, in case a letter appears more than  
once, you are replacing all instances. Anyway, since you *know* you want  
to replace the y-th item, just do:
temail = temail[:y] + '.' + temail[y:]

-- 
Gabriel Genellina

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

Re: Looping through the gmail dot trick

2008-01-20 Thread Martin Marcher
On Sunday 20 January 2008 17:38 Joshua Gilman wrote:

> So I have a very interesting task ahead of me and it is to loop through an
> email using the 'gmail dot trick'. Essentially this trick puts periods
> throughout your email to make it look different. Even though it has
> periods gmail will replace them all and send it to that email.

are you saying that when i have 2 gmail addresses

"[EMAIL PROTECTED]" and
"[EMAIL PROTECTED]"

they are actually treated the same? That is plain wrong and would break a
lot of mail addresses as I have 2 that follow just this pattern and they
are delivered correctly!

Do you have any reference on that where one could read up why gmail would
have such a behaviour?

> So [EMAIL PROTECTED] is the same as [EMAIL PROTECTED]

To my best knowledge it is not the same and must not be the same. The
localpart of an email is entirely up to the receiving mailserver and cannot
be tempered with without risking misdelivery (at least). If I'm wrong I'd
be gladly corrected, just point me to the references.

/martin


-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread dg . google . groups
Hi Marek,

That's a really nice solution (and ultrafast).

Unfortunately I realise I stated the problem imprecisely. You're only
allowed to use each number once (otherwise there's a trivial solution
for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times
for target y given any source number x). Trying your program on 234
from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times.

Does your solution adjust to deal with this additional requirement? At
first I thought it would be an easy fix, but maybe it's a little more
complicated than I thought...

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


Re: Looping through the gmail dot trick

2008-01-20 Thread Neil Hodgson
Martin Marcher:

> are you saying that when i have 2 gmail addresses
> 
> "[EMAIL PROTECTED]" and
> "[EMAIL PROTECTED]"
> 
> they are actually treated the same? That is plain wrong and would break a
> lot of mail addresses as I have 2 that follow just this pattern and they
> are delivered correctly!

This is a feature of some mail services such as Gmail, not of email 
addresses generically. One use is to provide a set of addresses given 
one base address. '+' works as well as '.' so when I sign up to service 
monty I give them the address [EMAIL PROTECTED] Then when I 
receive spam at nyamatongwe+monty, I know who to blame and what to block.

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Unfortunately I realise I stated the problem imprecisely. You're only
> allowed to use each number once (otherwise there's a trivial solution
> for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times
> for target y given any source number x). Trying your program on 234
> from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times.

Here is a pretty inefficient solution.  It doesn't find 234 but it
does find 253 twice:

from operator import *

def countdown(nums, ops, trace):
n0 = nums[0]
if len(nums) == 1:
yield n0, str(n0)
return
for i,n in enumerate(nums[1:]):
for f in ops:
for r,t in countdown(nums[1:i] + nums[i+1:], [add, mul, sub], 
trace):
if f != div or r != 0 and n0 % r == 0:
yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t)

def search(nums, target):
for x,t in countdown(nums, [add, mul, sub, div], []):
if x == target:
print x,t

search([100,9,7,6,3,1], 253)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Martin v. Löwis
> But for different reasons I also want to get the absolute path of
> Python install directory (not only the executable under Linux) and
> site-packages directory.

The Python install directory is available as sys.prefix. The
site-packages directory is
sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from
sys.version_info).

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 20 jan, 20:59, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> pythonewbie schrieb:
>
>
>
> > On 20 jan, 19:50, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> pythonewbie schrieb:
>
> >>> On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
>  pythonewbie wrote:
> > I am stucked on creating a function to get the Python install
> > directory (and site-packages directory) with a 100% reliable method...
>  Only one method is 100% reliable:
>  try:
>  import yourextension
>  except ImportError:
>  available = False
>  else:
>  available = True
>  Christian
> >>> Hi Christian,
> >>> OK thanks, interesting to detect if an extension is available or not.
> >>> But for different reasons I also want to get the absolute path of
> >>> Python install directory (not only the executable under Linux) and
> >>> site-packages directory.
> >>> How could I proceed ?
> >> Maybe sys.path is a starter?
>
> >> Diez
>
> > Yes, it is, but my problem is that I am not sure to find the
> > information I need at the same position of the list generated by
> > sys.path.
>
> > I explain, for Win32, I find install directory using sys.path[6] and
> > site-package directory using sys.path[7], for Linux I find install
> > directory using sys.path[2] and site-package directory using
> > sys.path[6].
>
> > For my tests, I have used XP Pro and Ubuntu Gutsy.
>
> > I am not sure to find these information at the same position in the
> > sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD
> > and using Python v2.1 2.2 2.3 etc ?
>
> > This why I'm asking experienced programmers of this usenet group for
> > advices.
>
> Sorry, I missed your first post. However, I don't see what your problem
> actually is. If you want to look for any extension, you need to consider
> whatever can be seen in the sys.path. So what do you care about the
> order of them?
>
> Diez

I just would like to know if I would ALWAYS find the install directory
in sys.path[6] and site-packages directory in sys.path[7] on any Win32
platform and sys.path[2] and site-packages directory in sys.path[6] on
any Linux platform.

If the reply is : "YES you can be sure of it !"

All would be great for me and I would be ready to create a script to
detect with a reliable manner the installation dir. et site-packages
dir. for all my Linux/Win32 Python apps.

Thanks for your interest on this topic.


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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Arnaud Delobelle
On Jan 20, 5:41 pm, [EMAIL PROTECTED] wrote:
> Ever since I learnt to program I've always loved writing solvers for
> the Countdown numbers game problem in different languages, and so now
> I'm wondering what the most elegant solution in Python is.
>
> If you don't know the game, it's simple: you're given six randomly
> chosen positive integers, and a target (another randomly chosen
> positive integer), and you have to make the target using only the
> numbers you're given, and +,-,* and / (and any number of brackets you
> like). You're not allowed fractions as intermediate values. So, given
> 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21.
>

Neat problem!  I couldn't help but have a go.  I have no idea how
efficient it is, I didn't think too much before I started typing :)


def partitions(l):
split(l) -> an iterator over all partitions of l into two
lists

There is no repetition provided that all elements of l are
distinct."""
# Works only for lists of length < 8*size(int) due to xrange
limitations
for i in xrange(1, 2**len(l)-1, 2):
partition = [], []
for x in l:
i, r = divmod(i, 2)
partition[r].append(x)
yield partition

def calc(l, filter=lambda *x:x):
"""calc(l, filter) -> an iterator over all expressions involving
all
numbers in l

filter is a function that returns its two arguments with possible
side-effects. """
if len(l) == 1:
yield l[0], str(l[0])
else:
for l1, l2 in partitions(l):
for v1, s1 in calc(l1, filter):
for v2, s2 in calc(l2, filter):
yield filter(v1 + v2, '(%s+%s)' % (s1, s2))
yield filter(v1 * v2, '(%s*%s)' % (s1, s2))
if v1 > v2:
yield filter(v1 - v2, '(%s-%s)' % (s1, s2))
elif v2 > v1:
yield filter(v2 - v1, '(%s-%s)' % (s2,
s1))
if not v1 % v2:
yield filter(v1 / v2, '(%s/%s)' % (s1, s2))
elif not v2 % v1:
yield filter(v2 / v1, '(%s/%s)' % (s2, s1))


def print_filter(target):
"""print_filter(target) -> filter that prints all expressions that
equal target"""
def filter(v, s):
if v == target: print s
return v, s
return filter

class ShortestFilter(object):
def __init__(self, target):
self.shortest = None
self.target = target
def __call__(self, v, s):
if v == self.target:
if not self.shortest or len(self.shortest) > len(s):
self.shortest = s
return v, s

def countdown(numbers, target):
"""countown(numbers, target) -> None -- print all countdown
solutions"""
for dummy in calc(numbers, print_filter(target)): pass

def best_countdown(numbers, target):
"""best_countdown(numbers, target) -> str -- return shortest
solution"""
filter = ShortestFilter(target)
for dummy in calc(numbers, filter): pass
return filter.shortest

>>> countdown([7,8,50,8,1,3], 923)
(50*8)-1)/3)*7)-8)
(50*8)-1)*7)/3)-8)
(8*50)-1)/3)*7)-8)
(8*50)-1)*7)/3)-8)
>>> print best_countdown([100,9,7,6,3,1], 234)
(((1+(3*6))+7)*9)


--
Arnaud

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


Re: Looping through the gmail dot trick

2008-01-20 Thread Steven D'Aprano
On Sun, 20 Jan 2008 21:13:03 +, Neil Hodgson wrote:

> Martin Marcher:
> 
>> are you saying that when i have 2 gmail addresses
>> 
>> "[EMAIL PROTECTED]" and
>> "[EMAIL PROTECTED]"
>> 
>> they are actually treated the same? That is plain wrong and would break
>> a lot of mail addresses as I have 2 that follow just this pattern and
>> they are delivered correctly!
> 
> This is a feature of some mail services such as Gmail, not of email
> addresses generically. One use is to provide a set of addresses given
> one base address. '+' works as well as '.' so when I sign up to service
> monty I give them the address [EMAIL PROTECTED] Then when I
> receive spam at nyamatongwe+monty, I know who to blame and what to
> block.

Technically, everything in the local part of the address (the bit before 
the @ sign) is supposed to be interpreted *only* by the host given in the 
domain (the bit after the @ sign). So if Gmail wants to interpret 
"[EMAIL PROTECTED]" and "[EMAIL PROTECTED]" the same, they can.

Or for that matter, "[EMAIL PROTECTED]". Although that would be silly.

Postfix, I think, interpets "foo+bar" the same as "foo".


-- 
Steven


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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 20 jan, 23:19, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > But for different reasons I also want to get the absolute path of
> > Python install directory (not only the executable under Linux) and
> > site-packages directory.
>
> The Python install directory is available as sys.prefix. The
> site-packages directory is
> sys.prefix+"lib/python"+x.y+"/site-packages (where x.y is from
> sys.version_info).
>
> HTH,
> Martin

http://forum.ubuntu-fr.org/viewtopic.php?id=184199

>>> import distutils.sysconfig
>>> distutils.sysconfig.get_python_lib()
'/usr/lib/python2.5/site-packages'

get_python_lib(plat_specific=0, standard_lib=0, prefix=None)
Return the directory containing the Python library (standard
or
site additions).

If 'plat_specific' is true, return the directory containing
platform-specific modules, i.e. any module from a non-pure-
Python
module distribution; otherwise, return the platform-shared
library
directory.  If 'standard_lib' is true, return the directory
containing standard Python library modules; otherwise, return
the
directory for site-specific modules.

If 'prefix' is supplied, use it instead of sys.prefix or
sys.exec_prefix -- i.e., ignore 'plat_specific'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Unfortunately I realise I stated the problem imprecisely. You're only
> allowed to use each number once (otherwise there's a trivial solution
> for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times
> for target y given any source number x). Trying your program on 234
> from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times.

Here's an inefficient solution, that doesn't find 234 but finds 253.
If you see a double post, it's because I posted something similar a
little while ago but cancelled it since it had a bug.  I'm not sure
this one is correct either ;-).

from operator import *

def countdown(nums, trace='', ops=[add,mul,sub,div]):
n0,n1s = nums[0], nums[1:]
if not n1s:
yield n0, str(n0)
return
for f in ops:
for r,t in countdown(n1s, trace, [add, mul, sub]):
if f != div or r != 0 and n0 % r == 0:
yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t)

def find_repr(target, nums):
# print all representations of target from nums
for x,t in countdown(nums):
if x == target:
print x,t

find_repr(253, [100,9,7,6,3,1])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread John Machin
On Jan 21, 8:58 am, pythonewbie <[EMAIL PROTECTED]> wrote:
> I just would like to know if I would ALWAYS find the install directory
> in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> platform and sys.path[2] and site-packages directory in sys.path[6] on
> any Linux platform.
>
> If the reply is : "YES you can be sure of it !"

No, you can't be sure of any such thing. In general in computing
assuming a fixed position in a variable-length list is a nonsense.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> from pprint import pprint as pp
>>> pp([(x, p) for x, p in enumerate(sys.path)])
[(0, ''),
 (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'),
 (2, 'C:\\WINDOWS\\system32\\python25.zip'),
 (3, 'c:\\python25\\DLLs'),
 (4, 'c:\\python25\\lib'),
 (5, 'c:\\python25\\lib\\plat-win'),
 (6, 'c:\\python25\\lib\\lib-tk'),
 (7, 'c:\\python25'),
 (8, 'c:\\python25\\lib\\site-packages'),
 (9, 'c:\\python25\\lib\\site-packages\\win32'),
 (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'),
 (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')]
>>>

Something like this might be more reliable:

>>> import sys, re
>>> for p in sys.path:
...m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p)
...if m:
...   print m.group(1, 0)
...   break
... else:
...raise Exception('Huh?')
...
('c:\\python25', 'c:\\python25\\lib\\site-packages')
>>>

>
> All would be great for me and I would be ready to create a script to
> detect with a reliable manner the installation dir. et site-packages
> dir. for all my Linux/Win32 Python apps.

You mentioned Python versions back to 2.1 earlier. However you
evidently haven't bothered to start up Python 2.1 and look at
sys.path:

C:\junk>\python21\python
Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license" for more information.
>>> import sys; sys.path
['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\
\python21\\lib\\
plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21']
>>>

Before you rush out and re-invent the wheel, have a look at this:

http://www.python.org/community/sigs/current/distutils-sig/

You may like to re-ask your questions on the distutils mailing list.

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 20 jan, 23:55, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> pythonewbie schrieb:
>
>
>
> > On 20 jan, 20:59, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> pythonewbie schrieb:
>
> >>> On 20 jan, 19:50, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>  pythonewbie schrieb:
> > On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
> >> pythonewbie wrote:
> >>> I am stucked on creating a function to get the Python install
> >>> directory (and site-packages directory) with a 100% reliable method...
> >> Only one method is 100% reliable:
> >> try:
> >> import yourextension
> >> except ImportError:
> >> available = False
> >> else:
> >> available = True
> >> Christian
> > Hi Christian,
> > OK thanks, interesting to detect if an extension is available or not.
> > But for different reasons I also want to get the absolute path of
> > Python install directory (not only the executable under Linux) and
> > site-packages directory.
> > How could I proceed ?
>  Maybe sys.path is a starter?
>  Diez
> >>> Yes, it is, but my problem is that I am not sure to find the
> >>> information I need at the same position of the list generated by
> >>> sys.path.
> >>> I explain, for Win32, I find install directory using sys.path[6] and
> >>> site-package directory using sys.path[7], for Linux I find install
> >>> directory using sys.path[2] and site-package directory using
> >>> sys.path[6].
> >>> For my tests, I have used XP Pro and Ubuntu Gutsy.
> >>> I am not sure to find these information at the same position in the
> >>> sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD
> >>> and using Python v2.1 2.2 2.3 etc ?
> >>> This why I'm asking experienced programmers of this usenet group for
> >>> advices.
> >> Sorry, I missed your first post. However, I don't see what your problem
> >> actually is. If you want to look for any extension, you need to consider
> >> whatever can be seen in the sys.path. So what do you care about the
> >> order of them?
>
> >> Diez
>
> > I just would like to know if I would ALWAYS find the install directory
> > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > any Linux platform.
>
> > If the reply is : "YES you can be sure of it !"
>
> > All would be great for me and I would be ready to create a script to
> > detect with a reliable manner the installation dir. et site-packages
> > dir. for all my Linux/Win32 Python apps.
>
> > Thanks for your interest on this topic.
>
> I doubt that you can say such things. You can even manipulate the path
> at runtime.
>
> And I still don't understand WHY you want that? If you want
> site-packages, why don't you loop through the paths until you find it?
>
> Diez

Because the solution using distutils.sysconfig.get_python_lib() is
very smart !
Cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread Diez B. Roggisch
pythonewbie schrieb:
> On 20 jan, 20:59, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> pythonewbie schrieb:
>>
>>
>>
>>> On 20 jan, 19:50, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
 pythonewbie schrieb:
> On 20 jan, 12:20, Christian Heimes <[EMAIL PROTECTED]> wrote:
>> pythonewbie wrote:
>>> I am stucked on creating a function to get the Python install
>>> directory (and site-packages directory) with a 100% reliable method...
>> Only one method is 100% reliable:
>> try:
>> import yourextension
>> except ImportError:
>> available = False
>> else:
>> available = True
>> Christian
> Hi Christian,
> OK thanks, interesting to detect if an extension is available or not.
> But for different reasons I also want to get the absolute path of
> Python install directory (not only the executable under Linux) and
> site-packages directory.
> How could I proceed ?
 Maybe sys.path is a starter?
 Diez
>>> Yes, it is, but my problem is that I am not sure to find the
>>> information I need at the same position of the list generated by
>>> sys.path.
>>> I explain, for Win32, I find install directory using sys.path[6] and
>>> site-package directory using sys.path[7], for Linux I find install
>>> directory using sys.path[2] and site-package directory using
>>> sys.path[6].
>>> For my tests, I have used XP Pro and Ubuntu Gutsy.
>>> I am not sure to find these information at the same position in the
>>> sys.path list using Win9x, Win2k, Ubuntu Dapper, Redhat FC6, FreeBSD
>>> and using Python v2.1 2.2 2.3 etc ?
>>> This why I'm asking experienced programmers of this usenet group for
>>> advices.
>> Sorry, I missed your first post. However, I don't see what your problem
>> actually is. If you want to look for any extension, you need to consider
>> whatever can be seen in the sys.path. So what do you care about the
>> order of them?
>>
>> Diez
> 
> I just would like to know if I would ALWAYS find the install directory
> in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> platform and sys.path[2] and site-packages directory in sys.path[6] on
> any Linux platform.
> 
> If the reply is : "YES you can be sure of it !"
> 
> All would be great for me and I would be ready to create a script to
> detect with a reliable manner the installation dir. et site-packages
> dir. for all my Linux/Win32 Python apps.
> 
> Thanks for your interest on this topic.


I doubt that you can say such things. You can even manipulate the path 
at runtime.

And I still don't understand WHY you want that? If you want 
site-packages, why don't you loop through the paths until you find it?

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


RE: Looping through the gmail dot trick

2008-01-20 Thread Delaney, Timothy (Tim)
Steven D'Aprano wrote:

> Postfix, I think, interpets "foo+bar" the same as "foo".

Gmail does the same. It's quite useful - apart from using it to
determine which site I signed up to has sent me mail, I also use it so I
can have multiple Guild Wars accounts using the same email account e.g.

[EMAIL PROTECTED]
[EMAIL PROTECTED]

All resolve to @gmail.com. I have a couple of spare accounts so when
friends or relative visit we can all play together ...

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread John Machin
On Jan 21, 11:00 am, pythonewbie <[EMAIL PROTECTED]> wrote:
> On 21 jan, 00:09, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jan 21, 8:58 am, pythonewbie <[EMAIL PROTECTED]> wrote:
>
> > > I just would like to know if I would ALWAYS find the install directory
> > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > > any Linux platform.
>
> > > If the reply is : "YES you can be sure of it !"
>
> > No, you can't be sure of any such thing. In general in computing
> > assuming a fixed position in a variable-length list is a nonsense.
>
> > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > (Intel)] on win32
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > import sys
> > >>> from pprint import pprint as pp
> > >>> pp([(x, p) for x, p in enumerate(sys.path)])
>
> > [(0, ''),
> >  (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'),
> >  (2, 'C:\\WINDOWS\\system32\\python25.zip'),
> >  (3, 'c:\\python25\\DLLs'),
> >  (4, 'c:\\python25\\lib'),
> >  (5, 'c:\\python25\\lib\\plat-win'),
> >  (6, 'c:\\python25\\lib\\lib-tk'),
> >  (7, 'c:\\python25'),
> >  (8, 'c:\\python25\\lib\\site-packages'),
> >  (9, 'c:\\python25\\lib\\site-packages\\win32'),
> >  (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'),
> >  (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')]
>
> > Something like this might be more reliable:
>
> > >>> import sys, re
> > >>> for p in sys.path:
>
> > ...m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p)
> > ...if m:
> > ...   print m.group(1, 0)
> > ...   break
> > ... else:
> > ...raise Exception('Huh?')
> > ...
> > ('c:\\python25', 'c:\\python25\\lib\\site-packages')
>
> > > All would be great for me and I would be ready to create a script to
> > > detect with a reliable manner the installation dir. et site-packages
> > > dir. for all my Linux/Win32 Python apps.
>
> > You mentioned Python versions back to 2.1 earlier. However you
> > evidently haven't bothered to start up Python 2.1 and look at
> > sys.path:
>
> > C:\junk>\python21\python
> > Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
> > win32
> > Type "copyright", "credits" or "license" for more information.>>> import 
> > sys; sys.path
>
> > ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\
> > \python21\\lib\\
> > plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21']
>
> > Before you rush out and re-invent the wheel, have a look at this:
>
> >http://www.python.org/community/sigs/current/distutils-sig/
>
> > You may like to re-ask your questions on the distutils mailing list.
>
> > HTH,
> > John
>
> Hi John,
>
> Thanks for your help and suggestions.
>
> Your code is very interesting for the newbie that I am.
>
> But I have not understood your two last suggestions...
>
> As a newbie, I have asked usenet for help in order to get a easy/
> convenient way to get the site-packages directory, and the best reply
> I obtained, was to use the function
> distutils.sysconfig.get_python_lib().
>
> This function is a really good way to avoid to re-invent the wheel to
> get what I wanted !
>

I am talking about your underlying goal "My goal is to verify if an/
several extension(s) are installed and to automatically install the
missing ones on Linux or Win32." ... you may well find that there is
at least one wheel for "automatically install".

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


Re: Basic inheritance question

2008-01-20 Thread Bjoern Schliessmann
(messed up references?)

Lie wrote:

> Please again, stop taking letters to the words

Please don't mix up followups.

Regards,


Björn

-- 
BOFH excuse #11:

magnetic interference from money/credit cards

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


RE: plz help how to print python variable using os.system()

2008-01-20 Thread Delaney, Timothy (Tim)
Grant Edwards wrote:

> On 2008-01-16, Lutz Horn <[EMAIL PROTECTED]> wrote:
>> Hi,
>> 
>> On Wed, 16 Jan 2008 05:29:08 -0800 (PST), [EMAIL PROTECTED]
>> said: 
>>> var = "/home/anonymous"
>>> os.system("echo $var)
>> 
>> os.system("echo %s" % var)
> 
> Though one wonders why one would do that instead of simply doing
> 
> print var

Only reason I can think of is to learn how to use os.system before doing
something larger. But the OP should be using subprocess or popen in most
cases anyway ...

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Mel
[EMAIL PROTECTED] wrote:
> Ever since I learnt to program I've always loved writing solvers for
> the Countdown numbers game problem in different languages, and so now
> I'm wondering what the most elegant solution in Python is.
> 
> If you don't know the game, it's simple: you're given six randomly
> chosen positive integers, and a target (another randomly chosen
> positive integer), and you have to make the target using only the
> numbers you're given, and +,-,* and / (and any number of brackets you
> like). You're not allowed fractions as intermediate values. So, given
> 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21.
> 
> So what's the best algorithm? And, what's the most elegant way to code
> it in Python? I've posted my most elegant version below (I have a
> faster version which is slightly less elegant). Can anyone do better?

I found that postfix notation made it easy to run up all the possible 
expressions based on permutations of the available numbers.  Don't 
know where my source code is ... have to look.

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


Re: Basic inheritance question

2008-01-20 Thread Lie
On Jan 16, 9:23 pm, Bjoern Schliessmann  wrote:
> Lie wrote:
> > [EMAIL PROTECTED]> wrote:
> >> I used to systematically use it - like I've always systematically
> >> used 'this' in C++  and Java.
>
> > And that is what reduces readability.
>
> IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion
> comes up here. If I have learned one thing from those very lengthy
> discussions, it's that Python's "self" handling is not going to
> change.

And ah... yes, I don't wish it go away either. In VB, excessive Me
reduces readability, but in Python it doesn't.

> > A proficient VB/C/Java programmer would frown upon the extra,
> > unneeded garbage as they thought it was clear already that the
> > variable refers to a class-level variable.
>
> C programmers surely have no opinion concerning C because it has no
> native classes.

C-family, ok? Please stop taking my words to its letters.

> Personally, I've seen many C++ programs with complex class designs
> where it definitely helps to consistently use "this->". I cannot
> remember all local (and global) variables in bigger methods.

In that case, you have the _option_ to do it.

> > There is one major positive point: convenience and shorter code.
> > (isn't that two?)
>
> Shorter code is not per se positive, neither is it convenient. If it
> was, everyone would use perl.

Not always, but sometimes it do help not to be obliged to use the
class name especially in short, simple programs (as opposed to big
projects that requires hundreds of thousands of lines of code) that is
changed frequently (being in heavy development). A good real-life
example for this would be for new learner of programming or the
language, they would write a lot of ten liners that is changed a LOT
of times due to their (yet) incomplete understanding of the concepts.

> >> it's the first argument of the function - which usually happens to be
> >> the current instance when the function is used as a method.
>
> > And that's the point, self (or anything you name it) is almost always
> > the current instance
>
> # this is a plain function. In this function,
> # 'obj' can be whatever that happens to have a (numeric)
> # 'stuff' attribute
> def func(obj, arg):
>    return (obj.stuff + arg) / 2.0
>
> # this is a class with an instance attribute 'stuff'
> class Foo(object):
>     def __init__(self, bar):
>       self.stuff = bar + 42
>
> # this is another (mostly unrelated) class
> # with a class attribute 'stuff'
> class Bar(object):
>    stuff = 42
>
> # this is a dummy container class:
> class Dummy(object): pass
>
> # now let's play:
> import new
>
> d = Dummy()
> d.stuff = 84
> print func(d, 1)
>
> d.baaz = new.instancemethod(func, d, type(d))
> print d.baaz(2)
>
> f = Foo(33)
> print func(f, 3)
> Foo.baaz = func
> f.baaz(4)
>
> print func(Bar, 5)
> Bar.baaz = classmethod(func)
> Bar.baaz(6)
>
> >  and that makes it functionally the same as Me and
> > this in VB and Java.
>
> Depends on the context, cf above !-)

Please again, stop taking letters to the words, I don't meant them to
be exactly the same, rather the same would meant that they generally
can be considered equal, exceptions exists of course. And btw, I don't
understand what you meant by your example, they seemed to be a
completely OK program for me, even though it's a bit confusing to
follow[2].

[2] btw, the reason it's a bit confusing to follow is one of my
points: It is a Bad Thing(tm) to use the same name for different
variables even in a language like Python that enforce explicit naming
of classes

> >>> Most other languages
> >>> 1) automatically assign the containing class' object
> >> s/containing class' object/current instance/
>
> >>> in a keyword
> >>> (Java: this, VB: Me) behind the screen,
>
> >> That's not very far from what a Python method object does -
> >> automatically assign the current instance to something. The difference
> >> is that Python uses functions to implement methods (instead of having
> >> two distinct contructs), so the only reliable way to "inject" the
> >> reference to the current instance is to pass it as an argument to the
> >> function (instead of making it pop from pure air).
>
> > It isn't very far, but Python makes it obvious about the assignment
> > (not behind the screen).
>
> Exactly. And given both the simplicity of the solution and what it let
> you do, that's a *very* GoodThing(tm) IMHO.

I agree, it's a Good Thing but it doesn't make the point less pointy,
the difference between Me/this and self is just the explicit
assignment. Other things that is possible because of the explicit
assignment is just a "coincidence" of design choice.

> >>> and 2) automatically searches
> >>> variable name in both the local variable table and the containing
> >>> class variable table  (so to refer to a class variable named var from a
> >>> method inside the class, we only need to write var, not self.var as in
> >>> python).
> >> This - as you know - cannot work well with Python's scoping rules and

Re: Memory errors with imaplib

2008-01-20 Thread Grant Edwards
On 2008-01-20, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> The problem and the one-line soulution have been known for over
>> two years and it's still an open bug?
>
> Nobody was interested to provide a patch. I raised the level of the bug.
> It's going to be fixed soonish.

If the solution shown in the bug report is correct, I'd be more
than happy to generate a patch.

-- 
Grant

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-20 Thread pythonewbie
On 21 jan, 00:09, John Machin <[EMAIL PROTECTED]> wrote:
> On Jan 21, 8:58 am, pythonewbie <[EMAIL PROTECTED]> wrote:
>
> > I just would like to know if I would ALWAYS find the install directory
> > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > any Linux platform.
>
> > If the reply is : "YES you can be sure of it !"
>
> No, you can't be sure of any such thing. In general in computing
> assuming a fixed position in a variable-length list is a nonsense.
>
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import sys
> >>> from pprint import pprint as pp
> >>> pp([(x, p) for x, p in enumerate(sys.path)])
>
> [(0, ''),
>  (1, 'c:\\python25\\lib\\site-packages\\setuptools-0.6c3-py2.5.egg'),
>  (2, 'C:\\WINDOWS\\system32\\python25.zip'),
>  (3, 'c:\\python25\\DLLs'),
>  (4, 'c:\\python25\\lib'),
>  (5, 'c:\\python25\\lib\\plat-win'),
>  (6, 'c:\\python25\\lib\\lib-tk'),
>  (7, 'c:\\python25'),
>  (8, 'c:\\python25\\lib\\site-packages'),
>  (9, 'c:\\python25\\lib\\site-packages\\win32'),
>  (10, 'c:\\python25\\lib\\site-packages\\win32\\lib'),
>  (11, 'c:\\python25\\lib\\site-packages\\Pythonwin')]
>
>
>
> Something like this might be more reliable:
>
> >>> import sys, re
> >>> for p in sys.path:
>
> ...m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p)
> ...if m:
> ...   print m.group(1, 0)
> ...   break
> ... else:
> ...raise Exception('Huh?')
> ...
> ('c:\\python25', 'c:\\python25\\lib\\site-packages')
>
>
>
> > All would be great for me and I would be ready to create a script to
> > detect with a reliable manner the installation dir. et site-packages
> > dir. for all my Linux/Win32 Python apps.
>
> You mentioned Python versions back to 2.1 earlier. However you
> evidently haven't bothered to start up Python 2.1 and look at
> sys.path:
>
> C:\junk>\python21\python
> Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
> win32
> Type "copyright", "credits" or "license" for more information.>>> import sys; 
> sys.path
>
> ['', 'C:\\junk', 'C:\\python21\\DLLs', 'C:\\python21\\lib', 'C:\
> \python21\\lib\\
> plat-win', 'C:\\python21\\lib\\lib-tk', 'C:\\python21']
>
>
>
> Before you rush out and re-invent the wheel, have a look at this:
>
> http://www.python.org/community/sigs/current/distutils-sig/
>
> You may like to re-ask your questions on the distutils mailing list.
>
> HTH,
> John

Hi John,

Thanks for your help and suggestions.

Your code is very interesting for the newbie that I am.

But I have not understood your two last suggestions...

As a newbie, I have asked usenet for help in order to get a easy/
convenient way to get the site-packages directory, and the best reply
I obtained, was to use the function
distutils.sysconfig.get_python_lib().

This function is a really good way to avoid to re-invent the wheel to
get what I wanted !

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Arnaud Delobelle
On Jan 20, 5:41 pm, [EMAIL PROTECTED] wrote:
> Ever since I learnt to program I've always loved writing solvers for
> the Countdown numbers game problem in different languages

Ok so here's a challenge I just thought of:

What is (or are) the set of 6 starting numbers which are such that the
smallest target they can't reach is maximal?

E.g for 1, 2, 3, 4, 5, 6 the smallest target they can't reach is 284:

100 = ((5*4)*(3+2))
101 = (5+((4*3)*(6+2)))
102 = (((6*5)+4)*3)
103 = ((5*((6*4)-3))-2)
...
280 = ((5*(4+3))*(6+2))
281 = (((5*(4+3))*(6+2))+1)
282 = ((4+((6*5)*3))*(2+1))
283 = (3+(((5*4)*2)*(6+1)))
284 : can't be done

For 2, 3, 5, 8, 9, 10, the smallest unreachable target is 796 (and
there are five others: 829, 956, 961, 964, 991).

For 2, 4, 5, 8, 9, 10, the smallest is 807 (but there are 23 others)

Time to go to bed :)

--
Arnaud

PS: apologies if I got the results wrong...

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Arnaud Delobelle
On Jan 21, 1:07 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> On Jan 20, 5:41 pm, [EMAIL PROTECTED] wrote:
>
> > Ever since I learnt to program I've always loved writing solvers for
> > the Countdown numbers game problem in different languages
>
> Ok so here's a challenge I just thought of:
>
> What is (or are) the set of 6 starting numbers which are such that the
> smallest target they can't reach is maximal?

Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999.

The question remains if we lift the upper limit of 999...

Time to really go to bed :)

--
Arnaud

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


PyCon 2008 Registration Open!

2008-01-20 Thread David Goodger

I am pleased to announce that PyCon 2008 registration is now open!

http://us.pycon.org/2008/registration/

Early-bird registration is open until February 20, so there's one
month to register at the low rates.  Regular on-line registration will
be available from February 21 through March 7.

PyCon 2008 will be held from March 13 through 20 in Chicago:

* Tutorials: Thursday, March 13
* Conference: Friday, March 14, through Sunday, March 16
* Sprints: Monday, March 17 through Thursday, March 20

Register early, especially if you'd like to attend a tutorial or
three, as tutorials fill up early.  And yes, you heard that correctly
-- this year, we have three tutorial sessions: morning, afternoon, and
evening.  There are 29 great tutorials to choose from.  More about the
tutorials soon, but for now, you can check out the descriptions
yourself here: http://us.pycon.org/2008/tutorials/schedule/

The talk schedule is also up (in a preliminary form), although some
changes are expected: http://us.pycon.org/2008/conference/schedule/

Hotel reservations are also open:

https://www.cteusa.com/pycon1/

The rate is $99/night plus tax ($112/night net), also until
February 20.  More hotel information is here:
http://us.pycon.org/2008/registration/hotel/

See the PyCon web site for complete details:

http://us.pycon.org/2008/

Thanks to the PyCon organizers for developing the software, providing
the website content, testing & debugging.  PyCon is a community
conference, of, by, and for the Python community.  There is still
much to do, and you can help!

http://us.pycon.org/2008/helping/

See you in Chicago!

David Goodger
PyCon 2008 Chair



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

Re: TopSort in Python?

2008-01-20 Thread Tim Peters
[EMAIL PROTECTED]
> Thanks for the topsort code.  It would be useful in a project I'm
> working on.  Can I use the code for free under public domain?  Thanks!

If I ran the world, everything I posted to a public place would be
public domain.  Alas, the last lawyer who typed at me about this
insisted that an individual in the USA cannot meaningfully disclaim
copyright, so perhaps you're required to pay me millions of dollars
instead ;-)

To keep him happy and you solvent, I hereby license the code under the
MIT license:

http://www.opensource.org/licenses/mit-license.php

Copyright (c) 1999-2008 Tim Peters

Permission is hereby granted, free of charge, to any person obtaining
a copy
of this software and associated documentation files (the "Software"),
to deal
in the Software without restriction, including without limitation the
rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be
included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
THE SOFTWARE.
-- 
http://mail.python.org/mailman/listinfo/python-list


Bittorent client with google talk interface

2008-01-20 Thread Astan Chee

Hi,
I dont know where to send this but I'll try here. I recently took the 
newest version of ABCTorrent and its code and added some features to it 
that I find very useful. Basically it is like a webUI except it connect 
to google's google talk and you can issue commands from it. Kinda like a 
command line bittorrent client. So when you start up the client, you can 
enter your google talk account information and using another google talk 
account (from somewhere else) send commands (system and torrent 
related). I've also added some proxy support for it since Im constantly 
behind proxies (but not at work or school). I use windows XP and 
wxPython 2.6.3.3  and python 2.5 so I dont know how it 
will behave in newer versions of things. There are also new modules that 
it requires (win32api) for file operations that you might need before 
compiling this. The main script to run this all is the abc.py script. 
Also I havent done much brushing up with the GUI so it wont look like 
the fastest ship around. Any suggestions or changes for further improvement?
Also for anyone who is developing or has used this before and tinkered 
with it Im pretty sure Im doing something wrong calling the interface 
from the code because it (wx) sporadically crashes; Im not sure what to 
do since I dont know how to call it properly. Does anyone have any idea?


Cheers
Astan

The file can be downloaded here:
http://gtalktorrent.googlecode.com/files/3.1.0.zip
-- 
http://mail.python.org/mailman/listinfo/python-list

dynamic type variable

2008-01-20 Thread J. Peng
Python's variable is dynamic type,is it?
But why this can't work?

>>> 3 + 'a'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'


So I see the number 3 can't be converted to string type automacially.
-- 
http://mail.python.org/mailman/listinfo/python-list


When is min(a, b) != min(b, a)?

2008-01-20 Thread Albert Hopkins
This issue may have been referred to in 
news:<[EMAIL PROTECTED]> but I didn't 
entirely understand the explanation.  Basically I have this:

>>> a = float(6)
>>> b = float('nan')
>>> min(a, b)
6.0
>>> min(b, a)
nan
>>> max(a, b)
6.0
>>> max(b, a)
nan

Before I did not know what to expect, but I certainly didn't expect 
this.  So my question is what is the min/max of a number and NaN or is it 
not defined (for which I would have expected either an exception to be 
raised or NaN returned in each case).

As a corrollary would I be able to rely on the above behavior or is it 
subject to change (to fix a bug in min/max perhaps :-)?

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


auto import

2008-01-20 Thread alf
Hi,

is there any way to tweak __import__ so it imports module with another 
arbitrary selected module included?

For instance I have my mylibs.py module. Then when I import a 
oneofhundredssmallmodules.py module from other place the mylibs.py is 
automatically imported without a explicit import. The effect is the same 
like below:

module oneofhundredssmallmodules.py:
import * from mylibs


In my software I hundreds of small modules constituting certain custom 
scripts. I need an ability to dynamically control what is imported into 
  them before custom code kicks in.


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


Re: dynamic type variable

2008-01-20 Thread Gabriel Genellina
En Mon, 21 Jan 2008 00:37:36 -0200, J. Peng <[EMAIL PROTECTED]>  
escribi�:

> Python's variable is dynamic type,is it?

No. Python has objects, and names that refer to those objects. Objects  
have a type, which can't change once the object is created. But a name may  
refer to different objects of different types at different times.

See http://effbot.org/zone/python-objects.htm

> But why this can't work?
>
 3 + 'a'
> Traceback (most recent call last):
> File "", line 1, in ?
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
>
> So I see the number 3 can't be converted to string type automacially.

Python never "converts" anything, except numeric types in expressions  
(2+3.0, sqrt(5L)) and sometimes string/unicode.

-- 
Gabriel Genellina

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

Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Terry Jones
Here's a solution that doesn't use any copying of lists in for recursion.
It also eliminates a bunch of trivially equivalent solutions. The countdown
function is 37 lines of non-comment code.  Sample (RPN) output below.

Terry


from operator import *

def countdown(target, nums, numsAvail, value, partialSolution, solutions, 
ops=(add, mul, sub, div)):
if not any(numsAvail):
# Ran out of available numbers. Add the solution, if we're right.
if value == target:
solutions.add(tuple(partialSolution))
elif value is None:
# Use each distinct number as a starting value.
used = set()
for i, num in enumerate(nums):
if num not in used:
numsAvail[i] = False
used.add(num)
partialSolution.append(num)
countdown(target, nums, numsAvail, num, partialSolution, 
solutions, ops)
numsAvail[i] = True
partialSolution.pop()
else:
for op in ops:
for i, num in enumerate(nums):
if numsAvail[i]:
numsAvail[i] = False
moreAvail = any(numsAvail)
try:
lastNum, lastOp = partialSolution[-2:]
except ValueError:
lastNum, lastOp = partialSolution[-1], None
# Don't allow any of:
if not any((
# Div: after mul, by 1, by 0, producing a fraction.
(op == div and (lastOp == 'mul' or num <= 1 or value % 
num != 0)),
# If initial mul/add, canonicalize to 2nd operator 
biggest.
((op == mul or op == add) and lastOp is None and num > 
lastNum),
# Don't all subtracting 0 (instead allow adding 0).
(op == sub and num == 0),
# Don't allow adding 0 unless it's the very last thing 
we do.
(op == add and num == 0 and moreAvail),
# Don't allow mult by 1 unless it's the very last thing 
we do.
(op == mul and num == 1 and moreAvail),
# Don't allow sub after add (allow add after sub).
(op == sub and lastOp == 'add'),
# If same op twice in a row, canonicalize operand order.
(lastOp == op.__name__ and num > lastNum)
)):
partialSolution.extend([num, op.__name__])
countdown(target, nums, numsAvail, op(value, num), 
partialSolution, solutions, ops)
del partialSolution[-2:]
numsAvail[i] = True

for nums, target in (((100, 9, 7, 6, 3, 1), 253),
 ((100, 9, 7, 6, 3, 1), 234),
 ((2, 3, 5), 21),
 ((7, 8, 50, 8, 1, 3), 923),
 ((8, 8), 16),
 ((8, 8, 8), 8),
 ((8, 0), 8),
 ((7,), 8),
 ((), 8),
 ((8, 8, 8, 8), 32)):
print "Target %d, numbers = %s" % (target, nums)
solutions = set()
countdown(target, nums, [True,] * len(nums), value=None, 
partialSolution=[], solutions=solutions)
for s in solutions: print '\t', s


This produces:

Target 253, numbers = (100, 9, 7, 6, 3, 1)
(7, 6, 'add', 3, 'add', 1, 'add', 9, 'mul', 100, 'add')
(7, 6, 'mul', 9, 'add', 3, 'mul', 100, 'add', 1, 'mul')
(3, 1, 'add', 6, 'mul', 7, 'sub', 9, 'mul', 100, 'add')
(100, 7, 'sub', 6, 'sub', 3, 'mul', 9, 'sub', 1, 'add')
(7, 1, 'add', 6, 'mul', 3, 'mul', 100, 'add', 9, 'add')
Target 234, numbers = (100, 9, 7, 6, 3, 1)
(6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div')
(100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add')
(7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul')
(100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul')
(7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add')
(6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul')
(100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul')
(100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul')
(100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add')
(100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul')
(7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add')
(100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div')
(100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul')
(100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul')
Target 21, numbers = (2, 3, 5)
(5, 2, 'add', 3, 'mul')
Target 923, numbers = (7, 8, 50, 8, 1, 3)
(50, 8, 'mul', 1, 'sub', 3, 'div', 7, 'mul', 8, 'sub')
Target 16, numbers = (8, 8)
(8, 8, 'add')
Target 8, numbers = (8, 8, 8)
(8, 8, 'sub', 8, 

problem with 'global'

2008-01-20 Thread oyster
why the following 2 prg give different results? a.py is ok, but b.py
is 'undefiend a'
I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
v.1310 32 bit (Intel)] on win32
#a.py
def run():
if 1==2:# note, it always False
global a
a=1

run()
a

#b.py
def run():
a=1

run()
a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Paul Rubin
Terry Jones <[EMAIL PROTECTED]> writes:
> Here's a solution that doesn't use any copying of lists in for recursion.
> It also eliminates a bunch of trivially equivalent solutions. The countdown
> function is 37 lines of non-comment code.  Sample (RPN) output below.

Nice, I realized after I posted my 2nd solution that it was missing
some cases and it's good to see confirmation that 239 is reachable.
I'll see if I can fix my version.  I think the list copying is ok
given that the recursion depth always must be fairly small if the
generator is to complete in any reasonable amount of time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a portable way to tell if data is available on a pipe?

2008-01-20 Thread John Nagle
I need some way to find out if a pipe has data available for
a read without blocking if it does not.

"select", unfortunately, doesn't work on pipes on Windows.

I think there's something proposed for Python 3000, but that's
not useful now.

I'd like to avoid having a thread to manage each pipe, but if I
have to, so be it.

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


Re: object scope

2008-01-20 Thread J. Peng
J. Peng 写道:
> Please see the code below,what's the scope for object "name"?
> I thought it should be located in the while block, but it seems not
> really,it can be accessed out of while (the db[name] statement).Thanks
> in advance.
> 
> 

sorry the before code seems be disordered,re-posted it.

db = {}
def newuser():
   prompt = 'login desired: '
   while 1:
 name = raw_input(prompt)
 if db.has_key(name):
   prompt = 'name taken, try another: '
   continue
 else:
   break
   pwd = raw_input('passwd: ')
   db[name] = pwd
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: dynamic type variable

2008-01-20 Thread Paddy
On Jan 21, 2:37 am, "J. Peng" <[EMAIL PROTECTED]> wrote:
> Python's variable is dynamic type,is it?
> But why this can't work?
>
> >>> 3 + 'a'
>
> Traceback (most recent call last):
> File "", line 1, in ?
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> So I see the number 3 can't be converted to string type automacially.

Hi,
You are probably confusing Dynamic typing with Weak typing.
Python is both dynamically and strongly typed. Perl is
both dynamically and weakly typed. It is Perls weak typing
that allows automatic conversion between dissimilar types.

See: http://en.wikipedia.org/wiki/Type_system

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


Our Bosch hid kit is $45/pc

2008-01-20 Thread housinghouse
We supply nice quality Bosch Hid Kit and Siemens Hid KitWe have
Promotion now...Our HID KIT is $45/pc..Please contact us as soon as
possibleOur website is www.housinghouse.comOur email is
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-20 Thread Bonjour
'NaN' means "Not a number". according to Python semantics, if you try
to compare it with any other float numbers, it should return FALSE.
just like
>>>
>>>1.0 > 'abc'
  False
>>>
Since it always return FALSE, it is not a surprise for your question.

If you wish to get infinitive number, you'd use 'inf' or '-inf', from
IEEE 754 semantics:
>>>a=float(6)
>>>b=float('inf')
>>>c=float('-inf')


Albert Hopkins wrote:
> This issue may have been referred to in
> news:<[EMAIL PROTECTED]> but I didn't
> entirely understand the explanation.  Basically I have this:
>
> >>> a = float(6)
> >>> b = float('nan')
> >>> min(a, b)
> 6.0
> >>> min(b, a)
> nan
> >>> max(a, b)
> 6.0
> >>> max(b, a)
> nan
>
> Before I did not know what to expect, but I certainly didn't expect
> this.  So my question is what is the min/max of a number and NaN or is it
> not defined (for which I would have expected either an exception to be
> raised or NaN returned in each case).
>
> As a corrollary would I be able to rely on the above behavior or is it
> subject to change (to fix a bug in min/max perhaps :-)?
-- 
http://mail.python.org/mailman/listinfo/python-list


object scope

2008-01-20 Thread J. Peng
Please see the code below,what's the scope for object "name"?
I thought it should be located in the while block, but it seems not
really,it can be accessed out of while (the db[name] statement).Thanks
in advance.


db = {}
def newuser():
prompt = 'login desired: '
while 1:
name = raw_input(prompt)
if db.has_key(name):
prompt = 'name taken, try another: '
continue
else:
break
pwd = raw_input('passwd: ')
db[name] = pwd
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with 'global'

2008-01-20 Thread Mel
oyster wrote:
> why the following 2 prg give different results? a.py is ok, but b.py
> is 'undefiend a'
> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
> v.1310 32 bit (Intel)] on win32
> #a.py
> def run():
> if 1==2:# note, it always False
> global a
> a=1
> 
> run()
> a
> 
> #b.py
> def run():
> a=1
> 
> run()
> a

The docs seem to be in  
but don't look all that helpful.  Probably the key is that global is 
not an executable statement, and isn't affected by being subordinate 
to an if statement.  In a.py the function has been primed to define a 
in the global namespace.  In b.py, not.

Docs do describe global as a "directive to the parser", even though 
it's lumped in with normal statements like print, return, yield, 
raise, etc.

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


Re: When is min(a, b) != min(b, a)?

2008-01-20 Thread Bonjour
'NaN' means "Not a number". according to Python semantics, if you try
to compare it with any other float numbers, it should return FALSE.
just like:

   >>>1.0 > 'abc'
  False

Since it always return FALSE, it is not a surprise for your question.

If you wish to get infinitive number, you'd use 'inf' for positive
infinitive or '-inf' for negative infinitive, from
IEEE 754 semantics, just like:

  >>>a=float(6)
  >>>b=float('inf')
  >>>c=float('-inf')

For more information, PEP-0754 may be helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-20 Thread Paddy
On Jan 21, 3:15 am, Albert Hopkins <[EMAIL PROTECTED]> wrote:
> This issue may have been referred to in
>  but I didn't
> entirely understand the explanation.  Basically I have this:
>
> >>> a = float(6)
> >>> b = float('nan')
> >>> min(a, b)
> 6.0
> >>> min(b, a)
> nan
> >>> max(a, b)
> 6.0
> >>> max(b, a)
> nan
>
> Before I did not know what to expect, but I certainly didn't expect
> this.  So my question is what is the min/max of a number and NaN or is it
> not defined (for which I would have expected either an exception to be
> raised or NaN returned in each case).
>
> As a corrollary would I be able to rely on the above behavior or is it
> subject to change (to fix a bug in min/max perhaps :-)?

I am definitely NOT a floating point expert, but I did find this:
http://en.wikipedia.org/wiki/IEEE_754r#min_and_max

P.S. What platform /Compiler are you using for Python?

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


Re: object scope

2008-01-20 Thread George Sakkis
On Jan 21, 12:16 am, "J. Peng" <[EMAIL PROTECTED]> wrote:

> Dennis Lee Bieber 写道:
>
> >The scope of "name" is the entire function; lacking a "global name"
> > statement, AND being on the left side of an assignment, it is a function
> > local name.
>
> Thank you. Does python have so-called 'block scope' object?

No, it doesn't; in most cases that you may care, a name's scope is
either local or global*.

> or if you can,please show me the doc for python's object scope.

http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html


George


* There is also class scope and lexical closures but most likely you
don't have to worry about them for now.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Iterate through slots

2008-01-20 Thread Gabriel Genellina
En Tue, 15 Jan 2008 16:35:52 -0200, Jared Grubb <[EMAIL PROTECTED]>  
escribi�:

> How can I iterate through the slots of a class, including those it  
> inherits
> from parent classes?
>
> class C(object):
>   __slots__ = ['a']
>
> class D(C):
>   __slots__ = ['b']
>

Iterate over all the class hierarchy keeping track of slot items:

def find_slots(cls):
   slots = set(getattr(cls, '__slots__', []))
   for base in cls.__bases__:
 slots.update(find_slots(base))
   return slots


-- 
Gabriel Genellina

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

newbie doubt ..numpy array

2008-01-20 Thread nodrogbrown
if this is too silly a qn pls forgive
I was learning numpy.ndarrays thru the tutorial.

myarr=numpy.array( [ [10, 20, 30, 40],[1,2,3,4],[5,6,7,8] ] )
if i want to access the element 3 i can do it by  myarr[1, 2]

but then myarr[1][2] will also give the same result..is there any
reason why two types of indexing is allowed?
gordon

p.s(i tried to post to numpy grp but it is not appearing there!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Arnaud Delobelle
On Jan 21, 3:19 am, Terry Jones <[EMAIL PROTECTED]> wrote:
> Here's a solution that doesn't use any copying of lists in for recursion.
> It also eliminates a bunch of trivially equivalent solutions. The countdown
> function is 37 lines of non-comment code.  Sample (RPN) output below.
>
> Terry

[snip code]

> This produces:
[...]
> Target 234, numbers = (100, 9, 7, 6, 3, 1)
>         (6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div')
>         (100, 1, 'sub', 3, 'div', 7, 'mul', 6, 'sub', 9, 'add')
>         (7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul', 1, 'mul')
>         (100, 7, 'sub', 3, 'div', 6, 'sub', 1, 'add', 9, 'mul')
>         (7, 6, 'mul', 3, 'mul', 1, 'sub', 100, 'add', 9, 'add')
>         (6, 9, 'sub', 7, 'mul', 1, 'sub', 100, 'add', 3, 'mul')
>         (100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul', 1, 'mul')
>         (100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div', 1, 'mul')
>         (100, 1, 'sub', 7, 'mul', 9, 'sub', 3, 'div', 6, 'add')
>         (100, 7, 'sub', 3, 'div', 1, 'sub', 9, 'add', 6, 'mul')
>         (7, 3, 'mul', 6, 'sub', 9, 'mul', 1, 'sub', 100, 'add')
>         (100, 7, 'mul', 6, 'sub', 1, 'sub', 9, 'add', 3, 'div')
>         (100, 9, 'add', 7, 'add', 1, 'add', 3, 'div', 6, 'mul')
>         (100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul', 1, 'mul')

In countdown you are not required to use all numbers to reach the
target.  This means you are missing solutions, e.g.
(1, 3, 6, 'mul', 'add', 7 , 'add', 9, 'mul')

After a quick glance at your code it seems to me that you can only
have solutions of the type:
(num, num, op, num, op, num, op, num, op, num, op)
this omits many possible solutions (see the one above).

--
Arnaud

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


Re: paging in python shell

2008-01-20 Thread Gabriel Genellina
En Mon, 14 Jan 2008 21:05:38 -0200, Ben Finney  
<[EMAIL PROTECTED]> escribi�:

> To my knowledge there's nothing in the default Python shell that
> enables what the OP is asking for. There are other Python shells, e.g.
> Idle, ipython, or a Python window inside Emacs, that may be better
> suited.

Yes, there is. Thanks to Tim Roberts who menctioned that the builtin help  
system implements paging internally, I looked at it. It's easy to use (but  
maybe too late for the OP):

Let Python determine the best pager available:

import pydoc
pydoc.pager(text)

(it may pipe the text into an external program like less or more). Or  
explicitely use the builtin pager:

import pydoc
pydoc.ttypager(text)


-- 
Gabriel Genellina

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

Re: When is min(a, b) != min(b, a)?

2008-01-20 Thread Albert Hopkins
On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote:
 
> I am definitely NOT a floating point expert, but I did find this:
> http://en.wikipedia.org/wiki/IEEE_754r#min_and_max
> 
> P.S. What platform /Compiler are you using for Python?

Linux with GCC 4

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Paul Rubin
Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> After a quick glance at your code it seems to me that you can only
> have solutions of the type:
> (num, num, op, num, op, num, op, num, op, num, op)
> this omits many possible solutions (see the one above).

Here's my latest, which I think is exhaustive, but it is very slow.
It prints a progress message now and then just to give the user some
sign of life.  It should print a total of 256-8 = 248 of those
messages and it takes around 20 minutes on my old 1 Ghz Pentium 3.  It
does find plenty of solutions for 234, e.g.

   234 mul(9,sub(mul(mul(6,mul(3,1)),7),100))

There are some obvious clunky ways to speed it up through memoizing
and symmetry folding but I can't help thinking there's a concise
elegant way to do that too.


from operator import *
from time import time, ctime
start_time = time()

def partition(k):
for i in xrange(1, (1<', n0s, f, '%.3f'%(time()-start_time)
for r0,t0 in countdown(n0s, trace, ams):
for r1,t1 in countdown(n1s, trace, ams):
if f != div or r1 != 0 and r0 % r1 == 0:
yield f(r0, r1), \
  '%s(%s,%s)'% (f.__name__, t0, t1)

def find_repr(target, nums):
for x,t in countdown(nums):
if x == target:
print x,t

print ctime()
find_repr(234, [100,9,7,6,3,1])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list depending of the indexes of another sorted list

2008-01-20 Thread babui
On 21 ene, 08:41, Santiago  Romero <[EMAIL PROTECTED]> wrote:
>  Hi ...
>
>  I have the following DNS MX records info:
>
> domain.com
> preference 10 host mx1.domain.com
> preference 30 host anotherhost.domain.com
> preference 20 host mx2.domain.com

>  And finally ... do you think there is a better python structure to
> store this data and sort it in a more easy way?

Why don't you use a list of tuples?

L = [ (10, "mx1.domain.com"), (30, "anotherhost.domain.com", (20,
"mx2.domain.com") ]

and L.sort() sorts the list !!!

Juan M. Gimeno
>  Thanks.

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


eucledian dist calculations

2008-01-20 Thread nodrogbrown
hi
i am using python to do some image data calculations..I use the
following numpy.ndarrays ,(i have given their shapes and ranks)

weights=ndarray :shape(100,30),ndim=2   will have vals like
2458121847.49 (of  type 'numpy.float64')
input_weight=ndarray :shape(30,),ndim=1 (similar to above but diff
vals)
distance =ndarray :shape(30,),ndim=1
mindistance==ndarray :shape(30,),ndim=1

now i am calculating the euclidian distance of 'input_weight' from
'weight'
since this is the cumulative diff i do this in this way


for image in range(100):
   temp=0.0
   for j in range(30):
distance[j]=abs(input_weight[j]-weights[image,j])

   if(image==0):
#at the start copy from distance to mindistance
mindistance=distance.copy()
   if (sum(mindistance) > sum(distance)):
imgindex=image # i use this  later to access a list
mindistance=distance.copy()

# now normalise the mindistance
array
if (max(mindistance) > 0.0):
mindistance=mindistance/(max(mindistance))

dist=sum(mindistance)



this gives me the correct results but i am worried if this is a bit
unpythonish?
(been a java programmer for a long time..) i wd like to know if there
is a better way

gordon

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


Sorting a list depending of the indexes of another sorted list

2008-01-20 Thread Santiago Romero

 Hi ...

 I have the following DNS MX records info:

domain.com
preference 10 host mx1.domain.com
preference 30 host anotherhost.domain.com
preference 20 host mx2.domain.com

 I'm storing this info in 2 lists:

preferences = [10, 30, 20]
hosts = [ "mx1.domain.com", "anotherhost.domain.com",
"mx2.domain.com"]

 (I was about to use a dict of  preferences : domain, but it's
possible to find 2 mx records with the same preference, so keys
wouldnt be unique).

 I'm trying to sort both lists so that they end like this:

preferences = [10, 20, 30]
hosts = [ "mx1.domain.com", "mx2.domain.com",
"anotherhost.domain.com" ]

 I want to sort hosts list depending on the numeric order of
"preferences".


 And finally ... do you think there is a better python structure to
store this data and sort it in a more easy way?

 Thanks.

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


How to use py2exe ...

2008-01-20 Thread Santiago Romero

 Hi...

 I'm a Linux user, and I would like some windows-friends to test a
game I'm writing with python+pygame without they needing to install
python, pygame, and so on.

 I've heard about py2exe and pygame2exe, but I'm not sure on how to
use them to create:

a.- standalone exe files with a single .py program.
Example: myprogram.py

or

b.- exe files containing all my source code + data directories (png
files, data files, and so).
Example: main.py, doc/README, src/*.py and data/*


 The problem is I'm not sure on how to use py2exe and pygame2exe to
build the executables...

 And finally, a question: if I want to provide source code
separately ... can I include .pyc files instead of .py files?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object scope

2008-01-20 Thread J. Peng
Dennis Lee Bieber 写道:
>   The scope of "name" is the entire function; lacking a "global name"
> statement, AND being on the left side of an assignment, it is a function
> local name.

Thank you. Does python have so-called 'block scope' object?
or if you can,please show me the doc for python's object scope.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Looping through the gmail dot trick

2008-01-20 Thread Martin Vilcans
On Jan 20, 2008 8:58 PM, Martin Marcher <[EMAIL PROTECTED]> wrote:
> are you saying that when i have 2 gmail addresses
>
> "[EMAIL PROTECTED]" and
> "[EMAIL PROTECTED]"
>
> they are actually treated the same? That is plain wrong and would break a
> lot of mail addresses as I have 2 that follow just this pattern and they
> are delivered correctly!
>
> Do you have any reference on that where one could read up why gmail would
> have such a behaviour?

Try the SMTP spec. IIRC there's a passage there that says that the
server should try to make sense of addresses that don't map directly
to a user name. Specifically, it says that firstname.lastname should
be mapped to the user with those first and last names.

-- 
[EMAIL PROTECTED]
http://www.librador.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object scope

2008-01-20 Thread Gabriel Genellina
En Mon, 21 Jan 2008 03:16:37 -0200, J. Peng <[EMAIL PROTECTED]>  
escribió:

> Dennis Lee Bieber 写道:
>>  The scope of "name" is the entire function; lacking a "global name"
>> statement, AND being on the left side of an assignment, it is a function
>> local name.
>
> Thank you. Does python have so-called 'block scope' object?
> or if you can,please show me the doc for python's object scope.

See http://docs.python.org/ref/naming.html

-- 
Gabriel Genellina

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