import

2007-07-05 Thread jolly
Hey guys,

I'm rather new to python and i'm have trouble(as usual)

I want to know if it is possible to change where 'import' looks
this will save me clogging up my python directory

Thanks

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Hendrik van Rooyen
 "John Machin"  wrote:

> 
> I don't know what you mean by "requires more than one
> character of lookahead" -- any non-Mickey-Mouse implementation of a
> csv reader will use a finite state machine with about half-a-dozen
> states, and data structures no more complicated than (1) completed
> rows received so far (2) completed fields in current row (3) bytes in
> current field. When a new input byte arrives, what to do can be
> determined based on only that byte and the current state; no look-
> ahead into the input stream is required, nor is any look-back into
> those data structures.
> 

True.

You can even do it more simply - by writing a GetField() that
scans for either the delimiter or end of line or end of file, and 
returns the "field" found, along with the delimiter that caused 
it to exit, and then writing a GetRecord() that repetitively calls
the GetField and assembles the row record until the delimiter 
returned is either the end of line or the end of file, remembering 
that the returned field may be empty, and handling the cases based 
on the delimiter returned when it is.

This also makes all the decisions based on the current character
read, no lookahead as far as I can see.

Also no state variables, no switch statements...

Is this the method that you would call "Mickey Mouse"?

Actually I lie about the no state variables - you have to keep track
of where you are in the file - but calling read(1) will do it for you,
so no worries, mate...

*wondering if someone will call him on the current row number
as state variable*

- Hendrik


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


Re: Htmllib help

2007-07-05 Thread axjacob
Thank you.

Thats right I don't need the output any where so I don't need to use the 
writer. I can remove it wowever will the formater work since it needs writer? 
Maybe I can use the Null writer?




 -- Original message --
From: "Gabriel Genellina" <[EMAIL PROTECTED]>
> En Thu, 05 Jul 2007 20:23:08 -0300, <[EMAIL PROTECTED]> escribió:
> 
> > I am using html and formater as shown below. They are used as part of a  
> > larger program.
> >
> > Even though I don't use any print statements, the htmllib seems to be  
> > throwing parts of the html page on to the standard out(my screen in this  
> > case). Is there a way to disable the output?
> >
> > import htmllib
> > w = formatter.DumbWriter()
> 
> Change the above line. From http://docs.python.org/lib/writer-impls.html:
> "class DumbWriter([file[, maxcol = 72]])
>   Simple writer class which writes output on the file object passed in as 
>  
> file or, if file is omitted, on standard output."
> 
> (From your code fragment it appears that you are not interested in any  
> output - in that case you don't need the writer at all. And maybe you can  
> use another parser, like HTMLParser.HTMLParser, so I'd ask why do you use  
> a writer in the first place?)
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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

Re: The best platform and editor for Python

2007-07-05 Thread Ben Finney
[EMAIL PROTECTED] (Alex Martelli) writes:

> Kay Schluehr <[EMAIL PROTECTED]> wrote:
> > half of the community is happy with Emacs and the other half wants
> > to program in a VS-like environment, neither consensus nor
> > progress has
>
> Calling all vi/vim users (and we'll heartily appreciate the support
> of TextMate fans, BBEdit ones, etc, etc) -- we're at risk being
> defined out of existence, since we're neither happy with Emacs nor
> wanting anything like Visual Studio, and yet Kay claims that people
> in either category make up the whole (one half plus the other half)
> and so that WE DON'T EXIST!!!  A ridiculous claim to be sure, but
> we'd better let Herr Schluehr know that in no uncertain terms...

Bah, it's clear. Vim users are in the *third* half -- the larger one.

Anyone not already in those three categories can presumably find a
decent half as well.

-- 
 \"Intellectual property is to the 21st century what the slave |
  `\   trade was to the 16th."  -- David Mertz |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Writing a read only attribute

2007-07-05 Thread Fabrizio Pollastri
Hello,
it is possible to force in some way a write to a read-only attribute of 
a python object?  In which case?
Thanks for any answer.

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


VB frontend to Python COM backend

2007-07-05 Thread nik
I have a VB6 application that I would like to attach to a python
communications application.

I have come across several discussions on using VB with a Python COM
back-end, but no starting point. I haven't had anymore luck with
google at finding out what this method is called and where to find
more information or examples on it. I would really appreciate it if
someone could point me in the right direction for using python objects
from VB.

Thank you,
Nik

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


Re: The best platform and editor for Python

2007-07-05 Thread Gregor Horvath
Kay Schluehr schrieb:

> The problem is simply that the Python community has failed in this
> respect. There are many platform dependent and ideology driven ways to
> do deal with code editing / debugging but not actually a recommend or
> "pythonic" way. Other than Smalltalk, Python has not created an own

Again, that's how Open Source or a Toolkit driven development (Unixy) 
works.
For every problem there are 5 solutions. One size does not fit all.

It's no fault that for example Linux Distributions do not have only one 
GUI but a lot of them. It's a great fortune.

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


Re: what is wrong with that r"\"

2007-07-05 Thread Tim Roberts
Matthieu TC <[EMAIL PROTECTED]> wrote:

>May I suggest giving the possibility to use any delimiter for a raw string?  
>just like in Vi or ruby.
>
>Vi:
> %s_a_b_g  is valid and so is  %s/a/b/g
>
>Ruby:
> %q{dj'\ks'a\'"}   or %q-dj'\ks'a\'"-
>
>So as long as your regex does not use all the valid characters, readability is 
>maintained.

But what about my program that wants to use r_a_b_ as an identifier?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interfacing python program to C++ program instance

2007-07-05 Thread Josiah Carlson
Jim Langston wrote:
> Windows. Situation: Using a Python program called OpenRPG.  I have a program 
> that displays form data (a character sheet) in C++.  I am able in the C++ 
> program to build a string and copy it into the clipboard, then paste it into 
> the input in the running Python program.

If I remember correctly, OpenRPG uses wxPython for it's GUI.  wxPython 
offers fairly easy access to the clipboard contents, so it could check 
the clipboard for the kind of data it wants.

> I would like to somehow automate this, that is, have the python instance 
> communicate with the C++ instance and vice versa.  I'm still trying to think 
> of a way to do this.  There seems to be a number of options, but I'm not 
> sure which one is best, or there is a better one.
> 
> 1. Write a new C++ program/library with extern C that Python could call. 
> This interface program would open up some shared memory that the C++ 
> application would also open up, and python and C++ could communicate that 
> way.  Python writing requests to the memory, C++ responding with responses.

mmap is the standard "shared memory communication" mechanism available 
on pretty much all platforms of note (Windows, Linux, OSX, BSD, Solaris, 
BeOS, etc.)


> 2. Have the C++ program interface directly into the python form, reading 
> directly from controls.  C++ could write to the input box with reponses.

If OpenRPG uses any custom controls (which are very easy to write with 
wxPython), this won't be easy.  Also, controlling an application that 
wasn't designed for such control can be a beast.


> 3. Have Python write a small file with the request to the HD.  Have the C++ 
> program intermittedly check for the presense of this file. If it exists, it 
> would open the file, read the request, write a response file, then delete 
> the file Python wrote.

This can work, but is unnecessary.  See mmap, socket, etc.


> 4. Find out if python can directly, somehow, open up shared memory and do 
> the same as 1 without the need for the extern C interface program.

import mmap


> 5. Something else I'm not thinking of but you know.

sockets.  In particular, XML-RPC for the call/return using structured 
data in XML format.  There exists XML-RPC server and client libraries in 
Python, and XML-RPC server and client libraries exist for just about 
every language worth discussing.  Alternatively, you can pass your 
queries/string directly via sockets (rather than the clipboard).


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


Re: How to close a program I execute with subprocess.Popen?

2007-07-05 Thread jitudon
On Jun 29, 6:36 pm, [EMAIL PROTECTED] wrote:
> I'm writing a program which has to execute a command, get its output
> and show it on a treeview.
> This command runs for a very long time.
> I want to end the execution of the command when the user closes my
> application.
>
> Right now I'm using an object my_child of type subprocess.Popen to
> execute the command, inside a thread with an infinite loop where we
> constantly ask for its output.
>
> To end the program when the user closes the application, I send a
> SIGTERM to the process with pid my_child.pid using os.kill. But I also
> have to send a SIGTERM to my_child.pid + 1 because my_child.pid is the
> pid of /bin/sh -c which is the one which calls the command, because
> when I try to run Popen with shell=False, it sends an exception and
> says the file or directory doesn't exist.
>
> Anyone knows of a better way to close the command than using a
> SIGTERM? I just can't help myself thinking this is an ugly dirty hack.

As nick pointed out use process group's .
I use the  "preexec_fn" keyword argument to Popen and "os.setsid()"
call's side effect
to make process groups and then os.killpg() to send the signal to
process groups.

child = Popen( cmd , preexec_fn = os.setsid )
os.killpg( child.pid,signal.SIGINT)

Regards
jitu




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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Dan Bishop
On Jul 5, 10:19 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > Besides, a string is an excellent epresentation for a zip code,
> > since arithmetic upon them is unthinkable.
>
> Absolutely!  Excel, unless you remedied that later with a column
> operation, would turn some East Coast zipcodes into 3- and 4-digit
> numbers (dropping the leading 0s), exactly because it's so obtuse as to
> try to "treat as numbers" entries that are all-digits.

What's even worse is having it treat credit card numbers as numbers.
Which wouldn't be so much of a problem if they were 15 digits.  But
they're 16 digits.

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


Re: The best platform and editor for Python

2007-07-05 Thread Kay Schluehr
On Jul 6, 12:13 am, Alex Popescu <[EMAIL PROTECTED]>
wrote:
> On Jul 5, 5:46 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Kay Schluehr wrote:
> > > On Jul 3, 8:12 pm, [EMAIL PROTECTED] (Cameron Laird) wrote:
>
> > > > Python is simply easier than C++; you might
> > > > well find that a debugger, for example, doesn't feel as essential
> > > > as it is for you with C++.
>
> > > That's what I love most about the Python community. Whenever there is
> > > just a non-standard, platform-dependent or crappy implementation of a
> > > feature you get told that you don't need it.
>
> > A fairly nice debugger is standard and built-in to the regular Python
> > distribution on all platforms.
>
> > But 95% of what a debugger is used for IME is getting a stack trace--
> > in Python (or Java or Ruby or most modern languages) you get that
> > automatically, and the debugger is nowhere near as useful as it is in
> > C or C++.
>
> I am a Python newbie, but unfortunately I don't agree with that. For
> me having a debugger helped understand very quickly the flow
> in the libraries for which otherwise I would have had to navigate
> through code (which once again is not always easy without a good IDE).

You don't have to be unfortune about it. As you see there is no
consensus. I don't even know how Java developers would respond to the
assertion that the debugger is halfway irrelevant because they can
read the stacktraces ( A real C programmer and real man can read core
dumps. So what? ) Java is often considered as Blub but it doesn't at
least deny progress in tool development of the last 20 years.

> But this is just a newbie opinion :-),

I don't think so. BTW if you want to take a glimpse on the future of
"dynamic" languages you might also checkout this paper:

http://lamp.epfl.ch/~mcdirmid/mcdirmid07live.pdf

Kay


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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Nis Jørgensen
Wildemar Wildenburger skrev:
> Nis Jørgensen wrote:
>> Neil Cerutti skrev:
>>
>>  
>>> Mostly you can use the default 'excel' dialect and be quite
>>> happy, since Excel is the main reason anybody still cares about
>>> this unecessarily hard to parse (it requires more than one
>>> character of lookahead for no reason except bad design) data
>>> format.
>>> 
>>
>> I knew there had to be a reason why everyone is using xml these days ...
>>
>> Nis
>>   
> Are you serious? 

No.

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


urllib to cache 301 redirections?

2007-07-05 Thread O.R.Senthil Kumaran
Hi,
There is an Open Tracker item against urllib2 library python.org/sf/735515
which states that.
urllib / urllib2 should cache the results of 301 (permanent) redirections.
This shouldn't break anything, since it's just an internal optimisation
from one point of view -- but it's also what the RFC (2616, section 10.3.2, 
first para) says
SHOULD happen. 

I am trying to understand, what does it mean.
Should the original url be avaiable to the user upon request as urllib
automatically calls the redirect_request and provides the redirected url only?

I am not completely getting what "cache - redirection" implies and what should
be done with the urllib2 module. Any pointers?

Thanks,
-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best platform and editor for Python

2007-07-05 Thread Alex Martelli
Kay Schluehr <[EMAIL PROTECTED]> wrote:
   ...
> half of the community is happy with Emacs and the other half wants to
> program in a VS-like environment, neither consensus nor progress has

Calling all vi/vim users (and we'll heartily appreciate the support of
TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out
of existence, since we're neither happy with Emacs nor wanting anything
like Visual Studio, and yet Kay claims that people in either category
make up the whole (one half plus the other half) and so that WE DON'T
EXIST!!!  A ridiculous claim to be sure, but we'd better let Herr
Schluehr know that in no uncertain terms...


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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Alex Martelli
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> Besides, a string is an excellent epresentation for a zip code,
> since arithmetic upon them is unthinkable.

Absolutely!  Excel, unless you remedied that later with a column
operation, would turn some East Coast zipcodes into 3- and 4-digit
numbers (dropping the leading 0s), exactly because it's so obtuse as to
try to "treat as numbers" entries that are all-digits.

Funny enough, that very issue took at least 5 minutes of lecture time at
a recent lecture in a course on "statistical approaches to data mining"
that I'm following (hopefully it will turn to slightly more advanced
issues soon:-): Excel (!) and R are the two "recommended" programs for
the course, and substantial parts of the lecture times so far have been
spent illustrating various foibles of each.  Still, another guy who's
taking the class had a funny and relevant war story: at one point a
company he was working for did a mass mailing (paper mail)... and big
bag of the mails was returned as undeliverable by a pretty peeved US
Post Office... the "mail merge" they had done apparently involved Excel
(or some other spreadsheet program) at some point, and many East Coast
zipcodes had indeed been truncated (which messes with USPO's automatic
system and thus is NOT tolerated, at least in bulk mail)...!-)


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


Re: MethodType/FunctionType and decorators

2007-07-05 Thread Alex Martelli
Alex Popescu <[EMAIL PROTECTED]> wrote:
   ...
> frameworks (TestNG is not a unit testing framework,
> but a full flavored testing framework that fits perfectly functional
> testing, integration testing, and with some of the
> very advanced features even performance and load testing).

Nice!  Does it have any integration/interoperability with FIT/Fitnesse,
btw?  For certain kinds of "functional testing" (where the specs are to
be mostly written by people with no programming skills but strong
business, accounting, &c, i.e., people _used_ to thinking in terms of
tables and spreadsheets) I find that approach very interesting...


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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-05 Thread George Sakkis
On Jul 5, 3:24 pm, Donn Cave <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Paul Boddie <[EMAIL PROTECTED]> wrote:
>
> > However, it's interesting to consider the work that sometimes needs to
> > go in to specify data structures in some languages - thinking of ML
> > and friends, as opposed to Java and friends. The campaign for optional
> > static typing in Python rapidly became bogged down in this matter,
> > fearing that any resulting specification for type information might
> > not be the right combination of flexible and powerful to fit in with
> > the rest of the language, and that's how we really ended up with PEP
> > 3107: make the semantics vague and pretend it has nothing to do with
> > types, thus avoiding the issue completely.
>
> I missed the campaign for optional static typing, must have been
> waged in the developer list.  Unless it was not much more than
> some on-line musings from GvR a year or two ago.  I don't see
> how it could ever get anywhere without offending a lot of the
> Python crowd, however well designed, so I can see why someone
> might try to sneak it past by pretending it has nothing to do
> with types.  But he didn't -- look at the examples, I think he
> rather overstates the potential for static typing applications.

The key point is that this is left to 3rd party libraries; the
language won't know anything more about static typing than it does
now. FWIW, there is already a typechecking module [1] providing a
syntax as friendly as it gets without function annotations. If the
number of its downloads from the Cheeshop is any indication of static
typing's popularity among Pythonistas, I doubt that PEP 3107 will give
significant momentum to any non-standard module anytime soon.

George


[1] http://oakwinter.com/code/typecheck/

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


Interfacing python program to C++ program instance

2007-07-05 Thread Jim Langston
Windows. Situation: Using a Python program called OpenRPG.  I have a program 
that displays form data (a character sheet) in C++.  I am able in the C++ 
program to build a string and copy it into the clipboard, then paste it into 
the input in the running Python program.

I would like to somehow automate this, that is, have the python instance 
communicate with the C++ instance and vice versa.  I'm still trying to think 
of a way to do this.  There seems to be a number of options, but I'm not 
sure which one is best, or there is a better one.

1. Write a new C++ program/library with extern C that Python could call. 
This interface program would open up some shared memory that the C++ 
application would also open up, and python and C++ could communicate that 
way.  Python writing requests to the memory, C++ responding with responses.

2. Have the C++ program interface directly into the python form, reading 
directly from controls.  C++ could write to the input box with reponses.

3. Have Python write a small file with the request to the HD.  Have the C++ 
program intermittedly check for the presense of this file. If it exists, it 
would open the file, read the request, write a response file, then delete 
the file Python wrote.

4. Find out if python can directly, somehow, open up shared memory and do 
the same as 1 without the need for the extern C interface program.

5. Something else I'm not thinking of but you know.

Thanks. 


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


Question about Making a Diskless Python Enviroment

2007-07-05 Thread [EMAIL PROTECTED]
Hi everyone
   We are making a disk less workstation environment which support
python.We use PXE DHCP TFTP to boot up disk less system.There are
three choices as i know to set up a python environment for diskless
system.

First Solution, Use a initrd image with everything inside as the root
file system.Diskless computer boots up with a kernel and this rootfs
image.If everything goes fine.We could use python in the ram disk.In
my situation,Target computers have 2G memory and 100M network,so the
we don't need to worry about the size of initrd image.MY QUESTIONS are
what files and libraries do i need to put into initrd image.Is there
any How-to file to help me install python into a initrd image or any
available initrd image with  python installed .

Second Solution.Use a small initrd to boot up the system and use NFS
to mount those directories on Diskless server.I guess we could use /
etc/fstab file to make it.Though we boot up the system form
network ,we need to mount its local hard disk to directory tree.MY
QUESTION ARE How to mount local devices in a diskless system?Is that
done by kernel automatically or i have to configure it in fstab?

Third Solution.Use NFS ROOT file system to boot up .In this
solution.We don't need initrd any more.What we are going to do is
recompile the kernel and build those important modules inside.It is
weird that my kernel couldn't get ip form dhcp server(it can use a
static ip form kernel command line).I notice that pxe could get ip
form dhcp so it must be something wrong with the Kernel.We stop here.

The three solution above are all i could think about. Any idea about
my questions is welcomed
 
Thanks
 
Best Regard

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


Re: Htmllib help

2007-07-05 Thread Gabriel Genellina
En Thu, 05 Jul 2007 20:23:08 -0300, <[EMAIL PROTECTED]> escribió:

> I am using html and formater as shown below. They are used as part of a  
> larger program.
>
> Even though I don't use any print statements, the htmllib seems to be  
> throwing parts of the html page on to the standard out(my screen in this  
> case). Is there a way to disable the output?
>
> import htmllib
> w = formatter.DumbWriter()

Change the above line. From http://docs.python.org/lib/writer-impls.html:
"class DumbWriter([file[, maxcol = 72]])
Simple writer class which writes output on the file object passed in as 
 
file or, if file is omitted, on standard output."

(From your code fragment it appears that you are not interested in any  
output - in that case you don't need the writer at all. And maybe you can  
use another parser, like HTMLParser.HTMLParser, so I'd ask why do you use  
a writer in the first place?)

-- 
Gabriel Genellina

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Alex Popescu wrote:
> Probably the simplest solution would be to create a new exception and
> wrapping the old one and the additional info. Unfortunately, this 
> may have a huge impact on 3rd party code that was catching the 
> original exception. So, I think you should create an utility 
> factory-like function that is either creating a new exception 
> instance as the one caught and with the additional information,

Right, I have gone with that (see the example with the PoliteException 
class somewhere below).

> or an utility that knows how to modify the caught exception according
> to its type.

I guess you mean something like this (simplified):

except Exception, e:
 if getattr(e, 'reason'):
 e.reason += "sorry"
 else:
 e.message += "sorry"

The problem is that these attribute names are not standardized and can 
change between Python versions. Not even "args" is sure, and if a class 
has "message" it does not mean that it is displayed. Therefore I think 
the first approach is better.

> In the first case you will need somehow to tell to the new instance
> exception the real stack trace, because by simply raising
> a new one the original stack trace may get lost.

Yes, but thats a different problem that is easy to solve.

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


Re: Proposal: s1.intersects(s2)

2007-07-05 Thread David Abrahams

on Thu Jul 05 2007, Christoph Zwerschke  wrote:

> Steven D'Aprano wrote:
>> I'm not a professional set theorist, but in 15-odd years of studying and
>> teaching maths I've never come across mathematicians using intersect as a
>> verb except as informal short-hand. I often say "North Street and South
>> Street don't intersect", but "the intersection of sets A and B is empty".
>
> I think mathematicians use more often the inverse predicate, namely 
> "disjoint", which is well defined as having an empty intersection.

Doesn't read so well as a method, though.  You end up with
"a.is_disjoint_with(b)."

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com

The Astoria Seminar ==> http://www.astoriaseminar.com

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-05 Thread Lenard Lindstrom
Falcolas wrote:
>> f = some_file() #maybe it's the file store for a database implementation
>> f.write('a bunch of stuff')
>> del f
>> #insert code that assumes f is closed.
>>
>> This is the sort of code that I warn against writing.
>>
>> f = some_file()
>> with f:
>>   f.write("a bunch of stuff")
>> #insert code that assumes f is closed, but correctly this time
>>
>> is better.
> 
> This has raised a few questions in my mind. So, here's my newbie
> question based off this.
> 
> Is this:
> 
> f = open(xyz)
> f.write("wheee")
> f.close()
> # Assume file is closed properly.
> 

This will not immediately close f if f.write raises an exception since 
the program stack is kept alive as a traceback.

> as "safe" as your code:
> 
> f = some_file()
> with f:
>   f.write("a bunch of stuff")
> #insert code that assumes f is closed, but correctly this time
> 

The with statement is designed to be safer. It contains an implicit 
try/finally that lets the file close itself in case of an exception.

--
Lenard Lindstrom
<[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (EMBEDDING) Can't get python error message

2007-07-05 Thread Gabriel Genellina
En Thu, 05 Jul 2007 08:47:57 -0300, <[EMAIL PROTECTED]> escribió:

> I run this string to produce a error "x+1"
>
> PyRun_SimpleStringFlags() return -1, so that i know this is a script
> with error inside...
>
> but now - how can i get error message?

Simply, you can't. From http://docs.python.org/api/veryhigh.html: "If  
there was an error, there is no way to get the exception information."
Use another function instead, like PyRun_StringFlags()

-- 
Gabriel Genellina

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


Debugger

2007-07-05 Thread James Matthews

Can anyone please tell me of a good debugger that can debug threads. My
issue is that i have a program that is crashing only under certain threads
but others are fine. And when i do it without threads it runs fine!

--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: None returned?

2007-07-05 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> I can't figure out -what- is going wrong here.  When the code reaches
> the 'return' line, there is data to be returned, but when it exits out
> to the calling function, 'None' is returned!
> 
> import mx.DateTime
> 
> def get_weeks(weeks, year, dates, date_list={}):
> if dates.has_key(year):
> date_list[year] = dates[year].keys()[-weeks:]
> if len(dates[year].keys()) >= weeks:
> return date_list
> else:
> weeks = weeks - len(dates[year].keys())
> get_weeks(weeks, str(int(year) -1), dates, date_list)
> 
So if the else branch is taken here you end up dropping of the end of 
the function's code, which will return None.

> def get_report_dates(weeks, dates):
> today = mx.DateTime.now()
> this_week = today.iso_week[1]
> rpt_dates = get_weeks(weeks, str(today.year), dates)
> print rpt_dates
> 
> def main():
> 
> dates = {'2006': {'50': [50, 'This is the 50th week'],
> '51': [51, 'This is the 51st week'],
> '52': [52, 'This is the 52nd week']},
>  '2007': {'25': [1, 'This is the 1st week'],
> '26': [2, 'This is the 2nd week'],
> '27': [3, 'This is the 3rd week'],
> '28': [4, 'This is the 4th week'],
> '29': [5, 'This is the 5th week']}}
> 
> get_report_dates(6, dates)
> 

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: None returned?

2007-07-05 Thread Kelvie Wong
On 7/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I can't figure out -what- is going wrong here.  When the code reaches
> the 'return' line, there is data to be returned, but when it exits out
> to the calling function, 'None' is returned!
>
> import mx.DateTime
>
> def get_weeks(weeks, year, dates, date_list={}):
> if dates.has_key(year):
> date_list[year] = dates[year].keys()[-weeks:]
> if len(dates[year].keys()) >= weeks:
> return date_list
> else:
> weeks = weeks - len(dates[year].keys())

Right here.

> get_weeks(weeks, str(int(year) -1), dates, date_list)

You have to change that line to:
return get_weeks(weeks, str(int(year) -1), dates, date_list)

Otherwise, if len(dates[year.keys()) < weeks, it doesn't return anything.

>
> def get_report_dates(weeks, dates):
> today = mx.DateTime.now()
> this_week = today.iso_week[1]
> rpt_dates = get_weeks(weeks, str(today.year), dates)
> print rpt_dates
>
> def main():
>
> dates = {'2006': {'50': [50, 'This is the 50th week'],
> '51': [51, 'This is the 51st week'],
> '52': [52, 'This is the 52nd week']},
>  '2007': {'25': [1, 'This is the 1st week'],
> '26': [2, 'This is the 2nd week'],
> '27': [3, 'This is the 3rd week'],
> '28': [4, 'This is the 4th week'],
> '29': [5, 'This is the 5th week']}}
>
> get_report_dates(6, dates)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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


A different debugger

2007-07-05 Thread M Friedeman
Try a different type of debugger.

This one does not need you to set breakpoints.
Run the program once and after that everything is available to you.

You then just scroll to any line you're interested in and click the
variable.

It requires Firefox and Python 2.5.

http://codeinvestigator.googlepages.com/main


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


Htmllib help

2007-07-05 Thread axjacob

I am using html and formater as shown below. They are used as part of a larger 
program.

Even though I don't use any print statements, the htmllib seems to be throwing 
parts of the html page on to the standard out(my screen in this case). Is there 
a way to disable the output?

import htmllib
w = formatter.DumbWriter() 
format = formatter.AbstractFormatter(w)
p = htmllib.HTMLParser(format)
p.feed(inhtml)
p.close()
for x in p.anchorlist:
   "Use x in regex"


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


None returned?

2007-07-05 Thread robinsiebler
I can't figure out -what- is going wrong here.  When the code reaches
the 'return' line, there is data to be returned, but when it exits out
to the calling function, 'None' is returned!

import mx.DateTime

def get_weeks(weeks, year, dates, date_list={}):
if dates.has_key(year):
date_list[year] = dates[year].keys()[-weeks:]
if len(dates[year].keys()) >= weeks:
return date_list
else:
weeks = weeks - len(dates[year].keys())
get_weeks(weeks, str(int(year) -1), dates, date_list)

def get_report_dates(weeks, dates):
today = mx.DateTime.now()
this_week = today.iso_week[1]
rpt_dates = get_weeks(weeks, str(today.year), dates)
print rpt_dates

def main():

dates = {'2006': {'50': [50, 'This is the 50th week'],
'51': [51, 'This is the 51st week'],
'52': [52, 'This is the 52nd week']},
 '2007': {'25': [1, 'This is the 1st week'],
'26': [2, 'This is the 2nd week'],
'27': [3, 'This is the 3rd week'],
'28': [4, 'This is the 4th week'],
'29': [5, 'This is the 5th week']}}

get_report_dates(6, dates)

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


Re: The best platform and editor for Python

2007-07-05 Thread Steven D'Aprano
On Thu, 05 Jul 2007 14:13:29 -0700, Kay Schluehr wrote:

> On Jul 5, 7:18 pm, kimiraikkonen <[EMAIL PROTECTED]> wrote:
>> I just wanted a simple answer to my simple question, however topic has
>> messed up. Think questioner as a beginner and use more understandable
>> terms to help :)
>>
>> Thanks.
> 
> The problem is simply that the Python community has failed in this
> respect. There are many platform dependent and ideology driven ways to
> do deal with code editing / debugging but not actually a recommend or
> "pythonic" way. 

What makes you think this is a *problem*?

Why is it a failure that Python is perfectly usable with a whole range
of editors, debuggers and development styles?

> Other than Smalltalk, Python has not created an own
> style / identity regarding decent development environments and since
> half of the community is happy with Emacs and the other half wants to
> program in a VS-like environment, neither consensus nor progress has
> to be expected.

I don't accept that consensus on editing tools is a good thing, let
alone a necessity. Nor that progress is only possible when everybody
agrees. To quote from one of my favourite fictional characters, Lord
Vetinari:

"Pulling together is the aim of despotism and tyranny. Free men pull
in all kinds of directions." He smiled, "It's the only way to make
progress. That and, of course, moving with the times."
-Terry Pratchett, "The Truth"


-- 
Steven.

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


Re: deliberate versus os socket timeout

2007-07-05 Thread John J. Lee
Robin Becker <[EMAIL PROTECTED]> writes:

> While messing about with some deliberate socket timeout code I got an
> unexpected timeout after 20 seconds when my code was doing
> socket.setdefaulttimeout(120).
>
> Closer inspection revealed that this error in fact seemed to come from
> the os (in this case windows xp).
>
> By inspection of test cases the error.reason from the deliberate
> socket timeout looks like
> 'timed out'
> whereas the windows caused timeout error.reason looks like
> '(10060 operation timed out)'
> 
> it would be nice to know if that is in fact true and whether there is
> any way to do the attribution of errors more sensibly.

What do you mean "is in fact true"?  Is what true?  That the reason is
always formatted in those ways when those particular errors occur?
Not sure there's any reason to rely on that: I'd expect .reason to be
an exception object, so (reading the docs for module socket)
e.reason.args[0] should be the error code if one is available, in this
case errno.ETIMEDOUT (i.e. WSAETIMEDOUT, which means the timeout
occurred before a connection was established).  Sometimes
e.reason.args will be length-1, and e.reason.args[0] will be a string,
again according to the docs for module socket.


> Both of these seem to cause urllib2.URLError and presumably appear
> somewhere in the socket code.
>
> It might be nice if the deliberate timeout could be something like
> timed out deliberately after xxx seconds'.

By "deliberate timeout", you mean the one you asked for by calling
socket.setdefaulttimeout().

In that case, I think e.reason will be a socket.timeout instance (as
opposed to socket.error in the WSAETIMEOUT case).


> More importantly is there anything I can do to avoid these wrong os
> inspired timeouts? I'm just using urllib2 to read from a remote site
[...]

Please define "wrong" ;-)

Googling suggests Windows doesn't let you configure its connect
timeout, except through a registry setting:

http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-09/msg00918.html


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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread John Machin
On Jul 6, 5:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>
> Mostly you can use the default 'excel' dialect and be quite
> happy, since Excel is the main reason anybody still cares about
> this unecessarily hard to parse (it requires more than one
> character of lookahead for no reason except bad design) data
> format.

One cares about this format because people create data files of
millions of rows (far exceeding the capacity of Excel (pre-2007)) in
many imaginative xSV dialects, some of which are not handled by the
Python csv module.

I don't know what you mean by "requires more than one
character of lookahead" -- any non-Mickey-Mouse implementation of a
csv reader will use a finite state machine with about half-a-dozen
states, and data structures no more complicated than (1) completed
rows received so far (2) completed fields in current row (3) bytes in
current field. When a new input byte arrives, what to do can be
determined based on only that byte and the current state; no look-
ahead into the input stream is required, nor is any look-back into
those data structures.

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


Re: Embedded For Loop With No Data

2007-07-05 Thread Steven D'Aprano
On Thu, 05 Jul 2007 22:03:59 +, rshepard wrote:

>   Haven't found an answer to my question in the books and other docs I have
> available, so I am asking here.
> 
>   I have three lists of data retrieved from database tables. I want to cycle
> through all three lists using nested FOR loops. What is the behavior if
> there are no data in the list used in the middle loop?

Why don't you try it and see for yourself?


types = ["Type A", "Type B", "Type C"]
subtypes = []
details = [1, 2, 3]


>   Example:
> 
>   for a in types:
>   for b in subtypes:
>   for c in details:
>   do some processing
> 
>   Not every item in the 'types' list will have an associated 'subtype'. Does
> the index ignore that loop and drop to the one nested beneath it?


Be sure to write back and let us know what you discover.


-- 
Steven.

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


Re: The best platform and editor for Python

2007-07-05 Thread Jason
On Jul 1, 1:10 pm, kimiraikkonen <[EMAIL PROTECTED]> wrote:
> Hi,
> For experienced with Pyhton users, which developing software and
> enviroment would you suggest for Pyhton programming? Compiler+Editor
> +Debugger.

That would depend on what platform(s) you would be developing on, what
development environments you were used to, and so forth.  I personally
enjoy working in Eclipse with the PyDev plugin.  Other people love
Emacs.  I know folk who you'll only pry their vim editors from their
cold, dead fingers.

For people dipping their toes into the Python pool, I recommend using
Idle.  It comes with Python itself, and has a built-in debugger (see
the Debug menu), syntax highlighting, and other goodies.  It's
certainly enough to write your programs in.

Quite frankly, you can use Windows Notepad to write your Python
programs.  Python itself is just a language.  There is no single
environment that Python ties to itself tightly.  The basic debugger,
PDB, is built in as a Python module, so you can use Python to debug
itself.  Most of the IDE's that provide debuggers are merely placing a
nice wrapper over the python debugger.

To develop very short programs, I often start Python on my command
line and fiddle away.

> Also what are your suggestions for beginners of Pyhton programming?

Don't worry about making GUI programs at first.  GUIs are present in
every operating system, but they are an additional level of
complexity.  Get the language down, first, then head into the world of
graphical user interfaces.

Start programming.  See "Dive Into Python"[1].  Check out the
Beginner's section of the Python Wiki[2].  The hardest part about
learning to programming is learning to structure your thoughts into a
coherent series of logical units.  The rest is just code, and code is
easy.  It's the damn thinking that's so hard.

Get familiar with the Python documentation.  If you are under Windows,
the Python docs are installed with Python in Microsoft's Compiled Help
format, so you can browse them via the contents, look things up in the
index, and search via the search tab.  Remember that the built-in
stuff, like lists and dictionaries, are documented in the Python
Library Reference [3], while most of the modules are documented in the
Global Modules [4] document.  It's huge, but if you want to know what
Python has, it's almost always in there.

If you have a question, look for the solution by Googling this
newsgroup or the web in general.  If you still can't find a solution,
ask around in here.  Give plenty of detail, such the exact error
messages if one occurred, and the minimum amount of working code that
causes or demonstrates the problem.

You may get twenty different answers sometimes (like for your question
here), but that's twenty answers or perspectives that you may not have
known before you asked.

  --Jason

[1] http://www.diveintopython.org/
[2] http://wiki.python.org/moin/BeginnersGuide
[3] http://docs.python.org/lib/lib.html
[4] http://docs.python.org/modindex.html

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Sorry for the soliloquy, but what I am really using is the following so 
that the re-raised excpetion has the same type:

def PoliteException(e):
 class PoliteException(e.__class__):
 def __init__(self, e):
 self._e = e
 def __getattr__(self, name):
 return getattr(self._e, name)
 def __str__(self):
 if isinstance(self._e, PoliteException):
 return str(self._e)
 else:
 return '\n%s: %s, I am sorry!' % (
 self._e.__class__.__name__, str(self._e))
 return PoliteException(e)

try:
 unicode('\xe4')
except Exception, e:
 raise PoliteException(e)

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


Re: MethodType/FunctionType and decorators

2007-07-05 Thread Alex Popescu
On Jul 5, 5:01 pm, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> On Jul 5, 3:17 pm, Alex Popescu <[EMAIL PROTECTED]>
> wrote:
>
> > The true story is that
> > while working on Groovy (I am a committer on this dynlang meant to run
> > on the Java VM:http://groovy.codehaus.org) and reading some Python
> > materials, my interest grew exponentially. And now I have decided to
> > see how other succesfull java project I have co-created 
> > (TestNG:http://testng.org) would look like in Python (this giving me the
> > opportunity to explore Python in more depth).
>
> If you are interested in testing, you should give a look at 1)
> doctest; 2) py.test
> (Python unittest framework should be old hat to you and not worth
> looking at).
>
>  Michele Simionato


Thanks for the pointers Michele. I have heard about those and their
are on my todo list. However, the features of TestNG
are very advanced and I don't think they are available in other
frameworks (TestNG is not a unit testing framework,
but a full flavored testing framework that fits perfectly functional
testing, integration testing, and with some of the
very advanced features even performance and load testing).
But I will make sure I am taking a look at the ones you pointed me to
(and I think I have a longer list available around).

bests,

./alex
--
.w( the_mindstorm )p.


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


Re: The best platform and editor for Python

2007-07-05 Thread Alex Popescu
On Jul 5, 5:46 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Kay Schluehr wrote:
> > On Jul 3, 8:12 pm, [EMAIL PROTECTED] (Cameron Laird) wrote:
>
> > > Python is simply easier than C++; you might
> > > well find that a debugger, for example, doesn't feel as essential
> > > as it is for you with C++.
>
> > That's what I love most about the Python community. Whenever there is
> > just a non-standard, platform-dependent or crappy implementation of a
> > feature you get told that you don't need it.
>
> A fairly nice debugger is standard and built-in to the regular Python
> distribution on all platforms.
>
> But 95% of what a debugger is used for IME is getting a stack trace--
> in Python (or Java or Ruby or most modern languages) you get that
> automatically, and the debugger is nowhere near as useful as it is in
> C or C++.

I am a Python newbie, but unfortunately I don't agree with that. For
me having a debugger helped understand very quickly the flow
in the libraries for which otherwise I would have had to navigate
through code (which once again is not always easy without a good IDE).

But this is just a newbie opinion :-),

./alex
--
.w( the_mindstorm )p.


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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Alex Popescu
On Jul 6, 12:21 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Kay Schluehr wrote:
> > If you are sure that the exception isn't caught on another level just
> > use the following showtraceback() function, manipulate it's output
> > slightly and terminate your program with sys.exit()
>
> That's what I want to avoid. In my case the error is displayed and
> evaluated in a completly different piece of software.
>
> -- Chris

Probably the simplest solution would be to create a new exception and
wrapping the old one and the additional info. Unfortunately,
this may have a huge impact on 3rd party code that was catching the
original exception.

So, I think you should create an utility factory-like function that is
either creating a new exception instance as the one caught
and with the additional information, or an utility that knows how to
modify the caught exception according to its type.
In the first case you will need somehow to tell to the new instance
exception the real stack trace, because by simply raising
a new one the original stack trace may get lost.

bests,

./alex
--
.w( the_mindstorm )p.

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


Embedded For Loop With No Data

2007-07-05 Thread rshepard
  Haven't found an answer to my question in the books and other docs I have
available, so I am asking here.

  I have three lists of data retrieved from database tables. I want to cycle
through all three lists using nested FOR loops. What is the behavior if
there are no data in the list used in the middle loop?

  Example:

  for a in types:
  for b in subtypes:
  for c in details:
do some processing

  Not every item in the 'types' list will have an associated 'subtype'. Does
the index ignore that loop and drop to the one nested beneath it?

Rich

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Wildemar Wildenburger
Nis Jørgensen wrote:
> Neil Cerutti skrev:
>
>   
>> Mostly you can use the default 'excel' dialect and be quite
>> happy, since Excel is the main reason anybody still cares about
>> this unecessarily hard to parse (it requires more than one
>> character of lookahead for no reason except bad design) data
>> format.
>> 
>
> I knew there had to be a reason why everyone is using xml these days ...
>
> Nis
>   
Are you serious? You want to cram tabular data in some tree-oriented 
data format? Now THAT is evangelism. Why is it a bad desing choice to 
seperate values by a specific delimiter, thus emulating a tabular 
arrangement? I really don't get it. Thats the natural format for tabular 
data. Period.

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


Re: list.append not working?

2007-07-05 Thread Wildemar Wildenburger
Abhishek Jain wrote:
> with every iteration your previous values are overwritten ('md' is a 
> dictionary) so thats why your are observing this ouput..
>
> check  if the following patch solves your problem
>
> for entity in temp:
> md['module']= entity.addr.get('module')
> md['id']=entity.addr.get('id')
> md['type']=entity.addr.get('type')
> #print md
> mbusentities.append(md)
> md = {}
> #print mbusentities
>
>
> Regards
> Abhi
This will work, but may I suggest putting the md = {} line at the 
*beginning* of the loop?
I find seeing it at the end HIGHLY confusing. Declaring it in the 
beginning makes sense, because you declare/initialize, then use it. But 
using and *then* initializing it for the next iteration is kind of 
quirky, because it breaks the logical encapsulation I would like to see 
in *one* loop iteration.

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


Re: need help with converting c function to python function

2007-07-05 Thread John Machin
On Jul 6, 3:32 am, nephish <[EMAIL PROTECTED]> wrote:
> hello all,
>
> i have a c function from some modbus documentation that i need to
> translate into python.
>
> it looks like this:
>
> unsigned short CRC16(puchMsg, usDataLen)
> unsigned char *puchMsg ;
> unsigned short usDataLen ;
> {
>unsigned char uchCRCHi = 0xFF ;
>unsigned char uchCRCLo = 0xFF ;
>unsigned uIndex ;
>while (usDataLen--)
>{
>uIndex = uchCRCHi ^ *puchMsgg++ ;
>uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ;
>uchCRCLo = auchCRCLo[uIndex] ;
>}
>return (uchCRCHi << 8 | uchCRCLo) ;
>
> }
>
> some of it i can make out, but i can't seem to figgure out
> this part ' auchCRCHi[uIndex};
> it looks like a typo, because there is a closing } that does not match
> the opening [.

Yes, that's one problem.
The other problems are:

(1) you haven't noticed that auchCRClo is *NOT* the same as uchCRClo
(ditto "hi").

(2) the C code is missing global declarations, something like this:

unsigned char auchCRCLo[256] = { yadda yadda yadda}; /* ditto "hi" */

These two tables of 8-bit constants correspond to the single "table"
of 16-bit constants in the reference that Anton gave you.

Aside: the code looks like it was originally Z80 assembly language
subsequently transliterated into BDS C (of blessed memory).


(3) you have misread/mistranslated auchCRCLo[uIndex] blindly and
unconcernedly as uchCRCLo ^ uIndex !!! (ditto "hi")

>
> here is what i have so far, but is not giving me the right values
>
>  def crc16(data):
>  crc_hi = 0xff
>  crc_lo = 0xff
>  for x in data:
>  crc_index = crc_hi ^ x
>  crc_hi = crc_lo ^ (crc_hi | crc_index)
>  crc_lo = crc_lo | crc_index
>  return (crc_hi << 8 | crc_lo)
>
> whaddya think?

I don't think you really want to know :-)


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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Seems that no simple solution exists,
so for now, I will be using something like this:

class PoliteException(Exception):
 def __init__(self, e):
 self._e = e
 def __getattr__(self, name):
 return getattr(self._e, name)
 def __str__(self):
 if isinstance(self._e, PoliteException):
 return str(self._e)
 else:
 return '\n%s: %s, I am sorry!' % (
 self._e.__class__.__name__, str(self._e))

try:
 unicode('\xe4')
except Exception, e:
 raise PoliteException(e)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.append not working?

2007-07-05 Thread Wildemar Wildenburger
7stud wrote:
> Hardy wrote:
>   
>> I experience a problem with append(). This is a part of my code:
>>
>> for entity in temp:
>> md['module']= entity.addr.get('module')
>> md['id']=entity.addr.get('id')
>> md['type']=entity.addr.get('type')
>> #print md
>> mbusentities.append(md)
>> #print mbusentities
>>
>> I want something like: [{'module': 'home', 'id': 123, 'type': 'core'},
>> {'module': 'work', 'id': 456, 'type': 'core'}]
>> md is always correct, BUT:mbusentities is wrong. Length of
>> mbusentities is same of temp, so it appended everything. BUT:
>> mbusentities only shows the values of the last append: [{'module':
>> 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456,
>> 'type': 'core'}]
>>
>> What's wrong?
>> 
>
> Inside your loop, you assign md["module"], md["id"], and md["type"]
> the same values over and over again.
>
>   
I may seem like a prick, but that is not the correct answer (infidel and 
Abhishek gave the correct explanation). I just thought I'd point this 
out to avoid confusion.

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


Re: Extracting arbitrary amounts of data from a dictionary.

2007-07-05 Thread Jyotirmoy Bhattacharya
On Jul 6, 2:21 am, Jyotirmoy Bhattacharya <[EMAIL PROTECTED]>
wrote:
> On Jul 6, 12:31 am, [EMAIL PROTECTED] wrote:
>
>
>
> > I had nothing better to do, so I thought I would make a database that
> > contained the songs played on the internet radio station I listen to
> > (hardradio.com) so I could see how many differents songs/artists they
> > played.
> > So I end up with a the number of times any given song by a given
> > artist is played in a day.  Want I want to do is to be able to print
> > out a report for X number of weeks and I am trying to determine the
> > best way to interate through the 'week' key of the dictionary.
>
> > For example, this is week 27, the dictonary has 6 'week' keys and I
> > want the data from the last 3 weeks.  Is this the best way to iterate
> > through the dictionary?
>
> >for date in dates[year][week].keys()[-3]:
>
> > Or is there a better way with all the new features that have been
> > added to Python?
>
> Here is an implementation using as many 'new' features of Python as I
> could think of.http://phpfi.com/247634

A bit shortened and improved:
http://phpfi.com/247642

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


Re: The best platform and editor for Python

2007-07-05 Thread Kay Schluehr
On Jul 5, 7:18 pm, kimiraikkonen <[EMAIL PROTECTED]> wrote:
> I just wanted a simple answer to my simple question, however topic has
> messed up. Think questioner as a beginner and use more understandable
> terms to help :)
>
> Thanks.

The problem is simply that the Python community has failed in this
respect. There are many platform dependent and ideology driven ways to
do deal with code editing / debugging but not actually a recommend or
"pythonic" way. Other than Smalltalk, Python has not created an own
style / identity regarding decent development environments and since
half of the community is happy with Emacs and the other half wants to
program in a VS-like environment, neither consensus nor progress has
to be expected. If you use Google groups to access comp.lang.python
you will also recognize that your question comes up every few weeks so
it has a certain tradition to create the same spectrum of answers.




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


Re: Extracting arbitrary amounts of data from a dictionary.

2007-07-05 Thread Jyotirmoy Bhattacharya
On Jul 6, 12:31 am, [EMAIL PROTECTED] wrote:
> I had nothing better to do, so I thought I would make a database that
> contained the songs played on the internet radio station I listen to
> (hardradio.com) so I could see how many differents songs/artists they
> played.

> So I end up with a the number of times any given song by a given
> artist is played in a day.  Want I want to do is to be able to print
> out a report for X number of weeks and I am trying to determine the
> best way to interate through the 'week' key of the dictionary.
>
> For example, this is week 27, the dictonary has 6 'week' keys and I
> want the data from the last 3 weeks.  Is this the best way to iterate
> through the dictionary?
>
>for date in dates[year][week].keys()[-3]:
>
> Or is there a better way with all the new features that have been
> added to Python?

Here is an implementation using as many 'new' features of Python as I
could think of.
http://phpfi.com/247634

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Kay Schluehr wrote:
> If you are sure that the exception isn't caught on another level just
> use the following showtraceback() function, manipulate it's output
> slightly and terminate your program with sys.exit()

That's what I want to avoid. In my case the error is displayed and 
evaluated in a completly different piece of software.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-05 Thread Douglas Alan
"Chris Mellon" <[EMAIL PROTECTED]> writes:

>> Some people here have been arguing that all code should use "with" to
>> ensure that the files are closed.  But this still wouldn't solve the
>> problem of the large data structures being left around for an
>> arbitrary amount of time.

> I don't think anyone has suggested that. Let me be clear about *my*
> position: When you need to ensure that a file has been closed by a
> certain time, you need to be explicit about it. When you don't care,
> just that it will be closed "soonish" then relying on normal object
> lifetime calls is sufficient. This is true regardless of whether
> object lifetimes are handled via refcount or via "true" garbage
> collection.

But it's *not* true at all when relying only on a "true GC"!  Your
program could easily run out of file descriptors if you only have a
real garbage collector and code this way (and are opening lots of
files).  This is why destructors are useless in Java -- you can't rely
on them *ever* being called.  In Python, however, destructors are
quite useful due to the refcounter.

> Relying on the specific semantics of refcounting to give
> certain lifetimes is a logic error.
>
> For example:
>
> f = some_file() #maybe it's the file store for a database implementation
> f.write('a bunch of stuff')
> del f
> #insert code that assumes f is closed.

That's not a logic error if you are coding in CPython, though I agree
that in this particular case the explicit use of "with" would be
preferable due to its clarity.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-05 Thread John Nagle
Falcolas wrote:
> On Jul 5, 10:30 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> 
>>I don't think anyone has suggested that. Let me be clear about *my*
>>position: When you need to ensure that a file has been closed by a
>>certain time, you need to be explicit about it. When you don't care,
>>just that it will be closed "soonish" then relying on normal object
>>lifetime calls is sufficient. This is true regardless of whether
>>object lifetimes are handled via refcount or via "true" garbage
>>collection. Relying on the specific semantics of refcounting to give
>>certain lifetimes is a logic error.

We may need a guarantee that if you create a local object and
don't copy a strong reference to it to an outer scope, upon exit from
the scope, the object will be destroyed.

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


Re: Portable general timestamp format, not 2038-limited

2007-07-05 Thread Wojtek
James Harris wrote :
> I have a requirement to store timestamps in a database. Simple enough
> you might think but finding a suitably general format is not easy. The
> specifics are
>
> 2) not bounded by Unix timestamp 2038 limit

I use the Java Calendar class for storing dates, which as I understand 
it, uses a long to store the date/time/milliseconds.

In my application I use the date .12.31 23:59:59.000 to store a 
blank date. Calendar has no problem storing that date, and returning 
the correct year, month, day, hour, minute, and second.

Note: Since I am using the year  as a "magic number", some of you 
may think that I am repeating the Y2K problem. Hey, if my application 
is still being used in the year 9998 I am not being paid nearly 
enough...

-- 
Wojtek :-)


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


Re: Portable general timestamp format, not 2038-limited

2007-07-05 Thread Ilya Zakharevich
[A complimentary Cc of this posting was sent to
James Harris 
<[EMAIL PROTECTED]>], who wrote in article <[EMAIL PROTECTED]>:
> On 5 Jul, 02:53, greg <[EMAIL PROTECTED]> wrote:
> > James Harris wrote:
> > > With that the time would range to +/- 9000
> > > quintillion years (18 digits)
> >
> > Use the Big Bang as the epoch, and you won't have
> > to worry about negative timestamps.

In pedantic mode: negative timestamps make sense with Big Bang as the
epoch as well.  (AFAIU, the current way of thinking is that it was
"just too hot" before the big bang, it is not that "there was
nothing".)

Hope this helps,
Ilya
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-raising exceptions with modified message

2007-07-05 Thread Kay Schluehr
On Jul 5, 3:53 pm, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> What is the best way to re-raise any exception with a message
> supplemented with additional information (e.g. line number in a
> template)? Let's say for simplicity I just want to add "sorry" to every
> exception message. My naive solution was this:
>
> try:
>  ...
> except Exception, e:
>  raise e.__class__, str(e) + ", sorry!"
>
> This works pretty well for most exceptions, e.g.
>
>  >>> try:
> ... 1/0
> ... except Exception, e:
> ... raise e.__class__, str(e) + ", sorry!"
> ...
> Traceback (most recent call last):
>File "", line 4, in 
> ZeroDivisionError: integer division or modulo by zero, sorry!
>
> But it fails for some exceptions that cannot be instantiated with a
> single string argument, like UnicodeDecodeError which gets "converted"
> to a TypeError:
>
>  >>> try:
> ... unicode('\xe4')
> ... except Exception, e:
> ... raise e.__class__, str(e) + ", sorry!"
> ...
> Traceback (most recent call last):
>File "", line 4, in 
> TypeError: function takes exactly 5 arguments (1 given)
>
> Another approach is using a wrapper Extension class:
>
> class SorryEx(Exception):
>  def __init__(self, e):
>  self._e = e
>  def __getattr__(self, name):
>  return getattr(self._e, name)
>  def __str__(self):
>  return str(self._e) + ", sorry!"
>
> try:
>  unicode('\xe4')
> except Exception, e:
>  raise SorryEx(e)
>
> But then I get the name of the wrapper class in the message:
>
> __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0:
> ordinal not in range(128), sorry!
>
> Yet another approach would be to replace the __str__ method of e, but
> this does not work for new style Exceptions (Python 2.5).
>
> Any suggestions?
>
> -- Chris

If you are sure that the exception isn't caught on another level just
use the following showtraceback() function, manipulate it's output
slightly and terminate your program with sys.exit()

def showtraceback():
'''
(Copied from code.py)
'''
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
lst = traceback.format_list(tblist)
if lst:
lst.insert(0, "Traceback (most recent call last):\n")
lst[len(lst):] = traceback.format_exception_only(type,
value)
finally:
tblist = tb = None
sys.stderr.write("".join(lst))


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


XQuery module for Python

2007-07-05 Thread bsneddon
Does anyone know of a module for Python XML that includes XQuery?
http://www.w3.org/XML/Query/
It seem like it would be very useful.  Is there a down side to XQuery
that has prevented
it from being incorporated into some of the Python XML offerings?
I have googled this some and have not seen answer to my above
questions.

Bill

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


Re: Callback scoping

2007-07-05 Thread Nick Craig-Wood
Dan <[EMAIL PROTECTED]> wrote:
>  So, I think I understand what python's scoping is doing in the
>  following situation:
> >>> x = [ lambda: ind for ind in range(10) ]
> 
>  But, I'm wondering what is the easiest (and/or most pythonic) way to
>  get the behavior I want? (If you haven't guessed, I want a list of (no
>  parameter) functions, each of which returns its index in the list.)

This is the traditional way :-

  >>> x = [ lambda ind=ind: ind for ind in range(10) ]
  >>> x[0]()
  0
  >>> x[2]()
  2
  >>> x[9]()
  9
  >>> 

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython

2007-07-05 Thread MC
Hi!

> No. The IDIspatch-interface explicitely lists what methods with what 
> arguments it has. So code completion is possible there as well.

Sorry, I think different.
In VS, assists use TLB for find methods & arguments.
Dynamic-server can't have TLB.

Other way for verify : try a Makepy on a COM server write with 
Python+Pywin32...

-- 
@-salutations

Michel Claveau


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


Re: Reversing a string

2007-07-05 Thread Martin Durkin
[EMAIL PROTECTED] (Alex Martelli) wrote in
news:[EMAIL PROTECTED]: 

> Aahz <[EMAIL PROTECTED]> wrote:
>> I would agree with people who claim
>> that you should memorize most of the built-in functions (which is
>> precisely why there is a high barrier to adding more built-in
>> functions). 
> 
> I think the built-in functions and types a beginner is likely to need
> are a "fuzzy subset" (the decision of whether to include or exclude
> something being not really obvious:-) roughly including:
> 
> abs all any bool chr cmp dict dir enumerate float getattr help hex int
> iter len list max min object open ord property raw_input reversed set
> sorted str sum tuple unichr unicode xrange zip
> 

Thanks guys, that is helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable general timestamp format, not 2038-limited

2007-07-05 Thread James Harris
On 5 Jul, 08:46, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 04 Jul 2007 22:12:46 -0400, Roy Smith <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
>
> > Astronomers use Julian Date (http://en.wikipedia.org/wiki/Julian_date) for
> > calculations like this.  It's a widely used format and highly portable.  
> > I'm sure there are libraries to deal with it in all the languages you
> > mention (and more).  Ask on sci.astro for more information.
>
>  But do you also need to account for
> Besselian or Julian centuries (Astronomy used to use B1900 as a
> computational epoch, but now uses J2000. A Julian century is 36525 days,
> Besselian century was 36524.22 days.

Whew! It was for reasons such as this that I suggested treating a day
(i.e. a /nominal/ 24-hour period) as the primary unit. The Gregorian
switch to Julian, for example, missed out a bunch of days to adjust
the calendars of Christendom but they had to be whole numbers of days.
In terms of real people (about the level I need) once a dividing line
has been chosen between one day and the next it becomes a reference
point.

Incidentally I have chosen to store /average/ values in the
application so if the sample period is 10 seconds and the count
increases by 45 I will store 4.5. This is plottable directly and I
could even allow an 11 second sample when a leap second is added (if I
needed that detail).

Is your Julian century a bit long, on average, 2000, 2400, 2800 etc
having 28 days in Feb?

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Neil Cerutti
On 2007-07-05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> You may need the traceback module to get at the error message, if
>> trying to read e.message can fail.
>> 
>> Something like this mess here: ;)
>> 
>>...
>>except Exception, e:
>>  etype, evalue, etb = sys.exc_info()
>>  ex = traceback.format_exception_only(etype, evalue)
>>  message = ex[0].partition(':')[2].strip()
>>  raise etype, message+". Sorry!", etb
>> 
>> Note that the above will break for SyntaxError (who's message
>> contains more than one line) and any kind of exception that
>> doesn't inherit from Exception.
>
> That's actually similar to what I was using in Kid already.
>
> The problem is that there are some Exceptions which cannot be
> instantiated with a single string argument, such as
> UnicodeDeocdeError. Please try the above with "unicode('\xe4')"
> instead of the dots. Instead of re-raising the
> UnicodeDecodeError, you will get a TypeError because of this
> problem.

Crud. After my third answer, I'll finally understand the
question. Unfortunately, I only had two in me.

-- 
Neil Cerutti
Low Self-Esteem Support Group will meet Thursday at 7 to 8:30 p.m. Please use
the back door. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable general timestamp format, not 2038-limited

2007-07-05 Thread James Harris
On 5 Jul, 02:53, greg <[EMAIL PROTECTED]> wrote:
> James Harris wrote:
> > With that the time would range to +/- 9000
> > quintillion years (18 digits)
>
> Use the Big Bang as the epoch, and you won't have
> to worry about negative timestamps.

Good idea if only they didn't keep shifting the femtosecond on which
it happened.. :-)


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


Re: Callback scoping

2007-07-05 Thread Marc 'BlackJack' Rintsch
On Thu, 05 Jul 2007 19:14:07 +, Dan wrote:

> So, I think I understand what python's scoping is doing in the
> following situation:
 x = [ lambda: ind for ind in range(10) ]
> 
> […]
> 
> But, I'm wondering what is the easiest (and/or most pythonic) way to
> get the behavior I want? (If you haven't guessed, I want a list of (no
> parameter) functions, each of which returns its index in the list.)

Default arguments are evaluated when the function is defined:

In [15]: x = [lambda x=i: x for i in xrange(10)]

In [16]: x[0]()
Out[16]: 0

In [17]: x[5]()
Out[17]: 5

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Nis Jørgensen
Neil Cerutti skrev:

> Mostly you can use the default 'excel' dialect and be quite
> happy, since Excel is the main reason anybody still cares about
> this unecessarily hard to parse (it requires more than one
> character of lookahead for no reason except bad design) data
> format.

I knew there had to be a reason why everyone is using xml these days ...

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


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread _spitFIRE
On Jul 5, 2:37 pm, "Jeff McNeil" <[EMAIL PROTECTED]> wrote:
> You could try pyDNS (http://pydns.sourceforge.net).  You should simply
> be able to call the 'DNS.mxlookup' function.  The other option would
> be twisted.names...
>

Thanks for the pointers.

> What about simply running an SMTP server on the machine running your
> application? Is that a possible approach?
>

  I guess that would be my last resort :)

> Not that I know of.  The protocol is standard, the queuing and retry
> logic, not so much.  Someone else may know more than I, though.
>

  I understand what you are saying. I guess, I would fall back to my
last option!

> http://mtamark.space.net/draft-stumpf-dns-mtamark-04.htmlhttp://en.wikipedia.org/wiki/Sender_Policy_Framework
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

  Thanks, once again.

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


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread _spitFIRE
On Jul 5, 2:21 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> You need to do a DNS MX lookup.  There's nothing in the Python stdlib
> which provides this functionality.  There are several libraries available
> which do this, though (Twisted among them ;).  You can probably find them
> with a little googling.  Beyond that, the rules for processing MX records
> are simple and it's not much work to pick the right host once you can do
> the MX lookups.
>
> Jean-Paul

Thanks for the pointer. However, as I said currently, I can't use
anything other than the standard libraries.

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


Re: need help with converting c function to python function

2007-07-05 Thread Anton Vredegoor
In article <[EMAIL PROTECTED]>, 
[EMAIL PROTECTED] says...

> i have a c function from some modbus documentation that i need to
> translate into python.
> 
> it looks like this:
> 
> 
> unsigned short CRC16(puchMsg, usDataLen)
> unsigned char *puchMsg ;
> unsigned short usDataLen ;
> {
>unsigned char uchCRCHi = 0xFF ;
>unsigned char uchCRCLo = 0xFF ;
>unsigned uIndex ;
>while (usDataLen--)
>{
>uIndex = uchCRCHi ^ *puchMsgg++ ;
>uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ;
>uchCRCLo = auchCRCLo[uIndex] ;
>}
>return (uchCRCHi << 8 | uchCRCLo) ;
> }
> 
> some of it i can make out, but i can't seem to figgure out
> this part ' auchCRCHi[uIndex};
> it looks like a typo, because there is a closing } that does not match
> the opening [.
> 
> 
> here is what i have so far, but is not giving me the right values
> 
>  def crc16(data):
>  crc_hi = 0xff
>  crc_lo = 0xff
>  for x in data:
>  crc_index = crc_hi ^ x
>  crc_hi = crc_lo ^ (crc_hi | crc_index)
>  crc_lo = crc_lo | crc_index
>  return (crc_hi << 8 | crc_lo)
> 
> whaddya think?

Use lateral thinking. CRC usually means some standard data checking 
algorithm. If you google for crc16 you will find various python 
implementations. Off hand I would first try this one because he seems to 
have been thinking about it:

http://mail.python.org/pipermail/python-list/2005-September/342097.html

But I don't really know what it is you are looking for, cyclic 
redundancy check?

http://en.wikipedia.org/wiki/Cyclic_redundancy_check

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Neil Cerutti wrote:
> You may need the traceback module to get at the error message, if
> trying to read e.message can fail.
> 
> Something like this mess here: ;)
> 
>...
>except Exception, e:
>  etype, evalue, etb = sys.exc_info()
>  ex = traceback.format_exception_only(etype, evalue)
>  message = ex[0].partition(':')[2].strip()
>  raise etype, message+". Sorry!", etb
> 
> Note that the above will break for SyntaxError (who's message
> contains more than one line) and any kind of exception that
> doesn't inherit from Exception.

That's actually similar to what I was using in Kid already.

The problem is that there are some Exceptions which cannot be 
instantiated with a single string argument, such as UnicodeDeocdeError.
Please try the above with "unicode('\xe4')" instead of the dots.
Instead of re-raising the UnicodeDecodeError, you will get a TypeError 
because of this problem.

-- Chris

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


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread Jeff McNeil
Inline...

On 7/5/07, _spitFIRE <[EMAIL PROTECTED]> wrote:
> On Jul 5, 1:34 pm, "Jeff McNeil" <[EMAIL PROTECTED]> wrote:
> > If you just want to send mail, you should be able to use the standard
> > smtplib module (http://docs.python.org/lib/module-smtplib.html). If
> > your recipients are on the Internet, you would need to handle MX
> > resolution yourself.
> >
>
> How complicated is to handle the MX resolution by myself? I'm sorry
> that I don't have a clue regarding that. Any pointers would be greatly
> appreciated.

You could try pyDNS (http://pydns.sourceforge.net).  You should simply
be able to call the 'DNS.mxlookup' function.  The other option would
be twisted.names...

>
> > I know you said you want to avoid a relay server, but it's probably
> > the best bet unless you control the SMTP infrastructure or are simply
> > sending messages locally.
>
> The problem is that with the scenario I'm faced with, I don't have any
> reliable SMTP server that I can use. Hence, I though I will spawn my
> own light-weight SMTP server that can send mails to the people I want,
> on the Internet. But, from what you are saying it seems, it might not
> be that light weight after all!

What about simply running an SMTP server on the machine running your
application? Is that a possible approach?

>
> > Otherwise, you'll probably need to also
> > implement queuing and retry logic (depending on your requirements).
>
> Isn't there a library module that can help me implement all this?

Not that I know of.  The protocol is standard, the queuing and retry
logic, not so much.  Someone else may know more than I, though.

>
> > There are also some warning lights that may go off and flag your mail
> > as spam if you're using a method like that...
> >
> > -Jeff
>
> Would you please fill me in with some pointers as to why my mail might
> get flagged as spam? Would it be considered spam even if I've a valid
> from address, and a proper message/subject? Does the spam filter also
> rely on the sending server's DNS etc because of which you say it might
> get flagged as spam?
>

http://mtamark.space.net/draft-stumpf-dns-mtamark-04.html
http://en.wikipedia.org/wiki/Sender_Policy_Framework

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


Extracting arbitrary amounts of data from a dictionary.

2007-07-05 Thread robinsiebler
I had nothing better to do, so I thought I would make a database that
contained the songs played on the internet radio station I listen to
(hardradio.com) so I could see how many differents songs/artists they
played.  I stored the data like this:

dates = {} #; year = {}; week = {}; date = {}; artist = []; song =
{}
#dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet
emotion': 1}, {'dream on': 2}],
#'Metallica':
[{'Fade to Black': 1}, {'Master of Puppets': 1}]},
# 'last_song': 'Master of Puppets'}}}


So I end up with a the number of times any given song by a given
artist is played in a day.  Want I want to do is to be able to print
out a report for X number of weeks and I am trying to determine the
best way to interate through the 'week' key of the dictionary.

For example, this is week 27, the dictonary has 6 'week' keys and I
want the data from the last 3 weeks.  Is this the best way to iterate
through the dictionary?

   for date in dates[year][week].keys()[-3]:

Or is there a better way with all the new features that have been
added to Python?

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Neil Cerutti
On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
> "Reader objects (DictReader instances and objects returned by
> the reader() function) have the following public methods:

Lucky for you and me, Peter Otten corrected my mistaken advice.

> next( )
>  Return the next row of the reader's iterable object as a list, 
> parsed according to the current dialect."
>
> But that's not enough information for me to use.  Also, the doc
> says basically "csv has dialects," but doesn't even enumerate
> them.  Where is the real documentation?

It's referring to the fact that csv has no standard to adhere to,
so sometimes slightly different ways of quoting and escaping
appear in csv files. Apart from that, through configuring a new
dialect you can use csv to parse many kinds of delimited data
files, not just csv as written by MS apps.

Mostly you can use the default 'excel' dialect and be quite
happy, since Excel is the main reason anybody still cares about
this unecessarily hard to parse (it requires more than one
character of lookahead for no reason except bad design) data
format.

See Library Reference 9.1.2 Dialects and Formatting Paremeters
for an explanation of what can be configured.

> Also, when I do a print of row, it comes out as:
> ['12345', 'ET']
>
> But there are no quotes around the number in the file.  Why is
> Python making it a string?

It's a string to start with, since it comes from a text file.
Besides, a string is an excellent epresentation for a zip code,
since arithmetic upon them is unthinkable.

I shared your frustration with the csv module docs when I first
read them. But happily you can skip them and just read
the easily adapted examples (9.1.5 Examples).

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


Re: Proposal: s1.intersects(s2)

2007-07-05 Thread Christoph Zwerschke
Steven D'Aprano wrote:
> I'm not a professional set theorist, but in 15-odd years of studying and
> teaching maths I've never come across mathematicians using intersect as a
> verb except as informal short-hand. I often say "North Street and South
> Street don't intersect", but "the intersection of sets A and B is empty".

I think mathematicians use more often the inverse predicate, namely 
"disjoint", which is well defined as having an empty intersection.

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-05 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Paul Boddie <[EMAIL PROTECTED]> wrote:

> However, it's interesting to consider the work that sometimes needs to
> go in to specify data structures in some languages - thinking of ML
> and friends, as opposed to Java and friends. The campaign for optional
> static typing in Python rapidly became bogged down in this matter,
> fearing that any resulting specification for type information might
> not be the right combination of flexible and powerful to fit in with
> the rest of the language, and that's how we really ended up with PEP
> 3107: make the semantics vague and pretend it has nothing to do with
> types, thus avoiding the issue completely.

I missed the campaign for optional static typing, must have been
waged in the developer list.  Unless it was not much more than
some on-line musings from GvR a year or two ago.  I don't see
how it could ever get anywhere without offending a lot of the
Python crowd, however well designed, so I can see why someone
might try to sneak it past by pretending it has nothing to do
with types.  But he didn't -- look at the examples, I think he
rather overstates the potential for static typing applications.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread Jean-Paul Calderone
On Thu, 05 Jul 2007 18:56:49 -, _spitFIRE <[EMAIL PROTECTED]> wrote:
>On Jul 5, 1:34 pm, "Jeff McNeil" <[EMAIL PROTECTED]> wrote:
>> If you just want to send mail, you should be able to use the standard
>> smtplib module (http://docs.python.org/lib/module-smtplib.html). If
>> your recipients are on the Internet, you would need to handle MX
>> resolution yourself.
>>
>
>How complicated is to handle the MX resolution by myself? I'm sorry
>that I don't have a clue regarding that. Any pointers would be greatly
>appreciated.

You need to do a DNS MX lookup.  There's nothing in the Python stdlib
which provides this functionality.  There are several libraries available
which do this, though (Twisted among them ;).  You can probably find them
with a little googling.  Beyond that, the rules for processing MX records
are simple and it's not much work to pick the right host once you can do
the MX lookups.

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


Re: Proposal: s1.intersects(s2)

2007-07-05 Thread Christoph Zwerschke
Nis Jørgensen wrote:
> The problem is, these functions can be read as "X is [consisting only
> of] digit[s]", "X is lower [case]" etc, where the bits in brackets have
> been removed for brewity. In the case of "s1 is intersect s2" there is
> no way I can see of adding words to get a correct sentence. The
> "obvious" naming is "s1.intersects(s2)" which reads as "s1 intersects
> s2", a perfectly cromulent sentence.

Agree. A possible alternative would be "s1.hasintersection(s2)", but 
s1.intersects(s2) is ok as well.

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


Callback scoping

2007-07-05 Thread Dan
So, I think I understand what python's scoping is doing in the
following situation:
>>> x = [ lambda: ind for ind in range(10) ]
>>> x
[ at 0x00BEC070>,  at 0x00BEC7F0>,
 at 0x00BECA70>,  at 0x00C1EBF0>,
 at 0x00C1EE30>,  at 0x00C228F0>,
 at 0x00C228B0>,  at 0x00C28730>,
 at 0x00C286F0>,  at 0x00C287F0>]
>>> x[0]()
9
>>> x[5]()
9
>>> x[9]()
9
>>> ind
9
>>> ind = 2
>>> x[0]()
2
>>>

But, I'm wondering what is the easiest (and/or most pythonic) way to
get the behavior I want? (If you haven't guessed, I want a list of (no
parameter) functions, each of which returns its index in the list.)

-Dan

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Neil Cerutti
On 2007-07-05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> The documentation for BaseException contains something that might
>> be relevant:
>> 
>>[...] If more data needs to be attached to the exception,
>>attach it through arbitrary attributes on the instance. All
>>
>> Users could get at the extra info you attached, but it wouldn't
>> be automatically displayed by the interpreter.
>
> Yes, that's the problem here. It wouldn't be displayed
> automatically and the users must be aware of this attribute.
> I'd like to have a more transparent solution.

You ought to be able to use the third arg of raise to raise a new
exception as if it were from the previous location, but now with
a new message.

You may need the traceback module to get at the error message, if
trying to read e.message can fail.

Something like this mess here: ;)

   ...
   except Exception, e:
 etype, evalue, etb = sys.exc_info()
 ex = traceback.format_exception_only(etype, evalue)
 message = ex[0].partition(':')[2].strip()
 raise etype, message+". Sorry!", etb

Note that the above will break for SyntaxError (who's message
contains more than one line) and any kind of exception that
doesn't inherit from Exception.

You might need some crufty try, finally to avoid having a
circular reference hang around, according to the docs for
sys.exc_info.

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


Re: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed

2007-07-05 Thread Klaas
On Jun 29, 3:48 am, "Mark Dufour" <[EMAIL PROTECTED]> wrote:

> I have just released version 0.0.22 of Shed Skin, an experimental
> Python-to-C++ compiler. Among other things, it has the exciting new
> feature of being able to generate (simple, for now) extension modules,
> so it's much easier to compile parts of a program and use them (by
> just importing them). Here's the complete changelog:
>
> -support for generating simple extension modules (linux/windows; see README)

Great work.  You might want to advertise this on the main site
(currently it states that this is impossible).

You've said somewhere that you didn't/don't plan on working on this
aspect, but it is surely the "killer feature" of shed skin needed to
for it to be able to be used as pyrex is currently (optimizing bits of
larger projects).

Of course, the perfect synthesis would be to combine the two projects
into something that applied type inferencing with a fallback to python
vm when necessary .  But there is such a large gap betwixt the
twain that such dreaming is but an excercise in fantasy (there's
always pypy).

I wish I had time to help,
-Mike

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


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread _spitFIRE
On Jul 5, 1:34 pm, "Jeff McNeil" <[EMAIL PROTECTED]> wrote:
> If you just want to send mail, you should be able to use the standard
> smtplib module (http://docs.python.org/lib/module-smtplib.html). If
> your recipients are on the Internet, you would need to handle MX
> resolution yourself.
>

How complicated is to handle the MX resolution by myself? I'm sorry
that I don't have a clue regarding that. Any pointers would be greatly
appreciated.

> I know you said you want to avoid a relay server, but it's probably
> the best bet unless you control the SMTP infrastructure or are simply
> sending messages locally.

The problem is that with the scenario I'm faced with, I don't have any
reliable SMTP server that I can use. Hence, I though I will spawn my
own light-weight SMTP server that can send mails to the people I want,
on the Internet. But, from what you are saying it seems, it might not
be that light weight after all!

> Otherwise, you'll probably need to also
> implement queuing and retry logic (depending on your requirements).

Isn't there a library module that can help me implement all this?

> There are also some warning lights that may go off and flag your mail
> as spam if you're using a method like that...
>
> -Jeff

Would you please fill me in with some pointers as to why my mail might
get flagged as spam? Would it be considered spam even if I've a valid
from address, and a proper message/subject? Does the spam filter also
rely on the sending server's DNS etc because of which you say it might
get flagged as spam?

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


Re: SMTP server w/o using Twisted framework

2007-07-05 Thread Jeff McNeil
If you just want to send mail, you should be able to use the standard
smtplib module (http://docs.python.org/lib/module-smtplib.html). If
your recipients are on the Internet, you would need to handle MX
resolution yourself.

I know you said you want to avoid a relay server, but it's probably
the best bet unless you control the SMTP infrastructure or are simply
sending messages locally. Otherwise, you'll probably need to also
implement queuing and retry logic (depending on your requirements).
There are also some warning lights that may go off and flag your mail
as spam if you're using a method like that...

-Jeff

On 7/5/07, _spitFIRE <[EMAIL PROTECTED]> wrote:
> Is it possible to run a SMTP server that sends mail to recipients
> using standard libraries, without using twisted framework, and also
> without using any relay server?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Thomas Jollans
On Thursday 05 July 2007, Captain Poutine wrote:
> Peter Otten wrote:
> > Neil Cerutti wrote:
> >> On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
> >>> I'm simply trying to read a CSV into a dictionary.
> >>>
> >>> (if it matters, it's ZIP codes and time zones, i.e.,
> >>> 35983,CT
> >>> 39161,CT
> >>> 47240,EST
> >>>
> >>>
> >>>
> >>> Apparently the way to do this is:
> >>>
> >>> import csv
> >>>
> >>> dictZipZones = {}
> >>>
> >>> reader = csv.reader(open("some.csv", "rb"))
> >>> for row in reader:
> >>>  # Add the row to the dictionary
> >>
> >> In addition to Chris's answer, the csv module can read and write
> >> dictionaries directly. Look up csv.DictReader and csv.DictWriter.
> >
> > DictReader gives one dict per row, with field names as keys. The OP is
> > more likely to want
> >
> > dict(csv.reader(open("some.csv", "rb")))
> >
> > which produces a dict that maps ZIP codes to time zones.
> >
> > Peter
>
> Thanks Peter, that basically works, even if I don't understand it.
>
> What does "rb" mean? (read binary?)
> Why are the keys turned into strings (they are not quoted in the .csv
> file)?

"rb" is read, in binary mode. On DOS and derivatives this prevents intentional 
file corruption when reading. (for ASCII files, omitting the b might be 
desirable...)

Think of csv.reader as a fancy variant of the following: (fancy in that it 
supports things like non-comma separators and comma escaping)

def CSVReader(file):
  for line in file:
yield line.split(',')

-- 
  Regards,   Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key :
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6


signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list

SMTP server w/o using Twisted framework

2007-07-05 Thread _spitFIRE
Is it possible to run a SMTP server that sends mail to recipients
using standard libraries, without using twisted framework, and also
without using any relay server?

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Captain Poutine
Peter Otten wrote:
> Neil Cerutti wrote:
> 
>> On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
>>> I'm simply trying to read a CSV into a dictionary.
>>>
>>> (if it matters, it's ZIP codes and time zones, i.e.,
>>> 35983,CT
>>> 39161,CT
>>> 47240,EST
>>>
>>>
>>>
>>> Apparently the way to do this is:
>>>
>>> import csv
>>>
>>> dictZipZones = {}
>>>
>>> reader = csv.reader(open("some.csv", "rb"))
>>> for row in reader:
>>>  # Add the row to the dictionary
>> In addition to Chris's answer, the csv module can read and write
>> dictionaries directly. Look up csv.DictReader and csv.DictWriter.
> 
> DictReader gives one dict per row, with field names as keys. The OP is more
> likely to want
> 
> dict(csv.reader(open("some.csv", "rb")))
> 
> which produces a dict that maps ZIP codes to time zones.
> 
> Peter
> 

Thanks Peter, that basically works, even if I don't understand it.

What does "rb" mean? (read binary?)
Why are the keys turned into strings (they are not quoted in the .csv file)?

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-05 Thread Falcolas
On Jul 5, 10:30 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
>
> I don't think anyone has suggested that. Let me be clear about *my*
> position: When you need to ensure that a file has been closed by a
> certain time, you need to be explicit about it. When you don't care,
> just that it will be closed "soonish" then relying on normal object
> lifetime calls is sufficient. This is true regardless of whether
> object lifetimes are handled via refcount or via "true" garbage
> collection. Relying on the specific semantics of refcounting to give
> certain lifetimes is a logic error.
>
> For example:
>
> f = some_file() #maybe it's the file store for a database implementation
> f.write('a bunch of stuff')
> del f
> #insert code that assumes f is closed.
>
> This is the sort of code that I warn against writing.
>
> f = some_file()
> with f:
>   f.write("a bunch of stuff")
> #insert code that assumes f is closed, but correctly this time
>
> is better.

This has raised a few questions in my mind. So, here's my newbie
question based off this.

Is this:

f = open(xyz)
f.write("wheee")
f.close()
# Assume file is closed properly.

as "safe" as your code:

f = some_file()
with f:
  f.write("a bunch of stuff")
#insert code that assumes f is closed, but correctly this time

Thanks!

G

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


Re: Re-raising exceptions with modified message

2007-07-05 Thread Christoph Zwerschke
Neil Cerutti wrote:
> The documentation for BaseException contains something that might
> be relevant:
> 
>[...] If more data needs to be attached to the exception,
>attach it through arbitrary attributes on the instance. All
>
> Users could get at the extra info you attached, but it wouldn't
> be automatically displayed by the interpreter.

Yes, that's the problem here. It wouldn't be displayed automatically and 
the users must be aware of this attribute. I'd like to have a more 
transparent solution.

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Captain Poutine
Neil Cerutti wrote:
> On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
>> I'm simply trying to read a CSV into a dictionary.
>>
>> (if it matters, it's ZIP codes and time zones, i.e.,
>> 35983,CT
>> 39161,CT
>> 47240,EST
>>
>>
>>
>> Apparently the way to do this is:
>>
>> import csv
>>
>> dictZipZones = {}
>>
>> reader = csv.reader(open("some.csv", "rb"))
>> for row in reader:
>>  # Add the row to the dictionary
> 
> In addition to Chris's answer, the csv module can read and write
> dictionaries directly. Look up csv.DictReader and csv.DictWriter.
> 

Yes, thanks.  I was happy when I saw it at 
http://www.python.org/doc/2.4/lib/node615.html


"Reader objects (DictReader instances and objects returned by the 
reader() function) have the following public methods:

next(   )
 Return the next row of the reader's iterable object as a list, 
parsed according to the current dialect."

But that's not enough information for me to use.  Also, the doc says 
basically "csv has dialects," but doesn't even enumerate them.  Where is 
the real documentation?


Also, when I do a print of row, it comes out as:
['12345', 'ET']

But there are no quotes around the number in the file.  Why is Python 
making it a string?

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Peter Otten
Neil Cerutti wrote:

> On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
>> I'm simply trying to read a CSV into a dictionary.
>>
>> (if it matters, it's ZIP codes and time zones, i.e.,
>> 35983,CT
>> 39161,CT
>> 47240,EST
>>
>>
>>
>> Apparently the way to do this is:
>>
>> import csv
>>
>> dictZipZones = {}
>>
>> reader = csv.reader(open("some.csv", "rb"))
>> for row in reader:
>>  # Add the row to the dictionary
> 
> In addition to Chris's answer, the csv module can read and write
> dictionaries directly. Look up csv.DictReader and csv.DictWriter.

DictReader gives one dict per row, with field names as keys. The OP is more
likely to want

dict(csv.reader(open("some.csv", "rb")))

which produces a dict that maps ZIP codes to time zones.

Peter

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


Re: WXPYTHON push button call a frame

2007-07-05 Thread Roel Schroeven
Marcpp schreef:
> Hi I need to call a widget from a button in WXPYTHON. I've tried to
> this from a function like this, but when push the button, the program
> opens a window and do error.
> Any idea?
> 
> .
> def DialogRRHH(self,event):
> prog = wx.PySimpleApp(0)
> wx.InitAllImageHandlers()
> DialogRRHH = MTRRHH(None, -1, "")
> prog.SetTopWindow(DialogRRHH)
> DialogRRHH.Show()
> prog.MainLoop()
> 
> class MTRRHH(wx.Frame):
> ...
> if __name__ == "__main__":
> app = wx.PySimpleApp(0)
> wx.InitAllImageHandlers()
> tasques = tasques(None, -1, "")
> app.SetTopWindow(tasques)
> tasques.Show()
> app.MainLoop()

In DialogRRHH() you create a new application object with a new event 
loop, while you already have one running. wxPython should have only one 
application object though; otherwise there conflicts between the 
different event loops. Also you don't need to call 
wx.InitAllImageHandlers() again.

It seems to me that in DialogRRHH() you want to create a dialog and wait 
until the user closes it. In that case, it should look more or less like 
this (beware, I'm not a wxPython expert myself):

 def DialogRRHH(self, event):
 DialogRRHH = MTRRHH(None, -1, "")
 DialogRRHH.ShowModal()

Also, in that case MTRRHH should be a wxDialog, not a wxFrame.

In case you want to show MTRRHH without waiting for the user to close 
it, use DialogRRHH.Show() instead of .ShowModal(). I think MTRRHH can be 
either a wxDialog or a wxForm in that case.



-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Proposal: s1.intersects(s2)

2007-07-05 Thread OKB (not okblacke)
Steven D'Aprano wrote:

> Just because I've never come across it doesn't mean it exists, so
> I'd be grateful for any reference to a technical definition, or
> even references to any mathematician using intersect as a verb in a
> vigorous, non-hand-waving way. Here's a link to get you started:

Here ( http://arxiv.org/PS_cache/math/pdf/0702/0702029v1.pdf )is a 
Russian math text (in English) which says:

"If A \cap B 6 = \emptyset, then we say that the sets A and B do 
intersect. Otherwise, if A \cap B = \emptyset, then we say that these 
sets do not intersect."

Here ( 
http://www.tcs.ifi.lmu.de/~fischerf/publications/bfh_tark07.pdf ) is a 
math paper which says:

"Sets that are disjoint in the diagram may have an empty 
intersection, i.e., there exist instances where these sets do not 
intersect."

A simple Google search will also turn up numerous uses of the 
phrase "non-intersecting sets", which would seem to be parallel (i.e., 
people are not bending over backwards to say "disjoint sets" or "sets 
with empty intersection").

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


need help with converting c function to python function

2007-07-05 Thread nephish
hello all,

i have a c function from some modbus documentation that i need to
translate into python.

it looks like this:


unsigned short CRC16(puchMsg, usDataLen)
unsigned char *puchMsg ;
unsigned short usDataLen ;
{
   unsigned char uchCRCHi = 0xFF ;
   unsigned char uchCRCLo = 0xFF ;
   unsigned uIndex ;
   while (usDataLen--)
   {
   uIndex = uchCRCHi ^ *puchMsgg++ ;
   uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ;
   uchCRCLo = auchCRCLo[uIndex] ;
   }
   return (uchCRCHi << 8 | uchCRCLo) ;
}

some of it i can make out, but i can't seem to figgure out
this part ' auchCRCHi[uIndex};
it looks like a typo, because there is a closing } that does not match
the opening [.


here is what i have so far, but is not giving me the right values

 def crc16(data):
 crc_hi = 0xff
 crc_lo = 0xff
 for x in data:
 crc_index = crc_hi ^ x
 crc_hi = crc_lo ^ (crc_hi | crc_index)
 crc_lo = crc_lo | crc_index
 return (crc_hi << 8 | crc_lo)

whaddya think?

thanks

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


Re: The best platform and editor for Python

2007-07-05 Thread Mark Morss
On Jul 1, 3:30 pm, "Sönmez Kartal" <[EMAIL PROTECTED]> wrote:
"Emacs is the best for anything for me."

Me too.

Also, as pointed out by some others, a debugger is not really all that
necessary for an interpreted language like Python.

> > Hi,
> > For experienced with Pyhton users, which developing software and
> > enviroment would you suggest for Pyhton programming? Compiler+Editor
> > +Debugger.
>
> > Also what are your suggestions for beginners of Pyhton programming?
>
> > Thank you.
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list


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

Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Neil Cerutti
On 2007-07-05, Captain Poutine <[EMAIL PROTECTED]> wrote:
> I'm simply trying to read a CSV into a dictionary.
>
> (if it matters, it's ZIP codes and time zones, i.e.,
> 35983,CT
> 39161,CT
> 47240,EST
>
>
>
> Apparently the way to do this is:
>
> import csv
>
> dictZipZones = {}
>
> reader = csv.reader(open("some.csv", "rb"))
> for row in reader:
>  # Add the row to the dictionary

In addition to Chris's answer, the csv module can read and write
dictionaries directly. Look up csv.DictReader and csv.DictWriter.

-- 
Neil Cerutti
In my prime I could have handled Michael Jordan.  Of course, he would be only
12 years old. --Jerry Sloan
-- 
http://mail.python.org/mailman/listinfo/python-list


deliberate versus os socket timeout

2007-07-05 Thread Robin Becker
While messing about with some deliberate socket timeout code I got an 
unexpected 
timeout after 20 seconds when my code was doing socket.setdefaulttimeout(120).

Closer inspection revealed that this error in fact seemed to come from the os 
(in this case windows xp).

By inspection of test cases the error.reason from the deliberate socket timeout 
looks like
 'timed out'
whereas the windows caused timeout error.reason looks like
 '(10060 operation timed out)'

it would be nice to know if that is in fact true and whether there is any way 
to 
do the attribution of errors more sensibly.

Both of these seem to cause urllib2.URLError and presumably appear somewhere in 
the socket code.

It might be nice if the deliberate timeout could be something like 'timed out 
deliberately after xxx seconds'.

More importantly is there anything I can do to avoid these wrong os inspired 
timeouts? I'm just using urllib2 to read from a remote site inside of a cgi 
script. I'm not sure it's a big problem, but I have no idea what could cause it.

The code I'm using is based on one of jjlee's recipes

def httpGet(self):
 import urllib2, socket
 from xml.sax.saxutils import escape
 oto = socket.getdefaulttimeout()
 try:
 socket.setdefaulttimeout(self.timeout)
 self.url = url = self.makeUrl(self.params)
 try:
 self.response = r = urllib2.urlopen(url)
 except urllib2.URLError, e:
 if hasattr(e, 'reason'):
 msg = 'HTTP error '+str(e.reason)
 if 'time' in msg:
 msg += '(our timeout=%s)' % socket.getdefaulttimeout()
 return 1,escape(msg)
 elif hasattr(e, 'code'):
 return 1, escape('The server couldn\'t fulfill the 
request.\nError code: '+str(e.code))
 else:
 # everything is fine
 h = self.headers = {}
 
 return 0,..
 finally:
 socket.setdefaulttimeout(oto)

-- 
Robin Becker

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


Re: The best platform and editor for Python

2007-07-05 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Gregor Horvath  <[EMAIL PROTECTED]> wrote:
>kimiraikkonen schrieb:
>
>> My another aim is: Can i develop graphical applications (like in
>> Windows) which contain menus, interactive dialog boxes etc. using
>> Ptyhon?
>> 
>> I got it quite but not sure. I don't know Ptyhon's capability skills
>> for creating interactive softwares like in Windows's created by C++ or
>> Delphi.
>> 
>
>have a look at Dabo
>
>http://www.dabodev.com/
.
.
.
I want to make this explicit for the benefit of the original questioner:
A.  Dabo's great stuff; but
B.  there are, at the same time, quite a few
other frameworks for GUI programming with
Python http://wiki.python.org/moin/GuiProgramming >.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best platform and editor for Python

2007-07-05 Thread kimiraikkonen
I just wanted a simple answer to my simple question, however topic has
messed up. Think questioner as a beginner and use more understandable
terms to help :)

Thanks.

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


Re: disappearing documentation of `coerce`

2007-07-05 Thread Alan Isaac
> On 2007-07-05, Alan Isaac <[EMAIL PROTECTED]> wrote:
>>Once upon a time, `coerce` was documented
>>with the other built-ins.


Neil Cerutti wrote:
> It's now documented in Library Reference 2.2 Non-essential
> Built-in Functions.
> Apparently it is no longer needed or useful, but only kept for
> backward compatibility.


Thanks.
I now see that it is going away:
http://www.python.org/dev/peps/pep-3100/

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


Re: login http://cheeseshop.python.org/pypi broken ?

2007-07-05 Thread gert
On Jul 5, 8:30 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> gert schrieb:
>
> > tried reseting password but i can not login anymore to upload my new
> > source code ?
>
> Please try again. It was a misconfiguration which should be fixed now.
>
> Regards,
> Martin

thank you, it works.

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

Re: Proposal: s1.intersects(s2)

2007-07-05 Thread Steven D'Aprano
On Thu, 05 Jul 2007 01:48:58 +, richyjsm wrote:

> On Jul 4, 8:14 pm, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
>> However, there's a very subtle flaw in the idea. While "the intersection"
>> of two sets is well-defined, "these two sets intersect" is (surprisingly!)
>> _not_ well-defined.
> 
> Poppycock!  It's perfectly well defined:  two sets intersect if and
> only if their intersection is nonempty.

That's certainly _a_ definition.

I'm not a professional set theorist, but in 15-odd years of studying and
teaching maths I've never come across mathematicians using intersect as a
verb except as informal short-hand. I often say "North Street and South
Street don't intersect", but "the intersection of sets A and B is empty".

Just because I've never come across it doesn't mean it exists, so I'd be
grateful for any reference to a technical definition, or even references
to any mathematician using intersect as a verb in a vigorous,
non-hand-waving way. Here's a link to get you started:

http://www.google.com.au/search?q=define%3Aintersect


> There's absolutely no reason
> to single out the empty set for special treatment in this definition.

But you can't avoid treating the empty set as special, because it _is_
special. You can only choose where to do so. For instance, do sets
intersect with themselves?

By my rule, every set intersects with itself, no exceptions.

By your rule, every set intersects with itself, except for the empty set.



>> The problem comes if we (perhaps naively) try to say that if a set A is a
>> subset of set B, set A must intersect with B.
> 
> Well of course false statements are going to cause problems.

My statement is only false if we treat the empty set as special, which
you've said we shouldn't do.

By my rule: if A <= B, then A and B intersect, no exceptions.

By your rule: if A <= B and A is not the empty set, then A and B intersect.



>> (Not all intersecting sets are subsets, but all subsets are
>> intersecting sets.)
> 
> Not true.

Can you give a counter-example, without treating the empty set as special?

Of course if you exclude the empty set by definition, my statement is no
longer true -- but that's begging the question of whether we should
exclude the empty set or not.


>> As a result, any proposed function or method that returns a True/False
>> value for whether set A intersects with set B needs to define (and
>> justify) what it means to say that two sets intersect when one or both
>> are the empty set.
> 
> Nope.  There's one, obvious, correct definition, as given above.  No
> need to mention the empty set at all.

It is obvious, but whether it is correct or not depends on how you decide
whether two things intersect or not.


-- 
Steven.

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


Re: Proposal: s1.intersects(s2)

2007-07-05 Thread Steven D'Aprano
On Thu, 05 Jul 2007 07:34:28 -0700, Aahz wrote:

> In article <[EMAIL PROTECTED]>,
> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>>
>>My main feeling is that any such function should be a set method rather
>>than a built-in function like len(). The name change was comparatively
>>unimportant.
> 
> Look up at the Subject: line.  

Subject line? What's that?

*chagrined wink*

> There never was any suggestion that
> intersects() be anything other than a set method.

My fault for replying to a reply instead of the original post.


-- 
Steven.

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-05 Thread Chris Mellon
On 7/5/07, Captain Poutine <[EMAIL PROTECTED]> wrote:
> I'm simply trying to read a CSV into a dictionary.
>
> (if it matters, it's ZIP codes and time zones, i.e.,
> 35983,CT
> 39161,CT
> 47240,EST
>
>
>
> Apparently the way to do this is:
>
> import csv
>
> dictZipZones = {}
>
> reader = csv.reader(open("some.csv", "rb"))
> for row in reader:
>  # Add the row to the dictionary
>
>
> But how to do this?
>
> Apparently there is no dict.append() nor dict.add()
>
> But what is there?  I see vague references to "the dict() constructor"
> and some examples, and news that it has been recently improved.  But
> where is the full, current documentation for the dict() constructor?
>

There's no dict.append or dict.add because a dict doesn't require
them. You insert keys via the normal indexing interface:

somedict[somekey] = somevalue.

Depending on which direction your mapping is, you may be interested in
the setdefault method.

The dict constructor is described in section 2.1, built in functions
(even though it's not a function anymore).

The other dict methods are described in section 3.8, mapping types.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >