Import Issue

2006-06-01 Thread praveenkumar . 117
Hi all,
   I am facing a problem while importing a file in python
script.
   After doing import file i am updating that file. Later i am
accessing a dictionary contained in that
   file. Eventhough changes are reflected in the file... When i
access a dictionary those changes are
   not there. I believe that it is accessing from the object
file that is created when i did import at
   the start of the script. I will be kind enough if somebody
suggest solution to this problem.
Regards-
praveen

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


Re: grouping a flat list of number by range

2006-06-01 Thread Paddy

Jim Segrave wrote:
> In article <[EMAIL PROTECTED]>,
> Paddy <[EMAIL PROTECTED]> wrote:
> >
> >What I ran was more like the version below, but i did a quick
> >separation of the line that has the ';' in it and goofed.
> >
>  def interv2(inlist):
> >...  for i,val in enumerate(inlist):
> >...  if i==0:
> >...  tmp = val
> >...  elif val != valinc:
> >...  yield [tmp, valinc]; tmp = val
> >...  valinc = val+1
> >...  yield [tmp, valinc]
> >...
>  list(interv2(inlist))
> >[[3, 4], [6, 9], [12, 14], [15, 16]]
>
> Fails on an empty list, as tmp is not defined when it hits the yield
>
>
> --
> Jim Segrave   ([EMAIL PROTECTED])

Yep, I still, purposfully, decided not to put any guard checks in
because:
  Its very easy to add.
  It detracts from the algorithm.
  It might never be called with an empty list in-situ.
  It is correct for the original posters testcases.
  Yah gotta leave-em something to do ;-)

But you-too are right. Don't just cut-n-paste newsgroup solutions. they
need testing for your particular use. I doubt anyone on C.L.P. would be
malicious, but your actual use of a function having a wider scope to
inputs than mentioned might be fairy common.

(Damn, I wanted to use 'caveat emptor', but it does not apply as
nothing is being bought. Oh well :-)

-- Pad.

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


Re: Are there something like "Effective Python"?

2006-06-01 Thread BartlebyScrivener
>> I just finished reading Learning Python 3rd ed,

For real? I thought there was only a 2nd edition.

http://www.oreilly.com/catalog/lpython2/

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


Re: C# equivalent to range()

2006-06-01 Thread Michel Claveau
Hi!

> There are thousands of threads to choose from in this forum.
> If they didn't like this question, they could have picked any other one
> to discuss.
> There's no need to be disagreeable :-)

I think the same thing.

-- 
@-salutations

Michel Claveau


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


Re: Are there something like "Effective Python"?

2006-06-01 Thread Ray
I think Aahz stated somewhere that he was workign on Effective Python.
I'm not sure if it's an ongoing plan or it's been canned though?

Mike Meng wrote:
> Hi all,
>  I just finished reading Learning Python 3rd ed, and am doing my
> first Python application, which   retrieves and process text and XML
> documents from Web. Python helped me to write the application in a few
> hours, I'm very happy with its productivity. But the performance is not
> satisfactory. I decide to optimized it in Python before trying C/C++
> extensions. But I don't know Python much and have no clu to tune my
> program. Also, I don't know what Pythonist's preferred styles. Are
> there any books/documents which play the similar role for Python as
> 'Effective C++' does for C++?
>
> For example, one of my friends read my program and suggest me to
> move the re.compile() out of a for-loop, since the regular pattern is
> fixed, and re.compile() is slow. I want to find more such advice, where
> can I find them?
> 
> Thank you.
> 
> Mike

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


Re: image lib & Qt4

2006-06-01 Thread Fredrik Lundh
Fredrik Lundh wrote:

> To get better performance, you should be able to use PIL's tostring() 
> method together with the QImage(buffer, width, height, depth, 
> colortable, numColors, bitOrder) form of the QImage constructor.

for PyQt4, that seems to have changed to QImage(buffer, width, height, 
format), where format is a QImage.Format_XXX specifier.

in other words, this should work:

if im.mode != "RGB":
im = im.convert("RGB")

data = im.tostring("raw", "BGRX")

image = QImage(data, im.size[0], im.size[1],
QImage.Format_RGB32)

note that the QImage descriptor will point into the data buffer, so you 
must hang on to data for as long you're using image.

(I haven't found a way to attach a user attribute to a QImage class; it 
doesn't complain when I do that, but it doesn't seem to do the right 
thing...)



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


Re: grouping a flat list of number by range

2006-06-01 Thread Gerard Flanagan

Gerard Flanagan wrote:
> [EMAIL PROTECTED] wrote:
> > hello,
> >
> > i'm looking for a way to have a list of number grouped by consecutive
> > interval, after a search, for example :
> >
> > [3, 6, 7, 8, 12, 13, 15]
> >
> > =>
> >
> > [[3, 4], [6,9], [12, 14], [15, 16]]
> >
> > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> > [6:9], and so on)
> >
> > i was able to to it without generators/yield but i think it could be
> > better with them, may be do you an idea?
> >
> > best regards,
> >
>
> a list comprehension/itertools version (this won't work with an empty
> list):
>
> from itertools import groupby
>
> a = [3, 6, 7, 8, 12, 13, 15]
>
> result = [[3, 4], [6,9], [12, 14], [15, 16]]
>
> b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x:
> x in a)]
>
> c = [ b[i:i+2] for i in range(0,len(a),2) ]
>
> assert c == result
>
>
> Gerard

change len(a) to len(b) in case a has duplicates like
[3,3,3,6,7,8,12,13,15]

Gerard

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


Re: Are there something like "Effective Python"?

2006-06-01 Thread Luis M. González
Mike Meng wrote:
> Hi all,
>  I just finished reading Learning Python 3rd ed, and am doing my
> first Python application, which   retrieves and process text and XML
> documents from Web. Python helped me to write the application in a few
> hours, I'm very happy with its productivity. But the performance is not
> satisfactory. I decide to optimized it in Python before trying C/C++
> extensions. But I don't know Python much and have no clu to tune my
> program. Also, I don't know what Pythonist's preferred styles. Are
> there any books/documents which play the similar role for Python as
> 'Effective C++' does for C++?
>
> For example, one of my friends read my program and suggest me to
> move the re.compile() out of a for-loop, since the regular pattern is
> fixed, and re.compile() is slow. I want to find more such advice, where
> can I find them?
>
> Thank you.
>
> Mike

http://wiki.python.org/moin/PythonSpeed/PerformanceTips

Also, I suggest checking Psyco ( http://psyco.sourceforge.net/ ), which
can easily improve your program's speed with no change in your code.

Hope this helps...
Luis

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


Re: grouping a flat list of number by range

2006-06-01 Thread Gerard Flanagan
[EMAIL PROTECTED] wrote:
> hello,
>
> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
>
> [3, 6, 7, 8, 12, 13, 15]
>
> =>
>
> [[3, 4], [6,9], [12, 14], [15, 16]]
>
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)
>
> i was able to to it without generators/yield but i think it could be
> better with them, may be do you an idea?
>
> best regards,
>

a list comprehension/itertools version (this won't work with an empty
list):

from itertools import groupby

a = [3, 6, 7, 8, 12, 13, 15]

result = [[3, 4], [6,9], [12, 14], [15, 16]]

b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x:
x in a)]

c = [ b[i:i+2] for i in range(0,len(a),2) ]

assert c == result


Gerard

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


Re: C# equivalent to range()

2006-06-01 Thread Luis M. González
Erik Max Francis wrote:
> Yeah, what jerks.  They actually wanted to talk about Python, not some
> random other language that you're trying to learn that has nothing to do
> with it ...

There are thousands of threads to choose from in this forum.
If they didn't like this question, they could have picked any other one
to discuss.
There's no need to be disagreeable :-)

Luis

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


Re: Inheritance structure less important in dynamic languages?

2006-06-01 Thread Ben Finney
"Marvin" <[EMAIL PROTECTED]> writes:

> It's been claimed that inheritance structures are less important in
> dynamic languages like Python.

Who claimed that? I ask not because I doubt your assertion ("it was
claimed"), but rather that if someone claimed something, it seems
better to ask that person your next question:

> Why is that and where can i read more about that?

The person who claimed it is more likely to be able and willing to
defend it.

-- 
 \   Eccles: "I just saw the Earth through the clouds!"  Lew: "Did |
  `\ it look round?"  Eccles: "Yes, but I don't think it saw me."  |
_o__)  -- The Goon Show, _Wings Over Dagenham_ |
Ben Finney

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


Re: C# equivalent to range()

2006-06-01 Thread Erik Max Francis
Neuruss wrote:

> I thougt that maybe some python programmer could have experience here
> with c# and give me a little hint.
> 
> But unfortunately, there are people here who are not willing to waste
> their time helping, but enjoy to waste their time niggling...

Yeah, what jerks.  They actually wanted to talk about Python, not some 
random other language that you're trying to learn that has nothing to do 
with it ...

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   A man can stand a lot as long as he can stand himself.
   -- Axel Munthe
-- 
http://mail.python.org/mailman/listinfo/python-list


Are there something like "Effective Python"?

2006-06-01 Thread Mike Meng
Hi all,
 I just finished reading Learning Python 3rd ed, and am doing my
first Python application, which   retrieves and process text and XML
documents from Web. Python helped me to write the application in a few
hours, I'm very happy with its productivity. But the performance is not
satisfactory. I decide to optimized it in Python before trying C/C++
extensions. But I don't know Python much and have no clu to tune my
program. Also, I don't know what Pythonist's preferred styles. Are
there any books/documents which play the similar role for Python as
'Effective C++' does for C++?

For example, one of my friends read my program and suggest me to
move the re.compile() out of a for-loop, since the regular pattern is
fixed, and re.compile() is slow. I want to find more such advice, where
can I find them?

Thank you.

Mike

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


Re: image lib & Qt4

2006-06-01 Thread Fredrik Lundh
aljosa wrote:

> does anybody know how to load  (in-memory
> representation of PNG image) from Qt (v.4.1.3) as QImage?

If you want the data from a StringIO object, you can either *read* the 
data from the object (it's a file-like object, after all), or use the 
getvalue() method.

Something like

qim = QImage()
qim.loadFromData(f.getvalue())

should work (unless they've changed things around lately).

To get better performance, you should be able to use PIL's tostring() 
method together with the QImage(buffer, width, height, depth, 
colortable, numColors, bitOrder) form of the QImage constructor.



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


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread A.M


Well the work is done now. I arrived home at 10:30 PM.



The application takes data from Oracle 10g stored procedures and renders 
data to both HTML and CSV formats. The HTML reports have summary and 
grouping sections and the HTML files are Excel friendly. The application is 
modular and consists of reusable modules. The application is called every 
night by scheduled task. The CSV and HTML files are being deployed to Apache 
for internal employee access.



This isn't a complex and big system. Tomorrow, I'll add the email 
functionality to the application and re-use it's components for more 
reports.



Now that I finished the 1st part of the application, I have to admit that 
choosing Python was an excellent decision. Python is an awesome programming 
language with comprehensive library and great community support.



I am not that new to Python anymore.. I had a productive day. Thanks 
everybody for help.





"gregarican" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Dear A.M.,
>
> The day is complete. My TPS reports still aren't on my desk. Either
> with or without cover sheets. Not a good time to try to teach yourself
> a new language. Please gather your belongings and move down to basement
> storage C.
>
> That'd be great,
> Bill Lumberg
>
> John Machin wrote:
>> A.M wrote:
>>
>> > The application is not mission critical system. It is just a simple
>> > reporting tool.
>>
>> Famous last words.
> 


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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread D H
A.M wrote:
> Hi,
> 
> Is there any built in feature in Python that can format long integer 
> 123456789 to 12,3456,789 ?

Apparently you need to use the locale module.  This is the
example they give online to print a simple number with commas:

import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
print locale.format("%d", 123456789, grouping=True)

Someone should make a module that uses .NET or Java's formmating.
You just use {0:n} or ###,### instead of all the above.
http://blog.stevex.net/index.php/string-formatting-in-csharp/
http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C# equivalent to range()

2006-06-01 Thread John Machin

Neuruss wrote:
> John Machin wrote:
> > Neuruss wrote:
> > > I'm sorry for asking about another language here, but since I only know
> > > Python and I'm trying to write something in C#, I guess this is the
> > > best place...
> > >
> >
> > Bad guess. Ask questions about language X on comp.lang.X
>
> Well, perhaps I should.
> And I should also explain how range and extend work in python, which is
> almost the same thing...
>
> I thougt that maybe some python programmer could have experience here
> with c# and give me a little hint.
>
> But unfortunately, there are people here who are not willing to waste
> their time helping, but enjoy to waste their time niggling...
> 

Plonk.

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


Re: C# equivalent to range()

2006-06-01 Thread Neuruss
Thank you DH!!



D H wrote:
> Neuruss wrote:
> > I'm sorry for asking about another language here, but since I only know
> > Python and I'm trying to write something in C#, I guess this is the
> > best place...
> >
> > I'd like to know how to write this in C#:
> >
> > x=[]
> > sz = 1000
> > x.extend(range(sz))
> >
> > My question is about "range" and "extend". Is there any equivalent in
> > C#?
> >
> > Thanks in advance,
> > Neuruss
> >
>
> List mylist = new List();
> for (int i=0; i<1000; i++)
> {
>  mylist.Add(i);
> }
>
> You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield,
> foreach, and so forth instead, but for your example this is simplest.
>
> Another option is to use boo.  http://boo.codehaus.org/
> It uses python's syntax but is as fast as C#.  The only change you'd
> have to make in that code is to capitalize the Extend method call.

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


Re: C# equivalent to range()

2006-06-01 Thread Neuruss
John Machin wrote:
> Neuruss wrote:
> > I'm sorry for asking about another language here, but since I only know
> > Python and I'm trying to write something in C#, I guess this is the
> > best place...
> >
>
> Bad guess. Ask questions about language X on comp.lang.X

Well, perhaps I should.
And I should also explain how range and extend work in python, which is
almost the same thing...

I thougt that maybe some python programmer could have experience here
with c# and give me a little hint.

But unfortunately, there are people here who are not willing to waste
their time helping, but enjoy to waste their time niggling...

Thanks anyway!
Neuruss

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


Re: C# equivalent to range()

2006-06-01 Thread D H
Neuruss wrote:
> I'm sorry for asking about another language here, but since I only know
> Python and I'm trying to write something in C#, I guess this is the
> best place...
> 
> I'd like to know how to write this in C#:
> 
> x=[]
> sz = 1000
> x.extend(range(sz))
> 
> My question is about "range" and "extend". Is there any equivalent in
> C#?
> 
> Thanks in advance,
> Neuruss
> 

List mylist = new List();
for (int i=0; i<1000; i++)
{
 mylist.Add(i);
}

You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield, 
foreach, and so forth instead, but for your example this is simplest.

Another option is to use boo.  http://boo.codehaus.org/
It uses python's syntax but is as fast as C#.  The only change you'd
have to make in that code is to capitalize the Extend method call.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is a wiki engine based on a cvs/svn a good idea?

2006-06-01 Thread R. P. Dillon
TWiki, written in perl, makes extensive use of versioning/diff 
functionality you mention through the use of RCS, which, IIRC, is the 
basis for CVS.  This method eliminates the need for the repository as 
such, and merely requires the presence of the RCS files (and RCS).

Unless you _want_ to host your data on a separate machine than the one 
hosting the wiki, you might consider RCS as an alternative to CVS.

OTOH, it is clearly a good idea to base your software on such a tool, 
given that TWiki does it and has proven to be quite successful.  =)

Rick

piotr malin'ski wrote:
> I'm planning to wite a fully featured wiki in Python in one of
> frameworks. I've seen some notes about wiki/documentation management
> scripts that use SVN as a data storage/versioning.
> I've been using SVN a bit but I don't know if it's a good idea to use
> it in a wiki engine. Pro: versioning / diffs, Cons: you need your own
> svn/cvs repository, can pyLucene or Xapwrap index this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C# equivalent to range()

2006-06-01 Thread Ben Finney
"Neuruss" <[EMAIL PROTECTED]> writes:

> I'm sorry for asking about another language here, but since I only
> know Python and I'm trying to write something in C#, I guess this is
> the best place...

Really, it isn't. Post in a C# discussion forum, describing the
behaviour you want from your program.

-- 
 \  "The only tyrant I accept in this world is the still voice |
  `\   within."  -- Mahatma Gandhi |
_o__)  |
Ben Finney

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Alex Martelli
Slawomir Nowaczyk <[EMAIL PROTECTED]> wrote:

> On Thu, 01 Jun 2006 15:12:23 -0700
> [EMAIL PROTECTED] wrote:
> 
> #> I believe that 'is' tests equality of reference, such that
> #> 
> #> >>> a = range(1,3)
> #> >>> b = range(1,3)
> #> >>> a is b
> #> False
> #> 
> #> The 'is' operator tells you whether a and b refer to the same object.
> #> What I've been discussing is whether == should test for "structural"
> #> equality so that a and b remain equivalent under parallel mutations
> #> (and also under single mutations to common references)
> 
> What does "parallel mutations" mean? In particular, what should be the
> results of each of the following three comparisons:
> 
> x, y, z = [1],[1],[1]
> a, b = [x,y], [y,z]
> c, d = [[1],[1]], [[1],[1]]
> a == b
> c == d
> a[0].remove(1)
> b[0].remove(1)
> a == b
> 
> So, do I understand correctly that you would like first comparison
> (a==b) to return "False" and second comparison (c==d) to return
> "True"?

I sure hope not, since, e.g.:

ridiculous = c[0]

is not a "mutation" (so equality should still hold, right?), and then it
becomes weird to claim that

ridiculous.append('bah, humbug!')

is a "nonparallel mutation to" c and/or d.

In fact, I'm starting to wonder if by Michaels' requirement ANY
non-*IDENTICAL* containers (with non-identical mutable items) could EVER
be deemed "equal".  If he's arguing that "==" should mean exactly the
same as "is", that's even crazier than I had gauged so far.

But of course, since Michaels still refuses to provide simple,
straightforward operational definitions of what it IS that he wants, all
of this remains vague and ill-defined.  See *WHY* it's so important to
provide precision rather than just the handwaving he's given so far?


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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Alex Martelli
Slawomir Nowaczyk <[EMAIL PROTECTED]> wrote:

> On Thu, 01 Jun 2006 13:40:34 -0700
> [EMAIL PROTECTED] wrote:
> 
> #> Scott David Daniels wrote:
> #> > Would you say that envelope containing five $100 bills is equal to
> #> > an envelope containing five $100 bills with different serial numbers?
> 
> #> Yes (unless I was testing the assertion that the second envelope did
> #> not contain counterfeits of the first)
> 
> So, what if Bank of America later decided that bills with serial
> numbers containing "7" are no longer valid?

Then Wachowia would no doubt be happy to take my business away from
BoA;-).

I suspect you believe BoA is some kind of "official" body -- it isn't,
just like Deutschebank is not one in Germany (rather, Bundesbank is).

Just to share some tidbits (about which, as an Italian now living
between San Francisco and San Jose, I'm sort of proud of...!-)...:

Bank of America is a private bank, founded in San Francisco more than
100 years ago by an Italian-American guy (Amadeo Giannini, born in San
Jose, CA, but to Italian-born parents) as "Bank of Italy", then renamed
in 1930 in part because the Italian State bank "Banca d'Italia"
objected.  It rose to prominence right after the SF earthquake of 100
years ago, by opening and staffing a temporary branch to ensure
depositors could access their money when they most needed it, while most
other banks were staying closed.

 
> In other word, *if* you assume equality must be preserved by future
> modifications, than no two different (modifiable) objects can ever be
> really equal.

Yes, apart from the (slight and understandable!) mistake about BoA's
role, this is an excellent example.  Here, a global change (to the rule
about what banknotes are "equal" to each other, by making some of them
invalid and thus unequal to others) perturbs Michaels' desired "strong
equality definition" -- to preserve it, equality must degenerate to
identity.  A Python example would be a change to the default encoding
(not officially supported but achievable through a reload(sys), hint;-)
which could easily make a bytestring equal, or not, to a Unicode string!


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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> I agree with Alex that checking for this type of inequality is not a
> trivial programming exercise.  It requires (at least) a parallel

I'm not asking for ANY programming: I'm asking for a *straightforward
operational definition*.  If the concept which you hanker after is NOT
subject to a straightforward operational definition, then I would rule
out that said concept could POSSIBLY be "natural".

> Alternatively, it might make sense to disallow == for containers by
> raising a TypeError although that would eliminate a largely useful
> feature.

This may be the best example I've ever seen of Emerson's well-known
quote about foolish consistency -- except that I don't think this
behavior would be "consistent" (either wisely or foolishly) with
anything except a vague handwaving set of constraints whose
"naturalness" (assuming it's unfeasible to provide a good and
straightforward operational definition) is out of the question.


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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> Hi Alex,
> With all due respect to your well-deserved standing in the Python
> community, I'm not convinced that equality shouldn't imply invariance
> under identical operations.

So, why aren't you satisfying my request?  Provide a simple concrete
definition of what your idea of equality WOULD behave like.  I notice
that your lack of response stands out like a sore thumb -- all you're
providing is a set of constraints you desire and a collection of
illfounded analogies and handwaving.  Traditional mathematics does not
support the concept of "change", nor the distinction between equality
and identity; the "real world" has no way to define what modifications
are "identical" except by their effects (if the results differ, either
the original equality was ill-posited or the modifications were not
"identical").  But the real world DOES have the concept of "performing
exactly the same sequence of operational steps", and, by THAT definition
of "equal modifications", then your assertion:

> make identical modifications to the engines of two identical
> automobiles, I expect the difference in performance to be identical.

is ill-founded -- or, rather, your *expectation* may be ill-founded.

Take two systems of any significant complexity that are similar enough
to be called "identical" by ALL observers (because trying to ascertain
the differences, if any, would inevitably perturb the systems
irretrievably by Heisenberg's effect -- i.e., there are no OBSERVABLE
differences, which by Occam's Razor requires you to posit the systems
are equal, because you cannot prove otherwise -- and entities must not
be multiplied beyond necessity, so supposing that "observably equal"
systems are indeed equal is Occam-compliant).

Now, perform "identical" (ditto) modifications: in the real world, due
to quantum effects, there WILL be sub-observable differences in what
you're doing to the first one and to the second one.  If the systems are
unstable to start with, they may well amplify those differences to
observable proportions -- and there you are: the effect of the "equal"
change on "equal" system may easily become observably unequal.
Philosophically, you may classify this as an "observation" of both
systems, which reasoning backwards lead you to posit that either the
systems were NOT equal to start with or the modifications weren't...
that is, IF you also posit determinism, which, as well we know, is an
unwarrantedly strong hypothesis for systems in which the differences at
quantum level matter.  Feel free to follow Einstein (and diverse
light-years away from the last few decades of physics) in positing that
there MUST exist "hidden variables" (unobservable except maybe in
destructive, irreversible ways) explaining the difference -- I'll stick
with the mainstream of physics and claim your expectation was badly
founded to start with.

I can debate epistemology with the best, but this is not really the
proper forum for this -- starting with the crucial distinction, what it
means, in mathematics OR in the real world, to state that two systems
are "equal but NOT identical"?  In the end, such debates tend to prove
rather futile and unproductive, however.

In the world of programming languages, we cut through the chase by
requesting *operational* (Brouwer-ian, mathematically speaking)
definitions.  Provide the *operational* definition of how you WANT
equality checking to work, contrast it with my simple two-lines one, and
THEN we can have a meaningful debate of which one is the correct one to
use in the core of a programming language that has the (blessing and
curse of) mutable data objects...


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


Re: Best Python Editor

2006-06-01 Thread Terry Hancock
Fredrik Lundh wrote:
>  "Manoj Kumar P" wrote:
> > Can anyone tell me a good python editor/IDE?
>  emacs!
[...]
Fredrik Lundh wrote:
>  "Manoj Kumar P" wrote:
> > Can anyone tell me a good python editor/IDE?
>  vim!

There is much truth in this man's replies.  ;-D

Cheers,
Terry


-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: C# equivalent to range()

2006-06-01 Thread John Machin

Neuruss wrote:
> I'm sorry for asking about another language here, but since I only know
> Python and I'm trying to write something in C#, I guess this is the
> best place...
> 

Bad guess. Ask questions about language X on comp.lang.X

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


C# equivalent to range()

2006-06-01 Thread Neuruss
I'm sorry for asking about another language here, but since I only know
Python and I'm trying to write something in C#, I guess this is the
best place...

I'd like to know how to write this in C#:

x=[]
sz = 1000
x.extend(range(sz))

My question is about "range" and "extend". Is there any equivalent in
C#?

Thanks in advance,
Neuruss

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


Inheritance structure less important in dynamic languages?

2006-06-01 Thread Marvin

Hi,

It's been claimed that inheritance structures are less important in dynamic
languages like Python. Why is that and where can i read more about that?

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


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread gregarican
Dear A.M.,

The day is complete. My TPS reports still aren't on my desk. Either
with or without cover sheets. Not a good time to try to teach yourself
a new language. Please gather your belongings and move down to basement
storage C.

That'd be great,
Bill Lumberg

John Machin wrote:
> A.M wrote:
>
> > The application is not mission critical system. It is just a simple
> > reporting tool.
> 
> Famous last words.

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread A.M


Thanks for help. Is there any comprehensive library for number formatting 
available on the net?



Alan




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


Re: Tkinter - changing existing Dialog?

2006-06-01 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Michael Yanowitz <[EMAIL PROTECTED]> wrote:
.
.
.
>2) Change the text of a label or button that is already drawn?
>
>  based on actions taken by the user. Can it be done without destroying
>the present dialog or the objects in it and creating a new one?
.
.
.
  import Tkinter

  root = Tkinter.Tk()

  counter = 0

  # This is one of several ways one can access the Button's label.
  def set_text():
  b.configure(text = "The button has been pushed %d time(s)." % counter)

  def actions():
  global counter
  counter += 1
  set_text()

  b = Tkinter.Button(root, command = actions)
  set_text()
  b.pack()
  root.mainloop()

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


Re: Tkinter - changing existing Dialog?

2006-06-01 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Michael Yanowitz <[EMAIL PROTECTED]> wrote:
>Hello:
>
>
>   I have a Tkinter GUI Dialog with many buttons and labels and text
>widgets.
>What I would like to do is, can I:
>
>1) Disable/deactivate/hide a button, text widget that is already drawn (and
>   of course the opposite enable/activate/show it)?
.
.
.
  import Tkinter

  root = Tkinter.Tk()

  def actions():
  print "Someone pushed the button."
  b.configure(state = Tkinter.DISABLED)

  b = Tkinter.Button(root, text = "Push me", command = actions)
  b.pack()
  root.mainloop()

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread John Machin

[EMAIL PROTECTED] wrote:
> A.M wrote:
> > Hi,
> >
> > Is there any built in feature in Python that can format long integer
> > 123456789 to 12,3456,789 ?
> >
> > Thank you,
> > Alan
>
> I did this for putting commas into monetary amounts (thus the .2f):
>
> def commas(value):
> return "".join(commafy("%.2f" % value))
>
> def commafy(s):
> pieces = s.split(".")
> l = len(pieces[0])
> for i in range(0,l):
> if (l - i) % 3 or not i:
> yield pieces[0][i]
> else:
> yield ","
> yield pieces[0][i]
> if len(pieces) > 1:
> yield "." + pieces[1]
> 

I dips me lid -- that's far fuglier than mine!!!

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


Re: execfile then import back

2006-06-01 Thread overly . crazy . steve
> ## x.py and y.py (they are identical) ##
> import testexec
> print "1:", v, testexec.v
> testexec.v = 7

Oops, testexec should be changed to t instead. That is:

## x.py and y.py (they are identical) ##
import t
print "1:", v, t.v
t.v = 7

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


execfile then import back

2006-06-01 Thread overly . crazy . steve
I am seeing something strange with execfile. I've simplified the code
to:

## t.py ##
print "here"
v = None

def f():
global v
v = 6

if __name__ == "__main__":
f()
print "0:", v
execfile("x.py")
print "0:", v
execfile("y.py")
print "0:", v

## x.py and y.py (they are identical) ##
import testexec
print "1:", v, testexec.v
testexec.v = 7

Runing "python t.py" (with Python 2.4.2), the printout I got is:

here
0: 6
here
1: 6 None
0: 6
1: 6 7
0: 6

So there is apparently 2 different instances of v at run time. Can
someone please explain (1) why this is the case, and (2) assuming this
is correct behavior, how I can avoid this? Thanks.

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread Ben Cartwright
John Machin wrote:
> A.M wrote:
> > Hi,
> >
> > Is there any built in feature in Python that can format long integer
> > 123456789 to 12,3456,789 ?
> >
>
> Sorry about my previous post. It would produce 123,456,789.
> "12,3456,789" is weird -- whose idea PHB or yours??

If it's not a typo, it's probably a regional thing.  See, e.g.,
http://en.wikipedia.org/wiki/Indian_numbering_system

--Ben

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread james . wondrasek

A.M wrote:
> Hi,
>
> Is there any built in feature in Python that can format long integer
> 123456789 to 12,3456,789 ?
>
> Thank you,
> Alan

I did this for putting commas into monetary amounts (thus the .2f):

def commas(value):
return "".join(commafy("%.2f" % value))

def commafy(s):
pieces = s.split(".")
l = len(pieces[0])
for i in range(0,l):
if (l - i) % 3 or not i:
yield pieces[0][i]
else:
yield ","
yield pieces[0][i]
if len(pieces) > 1:
yield "." + pieces[1]


jtm

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread Ben Cartwright
A.M wrote:
> Is there any built in feature in Python that can format long integer
> 123456789 to 12,3456,789 ?

The locale module can help you here:

  >>> import locale
  >>> locale.setlocale(locale.LC_ALL, '')
  'English_United States.1252'
  >>> locale.format('%d', 123456789, True)
  '123,456,789'

Be sure to read the caveats for setlocale in the module docs:
  http://docs.python.org/lib/node323.html
I'd recommend calling setlocale only once, and always at the start of
your program.

--Ben

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread John Machin

A.M wrote:
> Hi,
>
> Is there any built in feature in Python that can format long integer
> 123456789 to 12,3456,789 ?
>

Sorry about my previous post. It would produce 123,456,789.
"12,3456,789" is weird -- whose idea PHB or yours??

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


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread John Machin

A.M wrote:

> The application is not mission critical system. It is just a simple
> reporting tool.

Famous last words.

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


Re: Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread John Machin
On 2/06/2006 9:08 AM, A.M wrote:
> Hi,
> 
> Is there any built in feature in Python that can format long integer 
> 123456789 to 12,3456,789 ?
> 
> Thank you,
> Alan

Not that I know of, but this little kludge may help:
8<---
import re

subber = re.compile(r'^(-?\d+)(\d{3})').sub

def fmt_thousands(amt, sep):
 if amt in ('', '-'):
 return ''
 repl = r'\1' + sep + r'\2'
 while True:
 new_amt = subber(repl, amt)
 if new_amt == amt:
 return amt
 amt = new_amt

if __name__ == "__main__":
 for prefix in ['', '-']:
 for k in range(11):
 arg = prefix + "1234567890.1234"[k:]
 print "<%s> <%s>" % (arg, fmt_thousands(arg, ","))
8<---

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


Re: Recommendations for CD/DVD-based or on-line Python classes?

2006-06-01 Thread Scott David Daniels
Joel Kolstad wrote:
> Just curious... I have plenty of programming background (C++ being the 
> closest 
> to Python), and I have a copy of Lutz's "Learning Python," but before I dive 
> head-first into that tome, does anyone know of a web-based or CD/DVD-based 
> training class that's priced for individuals?
> 
> Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis 
> had a bunch of on-line instructor-lead courses, where you'd read a chapter in 
> a book, read the instructor's take on the chapter (just a few pages), perform 
> the programming assignments, and ask the instructor if you had any 
> difficulties.  There was a solid schedule (ch. 1 this week, ch. 2 the next, 
> etc. -- courses repeated every quarter or somesuch) as well.  Ziff-Davis 
> charged something like $99 or $199/year for this service (all the courses you 
> wanted to sign up for -- quite reasonable, IMO) and also made money by 
> requiring the use of their own books (which were often someone else's book 
> that they'd just put their own name on) -- which were usually cheap enough at 
> something like $30/ea.
> 
> That whole setup worked quite well for me... anyone know of something 
> similar? 
> If not I probably will have to force myself to spend an hour a day or 
> something going through Lutz's book...
> 
> Thanks,
> ---Joel Kolstad
> 
> 
Well, you could read through all the web thingies around (the online
tutorial is great), many others listed "getting started" should help,
and to really build your muscles, try the "Python challenge."

-- 
--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grouping a flat list of number by range

2006-06-01 Thread John Machin
On 2/06/2006 8:36 AM, Paddy wrote:
> [EMAIL PROTECTED] wrote:
>> hello,
>>
>> i'm looking for a way to have a list of number grouped by consecutive
>> interval, after a search, for example :
>>
>> [3, 6, 7, 8, 12, 13, 15]
>>
>> =>
>>
>> [[3, 4], [6,9], [12, 14], [15, 16]]
>>
>> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
>> [6:9], and so on)
>>
>> i was able to to it without generators/yield but i think it could be
>> better with them, may be do you an idea?
>>
>> best regards,
>>
>> J.
> 
> I did a proceedural version, then re-read your post and did a generator
> based version ;-)
> 
> === interv1 ===
 inlist = [3, 6, 7, 8, 12, 13, 15]
 tmp = []
 for i,val in enumerate(inlist):
> ...   if i==0:
> ...   tmp.append(val)
> ...   elif val != valinc:
> ...   tmp += [valinc, val]
> ...   valinc = val+1
> ...
 tmp.append(valinc)
 tmp
> [3, 4, 6, 9, 12, 14, 15, 16]
 tmp[0::2]
> [3, 6, 12, 15]
 tmp[1::2]
> [4, 9, 14, 16]
 zip(tmp[0::2], tmp[1::2])
> [(3, 4), (6, 9), (12, 14), (15, 16)]
> 
> === END interv1 ===
> 
> === interv2 ===
 def interv2(inlist):
> ...   for i,val in enumerate(inlist):
> ...   if i==0:
> ...   tmp = val
> ...   elif val != valinc:
> ...   yield [tmp, valinc]
> ... tmp = val
> ...   valinc = val+1
> ...   yield [tmp, valinc]
> ...
 list(interv2(inlist))
> [[3, 4], [6, 9], [12, 14], [15, 16]]
> 
> === END interv2 ===
> 
> - Paddy.
> 

Oh the siren call of every new feature in the language!
enumerate() just to get a first-time test, and then botch it??

Read the following; the replacement version uses a simple old-fashioned 
inelegant flag, works with an empty sequence, and doesn't depend on the 
input being sliceable or indexable.

HTH,
John

C:\junk>type interval.py
def interv2(inlist):
 for i,val in enumerate(inlist):
 if i==0:
 tmp = val
 elif val != valinc:
 yield [tmp, valinc]
 tmp = val
 valinc = val+1
 yield [tmp, valinc]

def interv3(inseq):
 first = True
 for val in inseq:
 if first:
 tmp = val
 first = False
 elif val != valinc:
 yield [tmp, valinc]
 tmp = val
 valinc = val + 1
 if not first:
 yield [tmp, valinc]

tests = [
 [3, 4, 6, 9, 12, 14, 15, 16],
 [3, 3, 3],
 [],
 ]

for func in (interv3, interv2):
 for test in tests:
 print "%s(%s) ->" % (func.__name__, test)
 result = list(func(test))
 print "\t%r" % result

C:\junk>interval.py
interv3([3, 4, 6, 9, 12, 14, 15, 16]) ->
 [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]]
interv3([3, 3, 3]) ->
 [[3, 4], [3, 4], [3, 4]]
interv3([]) ->
 []
interv2([3, 4, 6, 9, 12, 14, 15, 16]) ->
 [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]]
interv2([3, 3, 3]) ->
 [[3, 4], [3, 4], [3, 4]]
interv2([]) ->
Traceback (most recent call last):
   File "C:\junk\interval.py", line 33, in ?
 result = list(func(test))
   File "C:\junk\interval.py", line 9, in interv2
 yield [tmp, valinc]
UnboundLocalError: local variable 'tmp' referenced before assignment

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


Re: Replace one element of a tuple (LONG)

2006-06-01 Thread Captain Dondo
BartlebyScrivener wrote:
>>>that one column is always the same, the name of the host that
>>>the database resides on.
> 
> 
> Then why are you pulling all of the other stuff out of the db? Why
> don't you just
> 
> UPDATE tablename
> SET hostname(or colname) = 'localhost'
> WHERE search condition = the rows you want to change
> 

Well, there is an interactive dialog where the user picks which records 
s/he wants to put into the other database.  So in the target database, 
that table may not even exist until the user selects which records go in 
there.

But it does sound like I need to do some work on the database query  :-)

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


Re: Replace one element of a tuple (LONG)

2006-06-01 Thread BartlebyScrivener
>> that one column is always the same, the name of the host that
>> the database resides on.

Then why are you pulling all of the other stuff out of the db? Why
don't you just

UPDATE tablename
SET hostname(or colname) = 'localhost'
WHERE search condition = the rows you want to change

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


Recommendations for CD/DVD-based or on-line Python classes?

2006-06-01 Thread Joel Kolstad
Just curious... I have plenty of programming background (C++ being the closest 
to Python), and I have a copy of Lutz's "Learning Python," but before I dive 
head-first into that tome, does anyone know of a web-based or CD/DVD-based 
training class that's priced for individuals?

Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis 
had a bunch of on-line instructor-lead courses, where you'd read a chapter in 
a book, read the instructor's take on the chapter (just a few pages), perform 
the programming assignments, and ask the instructor if you had any 
difficulties.  There was a solid schedule (ch. 1 this week, ch. 2 the next, 
etc. -- courses repeated every quarter or somesuch) as well.  Ziff-Davis 
charged something like $99 or $199/year for this service (all the courses you 
wanted to sign up for -- quite reasonable, IMO) and also made money by 
requiring the use of their own books (which were often someone else's book 
that they'd just put their own name on) -- which were usually cheap enough at 
something like $30/ea.

That whole setup worked quite well for me... anyone know of something similar? 
If not I probably will have to force myself to spend an hour a day or 
something going through Lutz's book...

Thanks,
---Joel Kolstad


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


Re: Conditional Expressions in Python 2.4

2006-06-01 Thread Robert Kern
A.M wrote:

> Do we have the conditional expressions in Python 2.4?

No.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Can Python format long integer 123456789 to 12,3456,789 ?

2006-06-01 Thread A.M
Hi,

Is there any built in feature in Python that can format long integer 
123456789 to 12,3456,789 ?

Thank you,
Alan



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


Re: Zope / Plone Groups

2006-06-01 Thread Rene Pijlman
[EMAIL PROTECTED]:
>are there any specific groups for zope / plone regarding questions?

Try plone-users: http://plone.org/support

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Conditional Expressions in Python 2.4

2006-06-01 Thread A.M
Hi,



I am using Python 2.4. I read the PEP 308 at:

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



I tried the statement:



a= "Yes" if 1==1 else "No"



but the interpreter doesn't accept it.



Do we have the conditional expressions in Python 2.4?



Thank you,

Alan


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


Re: grouping a flat list of number by range

2006-06-01 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Paddy <[EMAIL PROTECTED]> wrote:
>
>What I ran was more like the version below, but i did a quick
>separation of the line that has the ';' in it and goofed.
>
 def interv2(inlist):
>...for i,val in enumerate(inlist):
>...if i==0:
>...tmp = val
>...elif val != valinc:
>...yield [tmp, valinc]; tmp = val
>...valinc = val+1
>...yield [tmp, valinc]
>... 
 list(interv2(inlist))
>[[3, 4], [6, 9], [12, 14], [15, 16]]

Fails on an empty list, as tmp is not defined when it hits the yield


-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: grouping a flat list of number by range

2006-06-01 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Paddy <[EMAIL PROTECTED]> wrote:
>I did a little re-arranging of the generator version:
>
>def interv3(inlist):
>tmp = inlist[0]
>valinc = tmp+1
>for val in inlist[1:]:
>if val != valinc:
>yield [tmp, valinc];
>tmp = val
>valinc = val+1
>yield [tmp, valinc]

Still fails when passed an empty list, the initial assignment to tmp
is an IndexError




-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: Replace one element of a tuple (LONG)

2006-06-01 Thread Captain Dondo
Brian wrote:
> Captain Dondo wrote:
> 
>>What I'd like to do is build the correct selectlist in the first place,
>>rather than build the wrong one and then rebuild a correct one.
> 
> 
> This is sounding more like a SQL/DB problem and less like a Python one.
>  If you have a field that is being pulled from the database that you
> would like to do a substitution on, I'm fairly sure MySQL includes a
> CASE statement in their flavor of SQL.  Instead of performing a  SELECT
> * in your script you could select the individual fields you want, and
> instead of just pulling the problematic column as is, you could pull it
> as something like "select case when sourcehost = x then y else
> sourcehost end case, ...".  Naturally if an entire column needs to be
> replaced with a static value, you won't even need to use CASE.
> 

AFAICT, that one column is always the same, the name of the host that 
the database resides on.  As myth can use multiple backends , it sort of 
makes sense, but it seems redunandant to me.  Even with mutliple 
backends, I would hope you have a single database

I thought about just picking all the other fields via the SQL query, but 
this seemed simpler to me

Anyway, here's the code I came up with:

for listing in itemlist:
 (rectitle, recdate) = listing.split('|',1)
 c.execute("""SELECT * FROM recorded WHERE title=%s AND 
starttime=%s""",(rectitle,recdate))
 for listitem in c.fetchall():
 if 'tooth.seiner.lan' in  listitem:
 selectlist.append(listitem[:7] + 
('hermes.seiner.lan',) + listitem[9:])
 else:
 selectlist.append(listitem)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if not CGI:

2006-06-01 Thread Bruno Desthuilliers
Max a écrit :
(snip)
> But now I'm ready to do it in the real world. Nothing complicated, but a 
> real project. And I have to choose my tools. Zope, Plone, Django, what 
> are these? 

Zope -> an application server
Plone -> a CMS built upon Zope
Django -> a MVC fullstack framework (fullstack : integration with a 
server + ORM + template system + various utilities).

> I don't have to stick with Python, although it's my preferred 
> language. I know Python, Java and C++. But I'm ready to learn Ruby if 
> RoR is as good as they say.

RoR is not bad, but really over-hyped. There's no shortage of at least 
as good solutions in Python. You may want to look at Django, Turbogears, 
Pylons, web.py etc. for fullstack MVC frameworks.

There are more barebones solutions, like CherryPy (the application 
server Turbogears is built upon), Myghty (extended perl::Mason port, 
used by Pylons), mod_python (if you're an hard-core Apache fanatic), 
WebStack (if you want to deploy on almost any server), and some other 
pieces like formencode (form validation), SQLObject (ORM, used by 
Turbogears and Pylons), SQLAlchemy (another ORM, very promising, by the 
author of Myghty), Routes (port of RoR routes, used by Pylons) and a lot 
of templating systems. So you can even build your own fullstack 
framework from existing pieces (that's what Turbogears and Pylons are 
doing FWIW).

And also whole lot of more specific solutions : Albatross, Quixote, 
Karrigel, Twisted/nevow, (...), and of course Zope 2.x and 3.x, but it 
may be overkill and long to learn.

Also, FWIW, Trac is almost a usable (somewhat minimalist) framework on 
it's own.

So the problem is not  "are there good solutions", but "which one to 
choose" !-) The answer of course depends on what you want and what you 
like, but taking a few days to play with Turbogears, Django and Pylons 
might be a good idea.

> I could do it in Python cgi (or mod_python). But it seems from all the 
> hype that this is not a good way to write scaleable, extensible web 
> applications.

Trac is a perfect counter-example IMHO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grouping a flat list of number by range

2006-06-01 Thread Paddy

Jim Segrave wrote:
> In article <[EMAIL PROTECTED]>,
> Paddy <[EMAIL PROTECTED]> wrote:
> >=== interv2 ===
>  def interv2(inlist):
> >...  for i,val in enumerate(inlist):
> >...  if i==0:
> >...  tmp = val
> >...  elif val != valinc:
> >...  yield [tmp, valinc]
> >... tmp = val
> >...  valinc = val+1
> >...  yield [tmp, valinc]
> >...
>  list(interv2(inlist))
> >[[3, 4], [6, 9], [12, 14], [15, 16]]
> >
> >=== END interv2 ===
>
> This doesn't actually run, changing it to make it do so:
>
> def interv2(inlist):
> tmp = valinc = 0
> for i,val in enumerate(inlist):
> if i==0:
> tmp = val
> valinc = val + 1
> elif val != valinc:
> yield [tmp, valinc]
> tmp = val
> valinc = val+1
> yield [tmp, valinc]
>
> it now works, but returns [0, 0] when passed an empty list, when it
> should return nothing at all
> --
> Jim Segrave   ([EMAIL PROTECTED])
Jim, I had tabs/spaces indent problems when cut-n-pasting.

What I ran was more like the version below, but i did a quick
separation of the line that has the ';' in it and goofed.

>>> def interv2(inlist):
... for i,val in enumerate(inlist):
... if i==0:
... tmp = val
... elif val != valinc:
... yield [tmp, valinc]; tmp = val
... valinc = val+1
... yield [tmp, valinc]
... 
>>> list(interv2(inlist))
[[3, 4], [6, 9], [12, 14], [15, 16]]

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


Re: grouping a flat list of number by range

2006-06-01 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Paddy <[EMAIL PROTECTED]> wrote:
>=== interv2 ===
 def interv2(inlist):
>...for i,val in enumerate(inlist):
>...if i==0:
>...tmp = val
>...elif val != valinc:
>...yield [tmp, valinc]
>... tmp = val
>...valinc = val+1
>...yield [tmp, valinc]
>...
 list(interv2(inlist))
>[[3, 4], [6, 9], [12, 14], [15, 16]]
>
>=== END interv2 ===

This doesn't actually run, changing it to make it do so:

def interv2(inlist):
tmp = valinc = 0
for i,val in enumerate(inlist):
if i==0:
tmp = val
valinc = val + 1
elif val != valinc:
yield [tmp, valinc]
tmp = val
valinc = val+1
yield [tmp, valinc]

it now works, but returns [0, 0] when passed an empty list, when it
should return nothing at all





-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: Replace one element of a tuple (LONG)

2006-06-01 Thread Brian
Captain Dondo wrote:
> What I'd like to do is build the correct selectlist in the first place,
> rather than build the wrong one and then rebuild a correct one.

This is sounding more like a SQL/DB problem and less like a Python one.
 If you have a field that is being pulled from the database that you
would like to do a substitution on, I'm fairly sure MySQL includes a
CASE statement in their flavor of SQL.  Instead of performing a  SELECT
* in your script you could select the individual fields you want, and
instead of just pulling the problematic column as is, you could pull it
as something like "select case when sourcehost = x then y else
sourcehost end case, ...".  Naturally if an entire column needs to be
replaced with a static value, you won't even need to use CASE.

HTH

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


Re: grouping a flat list of number by range

2006-06-01 Thread Paddy
I did a little re-arranging of the generator version:

def interv3(inlist):
tmp = inlist[0]
valinc = tmp+1
for val in inlist[1:]:
if val != valinc:
yield [tmp, valinc];
tmp = val
valinc = val+1
yield [tmp, valinc]

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


Re: struct: type registration?

2006-06-01 Thread John Machin
On 2/06/2006 4:18 AM, Serge Orlov wrote:
> Giovanni Bajo wrote:
>> John Machin wrote:
>>> I am an idiot, so please be gentle with me: I don't understand why you
>>> are using struct.pack at all:
>> Because I want to be able to parse largest chunks of binary datas with custom
>> formatting. Did you miss the whole point of my message:
>>
>> struct.unpack("3liiSiiShh", data)
> 
> Did you want to write struct.unpack("Sheesh", data) ? Seriously, the
> main problem of struct is that it uses ad-hoc abbreviations for
> relatively rarely[1] used functions calls and that makes it hard to
> read.

Indeed. The first time I saw something like struct.pack('20H', ...) I 
thought it was a FORTRAN format statement :-)

> 
> If you want to parse binary data use pyconstruct
> 
> 

Looks promising on the legibility and functionality fronts. Can you make 
any comment on the speed? Reason for asking is that Microsoft Excel 
files have this weird "RK" format for expressing common float values in 
32 bits (refer http://sc.openoffice.org, see under "Documentation" 
heading). I wrote and support the xlrd module (see 
http://cheeseshop.python.org/pypi/xlrd) for reading those files in 
portable pure Python. Below is a function that would plug straight in as 
an example of Giovanni's custom unpacker functions. Some of the files 
can be very large, and reading rather slow.

Cheers,
John

from struct import unpack

def unpack_RK(rk_str): # arg is 4 bytes
 flags = ord(rk_str[0])
 if flags & 2:
 # There's a SIGNED 30-bit integer in there!
 i, = unpack('>= 2 # div by 4 to drop the 2 flag bits
 if flags & 1:
 return i / 100.0
 return float(i)
 else:
 # It's the most significant 30 bits
 # of an IEEE 754 64-bit FP number
 d, = unpack('http://mail.python.org/mailman/listinfo/python-list


Solved: Tktable, WinXP and ActiveState Python 2.4.3,x

2006-06-01 Thread jerry . levan

[EMAIL PROTECTED] wrote:
> Hi,
> I have a python app that runs fine on MacOS X and Fedora Core 5.
>
> This evening I dragged the folder over to my windows partition and
> tried to run the rascal.
>
> The program starts up fine but at the first call to create a Table
> object
> I get
>
> Traceback (most recent call last):
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "C:\Documents and
> Settings\Jerry\Desktop\PyPgBrowseUni\PyPgExplorer.py", line 7, in ?
> obj.main()
>   File "C:\Documents and
> Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line 72,
> in main
> self.build_ui( info)
>   File "C:\Documents and
> Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line
> 187, in build_ui
> rowtagcommand=self.rowproc
>   File "C:\Documents and
> Settings\Jerry\Desktop\PyPgBrowseUni\Resources\Tktable.py", line 64, in
> __init__
> master.tk.call('load', '', 'Tktable' )
> TclError: package "Tktable" isn't loaded statically
> :
>
> I get the same error if I try to create a Table object from the command
> line
> in a console.
>
> I tried waving a dead chicken at my laptop but it did no good.
>
> Is there some special magic to get Tktable.py to play nice?
> I do have the latest Tcl from Active State loaded on my box and
> the Tktable in my Tk programs work well...
>
> Thanks for any insight
>
> Jerry

Thanks to the good folks at Active State here is a way to use tktable
from Python.

1) Put the wrapper file Tktable.py into C:\Python24\Lib\lib-tk
2) Copy the whole folder C:\Tcl\lib\Tktable* to C:\Python\tcl

Letter Rip

Thanks Jeff...

Jerry

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Slawomir Nowaczyk
On Thu, 01 Jun 2006 15:12:23 -0700
[EMAIL PROTECTED] wrote:

#> I believe that 'is' tests equality of reference, such that
#> 
#> >>> a = range(1,3)
#> >>> b = range(1,3)
#> >>> a is b
#> False
#> 
#> The 'is' operator tells you whether a and b refer to the same object.
#> What I've been discussing is whether == should test for "structural"
#> equality so that a and b remain equivalent under parallel mutations
#> (and also under single mutations to common references)

What does "parallel mutations" mean? In particular, what should be the
results of each of the following three comparisons:

x, y, z = [1],[1],[1]
a, b = [x,y], [y,z]
c, d = [[1],[1]], [[1],[1]]
a == b
c == d
a[0].remove(1)
b[0].remove(1)
a == b

So, do I understand correctly that you would like first comparison
(a==b) to return "False" and second comparison (c==d) to return
"True"?

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

Living on Earth may be expensive, but it includes
an annual free trip around the Sun.

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


Re: grouping a flat list of number by range

2006-06-01 Thread Paddy
[EMAIL PROTECTED] wrote:
> hello,
>
> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
>
> [3, 6, 7, 8, 12, 13, 15]
>
> =>
>
> [[3, 4], [6,9], [12, 14], [15, 16]]
>
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)
>
> i was able to to it without generators/yield but i think it could be
> better with them, may be do you an idea?
>
> best regards,
>
> J.

I did a proceedural version, then re-read your post and did a generator
based version ;-)

=== interv1 ===
>>> inlist = [3, 6, 7, 8, 12, 13, 15]
>>> tmp = []
>>> for i,val in enumerate(inlist):
... if i==0:
... tmp.append(val)
... elif val != valinc:
... tmp += [valinc, val]
... valinc = val+1
...
>>> tmp.append(valinc)
>>> tmp
[3, 4, 6, 9, 12, 14, 15, 16]
>>> tmp[0::2]
[3, 6, 12, 15]
>>> tmp[1::2]
[4, 9, 14, 16]
>>> zip(tmp[0::2], tmp[1::2])
[(3, 4), (6, 9), (12, 14), (15, 16)]
>>>

=== END interv1 ===

=== interv2 ===
>>> def interv2(inlist):
... for i,val in enumerate(inlist):
... if i==0:
... tmp = val
... elif val != valinc:
... yield [tmp, valinc]
... tmp = val
... valinc = val+1
... yield [tmp, valinc]
...
>>> list(interv2(inlist))
[[3, 4], [6, 9], [12, 14], [15, 16]]

=== END interv2 ===

- Paddy.

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


Re: argmax

2006-06-01 Thread Ben Cartwright
David Isaac wrote:
> 2. Is this a good argmax (as long as I know the iterable is finite)?
> def argmax(iterable): return max(izip( iterable, count() ))[1]

Other than the subtle difference that Peter Otten pointed out, that's a
good method.

However if the iterable is a list, it's cleaner (and more efficient) to
use seq.index(max(seq)).  That way you won't be creating and comparing
all those tuples.

  def argmax(it):
  try:
  it.index
  except AttributeError:
  it = list(it)
  # Or if it would too expensive to convert it to list:
  #return -max((v, -i) for i, v in enumerate(it))[1]
  return it.index(max(it))

--Ben

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


Re: Tkinter - changing existing Dialog?

2006-06-01 Thread John McMonagle
On Thu, 2006-06-01 at 08:31 -0400, Michael Yanowitz wrote:
> Hello:
> 
> 
>I have a Tkinter GUI Dialog with many buttons and labels and text
> widgets.
> What I would like to do is, can I:
> 
> 1) Disable/deactivate/hide a button, text widget that is already drawn (and
>of course the opposite enable/activate/show it)?
> 
> 2) Change the text of a label or button that is already drawn?
> 
>   based on actions taken by the user. Can it be done without destroying
> the present dialog or the objects in it and creating a new one?
> 
>   Sorry for what probably is such a trivial and basic question. I just can't
> find the answer or know what the technical term for what I want to do is to
> search for it myself.

To disable/deactivate a button widget, use the keyword 'state'.  For
example, 


import Tkinter as Tk
root = Tk.Tk()
bid = Tk.Button(root, text='test', state=Tk.NORMAL)
bid.pack()
bid.configure(state=Tk.DISABLED)

If you want to hide the button (using Pack geometry manager):

bid.pack_forget()

You can pack it again using bid.pack() but it may be difficult to pack
it back where you originally intended.

If you are using the Grid geometry manager:

bid.grid_forget()

To put it back simply call grid again with the same row, column.



Changing the text of a label or button already drawn is simply done by a
call to the configure method on the button or label's text attribute:

bid.configure(text='Help')

Regards,

John







-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

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


Re: losing handles of open files

2006-06-01 Thread Ben Finney
Please don't post non-text message bodies to discussion
forums. Message bodies should be plain text.

"Anthra Norell" <[EMAIL PROTECTED]> writes:

> If a piece of code exits with an exception before it closes an open
> file, that file seems to remain locked, which is real pain in the
> butt

You will want to examine the 'finally' clause, which is executed after
the 'try' suite regardless of exceptions.

http://docs.python.org/ref/exceptions.html>
http://docs.python.org/ref/try.html#try>

You may also be interested in the 'with' statement, coming in Python
2.5, which will be a more natural way of expressing this idiom.

http://docs.python.org/dev/whatsnew/section-generators.html>

-- 
 \ "If nature has made any one thing less susceptible than all |
  `\others of exclusive property, it is the action of the thinking |
_o__)   power called an idea"  -- Thomas Jefferson |
Ben Finney

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


Re: TSV to HTML

2006-06-01 Thread Brian

Dennis Lee Bieber wrote:
> On 1 Jun 2006 03:29:35 -0700, "Brian" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> > Thank you for that response.  Your code was very helpful to me.  I
> > think that actually seeing how it should be done in Python was a lot
> > more educational than spending hours with trial and error.
> >
>   It's not the best code around -- I hacked it together pretty much
> line-for-line from an assumption of what the Ruby was doing (I don't do
> Ruby -- too much PERL idiom in it)
>
> > One question (and this is a topic that I still have trouble getting my
> > arms around).  Why is the text in STYLEBLOCK tripple quoted?
> >
>   Triple quotes allow: 1) use of single quotes within the block
> without needing to escape them; 2) allows the string to span multiple
> lines. Plain string quoting must be one logical line to the parser.
>
>   I've practically never seen anyone use a line continuation character
> in Python. And triple quoting looks cleaner than parser concatenation.
>
>   The alternatives would have been:
>
> Line Continuation:
> STYLEBLOCK = '\n\
> \n\
> td {\n\
> border-left:1px solid #00;\n\
> padding-right:4px;\n\
> padding-left:4px;\n\
> white-space: nowrap;}\n\
> .cellTitle {\n\
> border-bottom:1px solid #00;\n\
> background:#e0;\n\
> font-weight: bold;\n\
> text-align: center; }\n\
> .cell0 { background:#3ff1f1;}\n\
> .cell1 { background:#f8f8f8;}\n\
> \n\
> '
>   Note the \n\ as the end of each line; the \n is to keep the
> formatting on the generated HTML (otherwise everything would be one long
> line) and the final \ (which must be the physical end of line)
> signifying "this line is continued". Also note that I used ' rather than
> " to avoid escaping the " on text/css.
>
> Parser Concatenation:
> STYLEBLOCK = (
> '\n'
> "td {\n"
> "border-left:1px solid #00;\n"
> "padding-right:4px;\n"
> "padding-left:4px;\n"
> "white-space: nowrap;}\n"
> ".cellTitle {\n"
> "border-bottom:1px solid #00;\n"
> "background:#e0;\n"
> "font-weight: bold;\n"
> "text-align: center; }\n"
> ".cell0 { background:#3ff1f1;}\n"
> ".cell1 { background:#f8f8f8;}\n"
> "\n"
> )
>
>   Note the use of ( ) where the original had """ """. Also note that
> each line has quotes at start/end (the first has ' to avoid escaping
> text/css). There are no commas separating each line (and the \n is still
> for formatting). Using the ( ) creates an expression, and Python is nice
> enough to let one split expressions inside () or [lists], {dicts}, over
> multiple lines (I used that feature in a few spots to put call arguments
> on multiple lines). Two strings that are next to each other
>
>   "string1" "string2"
>
> are parsed as one string
>
>   "string1string2"
>
>   Using """ (or ''') is the cleanest of those choices, especially if
> you want to do preformatted layout of the text. It works similar to the
> Ruby/PERL construct that basically said: Copy all text up to the next
> occurrence of MARKER_STRING.

Thank you for your explanation, now it makes sense.

Brian

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


Re: Replace one element of a tuple (LONG)

2006-06-01 Thread Captain Dondo
BartlebyScrivener wrote:
>>>I've looked at various search-and-replace snippets but none that address
>>>what I am trying to do
> 
> 
> I think you need to tell more about what you're trying to do. You say
> it's in a database? Is that why you can't just put the whole blob in
> your text editor and do search-and-replace?
> 
> And is that also why you can't turn it into a giant string and do
> giantstring.replace('unwanted','wanted')
> 
> rd
> 

Fair enough.  I am trying to pull records from one database (on 
tooth.seiner.lan) and create a smaller table with only selected elements 
in another database (on localhost aka hermes).

My code so far:

import MySQLdb
import sys, os, os.path, time, string, dialog

masterBackend="tooth.seiner.lan"
toGoBackend="hermes.seiner.lan"

masterDB=MySQLdb.connect(host=masterBackend,user="mythtv",passwd="mythtv",db="mythconverg")

# pull recordings from masterDB

c=masterDB.cursor()
c.execute("""SELECT title, subtitle, starttime FROM recorded""")

# build our dialog checkbox

d = dialog.Dialog(dialog="dialog")
d.add_persistent_args(["--backtitle", "Myth2Go"])

recordings=[]
for listing in c.fetchall():
 recordings.append(
(listing[0]+'|'+listing[2].isoformat(),
listing[1],0))

recordings.sort()

(retcode, itemlist) = d.checklist(text="",
 height=15, width=70, list_height=7,
 choices=recordings,
 title="Which recordings do you want to transfer?")

selectlist=[]
for listing in itemlist:
 print listing
 (rectitle, recdate) = listing.split('|',1)
 c.execute("""SELECT * FROM recorded WHERE title=%s AND
starttime=%s""",(rectitle,recdate))
 selectlist.append(c.fetchone())



The problem is the last line.  I am creating a bunch of tuples that are, 
for my purposes, incorrect.  I would like to create them with 
masterBackend replaced by toGoBackend.

Currently (I corrected a small bug based on another post) after a user 
selects what recordings s/he wants, selectlist contains:

[

(1028L, datetime.datetime(2006, 5, 26, 7, 0), datetime.datetime(2006, 5, 
26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '', 
'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 
'SH044107', 'EP0441070207', datetime.datetime(2006, 5, 26, 7, 31, 1), 
1162899392L, 0.0, 0, datetime.date(2006, 5, 26), 0, 0L, 0),

(1028L, datetime.datetime(2006, 5, 27, 9, 0), datetime.datetime(2006, 5, 
27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children', 
'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 
'EP0441070204', datetime.datetime(2006, 5, 27, 9, 31, 26), 1164783552L, 
0.0, 0, datetime.date(2006, 5, 23), 0, 0L, 0),

(1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, 
30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', 
'Prunella prepares for a sleepover with Marina; D.W. protects a 
snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 
'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0)

]

which is the correct format to insert into the new database.

What I'd like to do is build the correct selectlist in the first place, 
rather than build the wrong one and then rebuild a correct one.

I can't find a replace method that would work on a tuple (not surprising 
since they're immutable) but I also can't find a replace function that 
would replace an element of a tuple and return a new tuple.

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


Re: grouping a flat list of number by range

2006-06-01 Thread Ben Cartwright
[EMAIL PROTECTED] wrote:
> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
>
> [3, 6, 7, 8, 12, 13, 15]
>
> =>
>
> [[3, 4], [6,9], [12, 14], [15, 16]]
>
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)
>
> i was able to to it without generators/yield but i think it could be
> better with them, may be do you an idea?

Sure:

def group_intervals(it):
it = iter(it)
val = it.next()
run = [val, val+1]
for val in it:
if val == run[1]:
run[1] += 1
else:
yield run
run = [val, val+1]
yield run

--Ben

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread michael . f . ellis
I believe that 'is' tests equality of reference, such that

>>> a = range(1,3)
>>> b = range(1,3)
>>> a is b
False

The 'is' operator tells you whether a and b refer to the same object.
What I've been discussing is whether == should test for "structural"
equality so that a and b remain equivalent under parallel mutations
(and also under single mutations to common references)

Cheers,
Mike

Maric Michaud wrote:
> Le Jeudi 01 Juin 2006 18:00, [EMAIL PROTECTED] a écrit :
> > Perhaps the most fundamental notion is mathematics is that the left and
> > right sides of an equation remain identical after any operation applied
> > to both sides.
>
> IMHO, you are not aware that the '=' symbol of mathematics exists in python,
> it's the 'is' assertion.
>
> a is b
> and then, do what you want with a (or b), a is b remains True.
>
> THIS is the meaning of expr1 = expr2, but in computer science, this is not as
> important as it is in pure logic (most languages do not even provide the 'is'
> assertion).
>
> --
> _
>
> Maric Michaud
> _
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097

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


Re: grouping a flat list of number by range

2006-06-01 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>hello,
>
>i'm looking for a way to have a list of number grouped by consecutive
>interval, after a search, for example :
>
>[3, 6, 7, 8, 12, 13, 15]
>
>=>
>
>[[3, 4], [6,9], [12, 14], [15, 16]]
>
>(6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
>[6:9], and so on)
>
>i was able to to it without generators/yield but i think it could be
>better with them, may be do you an idea?

There are probably better ways, but this works

>
>best regards,
>
>J.

class IterInterval(object):
"""Create an iterator which, given a list of integers,
for each run of consecutive integers i...j, yields a two
element list [i, j + 1]

Singleton lists [i] return [i, i + 1]
Empty lists return None
"""
def __init__(self, seq):
self.seq = seq
self.firstval = None
self.index = 0

def __iter__(self):
# firstval = the start of a run of consecutive integers
# lastval = the last value found in the run
# nextval = the most recent value taken from the input list
if not self.firstval:
# set up the first iteration
if self.index >= len(self.seq):
# empty list, return
raise StopIteration
self.firstval = lastval = int(self.seq[self.index])
self.index += 1
while True:
if self.index >= len(self.seq):
# list exhausted, output the last value read
yield [self.firstval, lastval + 1]
raise StopIteration
nextval = int(self.seq[self.index])
self.index += 1
if nextval == lastval + 1:
lastval = nextval
continue
else:
# end of run - output the run, reset for next call
yield [self.firstval, lastval + 1]
self.firstval = lastval = nextval
continue

if __name__ == '__main__':
for l in [[3, 6, 7, 8, 12, 13, 15], [2], []]:
print l, "=>", [lst for lst in  IterInterval(l)]

/usr/home/jes% python interval.py 
[3, 6, 7, 8, 12, 13, 15] => [[3, 4], [6, 9], [12, 14], [15, 16]]
[3] => [[3, 4]]
[] => []



-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Slawomir Nowaczyk
On Thu, 01 Jun 2006 13:40:34 -0700
[EMAIL PROTECTED] wrote:

#> Scott David Daniels wrote:
#> > Would you say that envelope containing five $100 bills is equal to
#> > an envelope containing five $100 bills with different serial numbers?

#> Yes (unless I was testing the assertion that the second envelope did
#> not contain counterfeits of the first)

So, what if Bank of America later decided that bills with serial
numbers containing "7" are no longer valid?

In other word, *if* you assume equality must be preserved by future
modifications, than no two different (modifiable) objects can ever be
really equal.

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

I believe that math illiteracy affects 7 out of every 5 people.

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


Re: urllib2 and HTTP 302

2006-06-01 Thread John J. Lee
Laszlo Nagy <[EMAIL PROTECTED]> writes:
[...]
> how can I return the redirection URL?
> I tried to get this information from the exception but I could not. Is 
> it possible to read it from the openerdirector?
> Any suggestions?
> 
> 
> try:
>self.post_multipart(
> url,
> [('uploadType','Inventory')],
> [('uploadFileName','inv.txt',fdata)]
> )
> except urllib2.HTTPError, e:
> if e.code == 302:
> return "I would like to get the URL to be redirected 
> to"
> else:
> raise

redirected_url = e.geturl()


John

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


Re: Finding a lost PYTHONPATH with find

2006-06-01 Thread John J. Lee
Edward Elliott <[EMAIL PROTECTED]> writes:

> John J. Lee wrote:
> 
> > find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \;
> > 
> > 
> > The minus in '-100k' (meaning "less than 100k") seems to be
> > undocumented, at least on my system.  
> 
> It should be standard in linux man pages, can't speak for other unices:
> 
>TESTS
>Numeric arguments can be specified as
> 
>+n for greater than n,
> 
>-n for less than n,
> 
>n  for exactly n.
> 
> Maybe you were fooled because it's not directly under the description of
> -size.

Yes, that's right -- thanks.


> > I suppose the -maxdepth is 
> > redundant since I think find searches breadth-first by default.
> 
> ??? maxdepth determines how deep the search will look, not the order the
> search occurs.  Your search only find things within 3 levels of the root,
> unless your directory tree goes no deeper than that (very unlikely) the
> maxdepth can't be redundant.

It can if you hit Control-C as soon as it finds the damn thing :-) --
which is exactly what I would have done, of course.


John

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread michael . f . ellis
Truthfully, I wouldn't mind it at all.  In Python, I frequently write
things like
   i == int(f)
or vice versa just to avoid subtle bugs that sometimes creep in when
later modifications to code change the original assumptions.

When working in C, I always set the compiler for maximum warnings and
do my damndest to make them all go away. In the long run, time spent on
rigorous coding always repays itself with interest in time saved
debugging.

Mike

Erik Max Francis wrote:
> [EMAIL PROTECTED] wrote:
>
> > With all due respect to your well-deserved standing in the Python
> > community, I'm not convinced that equality shouldn't imply invariance
> > under identical operations.
>
> Doo you really want
>
>   2 == 2.0
>
> to be False?
>
> --
> Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
> San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
>Without victory there is no survival.
>-- Winston Churchill

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


Re: Using print instead of file.write(str)

2006-06-01 Thread A.M
Yes, it saved my time big time.

Thank you Bruno.



I use the print >>>file to generate HTML files. print is very flexible and 
nice.



The dictionary formatting that Brunto said is awesome!



Thanks again,

Alan





"Jon Clements" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Didn't know of the >> syntax:  lovely to know about it Bruno - thank
you.

To the OP - I find the print statement useful for something like:
print 'this','is','a','test'
>>> 'this is a test'
(with implicit newline and implicit spacing between parameters)

If you want more control (more flexibility, perhaps?) over the
formatting of the output: be it spacing between parameters or newline
control, use the methods Bruno describes below.

I'm not sure if you can suppress the spacing between elements (would
love to be corrected though); to stop the implicit newline use
something like
print 'testing',
>>> 'testing'
(but - with the leading comma, the newline is suppressed)

I personally find that print is convenient for sentences (or writing
'lines').

Thought it worth pointing this out in case, like some I know, you come
across a cropper with certain output streams.

All the best,

Jon.



Bruno Desthuilliers wrote:
> A.M a écrit :
> > Hi,
> >
> >
> > I found print much more flexible that write method. Can I use print 
> > instead
> > of file.write method?
> >
>
> f = open("/path/to/file")
> print >> f, "this is my %s message" % "first"
> f.close()
>
> To print to stderr:
>
> import sys
> print >> sys.stderr, "oops"
>
> FWIW, you and use string formating anywhere, not only in print statements:
>
> s = "some %s and % formating" % ("nice", "cool")
> print s
>
> You can also use "dict formating":
>
> names = {"other": "A.M.", "me" : "bruno"}
> s = "hello %(other)s, my name is %(me)s" % names


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

Re: Replace one element of a tuple

2006-06-01 Thread BartlebyScrivener
>> I've looked at various search-and-replace snippets but none that address
>> what I am trying to do

I think you need to tell more about what you're trying to do. You say
it's in a database? Is that why you can't just put the whole blob in
your text editor and do search-and-replace?

And is that also why you can't turn it into a giant string and do
giantstring.replace('unwanted','wanted')

rd

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


Re: grouping a flat list of number by range

2006-06-01 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
> 
> [3, 6, 7, 8, 12, 13, 15]
> 
> =>
> 
> [[3, 4], [6,9], [12, 14], [15, 16]]
> 
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)
> 
> i was able to to it without generators/yield but i think it could be
> better with them, may be do you an idea?

Don't hold back your code. Would it work to replace each occurrence of

result_list.append([start, stop]) 

with 

yield [start, stop]

?

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Maric Michaud
Le Jeudi 01 Juin 2006 18:00, [EMAIL PROTECTED] a écrit :
> Perhaps the most fundamental notion is mathematics is that the left and
> right sides of an equation remain identical after any operation applied
> to both sides.

IMHO, you are not aware that the '=' symbol of mathematics exists in python, 
it's the 'is' assertion.

a is b
and then, do what you want with a (or b), a is b remains True.

THIS is the meaning of expr1 = expr2, but in computer science, this is not as 
important as it is in pure logic (most languages do not even provide the 'is' 
assertion).

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using print instead of file.write(str)

2006-06-01 Thread Jon Clements
I meant 'trailing': not leading.

mea culpa.

Jon.

Jon Clements wrote:
> Didn't know of the >> syntax:  lovely to know about it Bruno - thank
> you.
>
> To the OP - I find the print statement useful for something like:
> print 'this','is','a','test'
> >>> 'this is a test'
> (with implicit newline and implicit spacing between parameters)
>
> If you want more control (more flexibility, perhaps?) over the
> formatting of the output: be it spacing between parameters or newline
> control, use the methods Bruno describes below.
>
> I'm not sure if you can suppress the spacing between elements (would
> love to be corrected though); to stop the implicit newline use
> something like
> print 'testing',
> >>> 'testing'
> (but - with the leading comma, the newline is suppressed)
>
> I personally find that print is convenient for sentences (or writing
> 'lines').
>
> Thought it worth pointing this out in case, like some I know, you come
> across a cropper with certain output streams.
>
> All the best,
>
> Jon.
>
>
>
> Bruno Desthuilliers wrote:
> > A.M a écrit :
> > > Hi,
> > >
> > >
> > > I found print much more flexible that write method. Can I use print 
> > > instead
> > > of file.write method?
> > >
> >
> > f = open("/path/to/file")
> > print >> f, "this is my %s message" % "first"
> > f.close()
> >
> > To print to stderr:
> >
> > import sys
> > print >> sys.stderr, "oops"
> >
> > FWIW, you and use string formating anywhere, not only in print statements:
> >
> > s = "some %s and % formating" % ("nice", "cool")
> > print s
> >
> > You can also use "dict formating":
> >
> > names = {"other": "A.M.", "me" : "bruno"}
> > s = "hello %(other)s, my name is %(me)s" % names

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


Re: struct: type registration?

2006-06-01 Thread John Machin
On 2/06/2006 3:44 AM, Giovanni Bajo wrote:
> John Machin wrote:
> 
>>> Looks like you totally misread my message.
>> Not at all.
>>
>> Your function:
>>
>> def mystring_pack(s):
>>  if len(s) > 20:
>>  raise ValueError, "a mystring can be at max 20 chars"
>>  s = (s + "\0"*20)[:20]
>>  s = struct.pack("20s", s)
>>  return s
>>
>> can be even better replaced by (after reading the manual "For packing,
>> the string is truncated or padded with null bytes as appropriate to
>> make it fit.") by:
>>
>> def mystring_pack(s):
>>  if len(s) > 20:
>>  raise ValueError, "a mystring can be at max 20 chars"
>>  return s
>>  # return s = (s + "\0"*20)[:20] # not needed, according to the
>>  manual # s = struct.pack("20s", s)
>>  # As I said, this particular instance of using struct.pack is a
>> big fat no-op.
> 
> John, the point of the example was to show that one could write custom
> packer/unpacker which calls struct.pack/unpack and, after that,
> post-processes the results to obtain some custom data type.

What you appear to be doing is proposing an API for extending struct by 
registering custom type-codes (ASCII alphabetic?) each requiring three 
call-back functions (mypacker, myunpacker, mylength).

Example registration for an "S" string (fixed storage length, true 
length determined on unpacking by first occurrence of '\0' (if any)).

 struct.register("S", packerS, unpackerS, lengthS)

You give no prescription for what those functions should do. You provide 
"examples" which require reverse engineering to deduce of what they are 
intended to be exemplars.

Simple-minded folk like myself might expect that the functions would 
work something like this:

Packing: when struct.pack reaches the custom code in the format, it does 
this (pseudocode):
 obj = _get_next_arg()
 itemstrg = mypacker(obj)
 _append_to_output_string(itemstrg)

Unpacking: when struct.unpack reaches a custom code in the format, it 
does this (pseudocode):
 n = mylength()
 # exception if < n bytes remain
 obj = myunpacker(remaining_bytes[:n])
 _append_to_output_tuple(obj)

Thus, in a simple case like the NUL-terminated string:

def lengthS():
 return 20
def packerS(s):
 assert len(s) <= 20
 return s.ljust(20, '\0')
 # alternatively, return struct.pack("20s", s)
def unpackerS(bytes):
 assert len(bytes) == 20
 i = bytes.find('\0')
 if i >= 0:
 return bytes[:i]
 return bytes

In more complicated cases, it may be useful for either/both the 
packer/unpacker custom functions to call struct.pack/unpack to assist in 
the assembly/disassembly exercise. This should be (1) possible without 
perturbing the state of the outer struct.pack/unpack invocation (2) 
sufficiently obvious to warrant little more than a passing mention.

> Now, I apologize
> if my example wasn't exactly the shortest, most compact, most pythonic piece
> of code. It was not meant to be. It was meant to be very easy to read and
> very clear in what it is being done. You are nitpicking that part of my code
> is a no-op. Fine.

Scarcely a nitpick. It was very clear that parts of it were doing 
absolutely nothing in a rather byzantine & baroque fashion. What was 
unclear was whether this was by accident or design. You say (*after* the 
examples) that "As shown, the custom packer/unpacker can call the 
original pack/unpack as a basis for their work. ... when called 
recursively ...". What basis for what work? As for recursion, I see no 
"19s", "18s", etc here :-)


> Sorry if this confused you.

It didn't. As a self-confessed idiot, I am resolutely and irredeemably 
unconfused.

> I was just trying to show a
> simple pattern:
> 
> custom packer: adjust data, call struct.pack(), return
> custom unpacker: call struct.unpack(), adjust data, return
> 
> I should have chosen a most complex example probably, but I did not want to
> confuse readers. It seems I have confused them by choosing too simple an
> example.

The problem was that you chose an example that had minimal justification 
(i.e. only the length check) for a custom packer at all (struct.pack 
pads the "s" format with NUL bytes) and no use at all for a call to 
struct.unpack inside the custom unpacker.

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


Re: Add file to zip, or replace file in zip

2006-06-01 Thread Chris Lambacher
Skip over the file in question when you first are zipping the directory.
Unfortunately you cannot replace or remove a file from a zip without unzipping
and rezipping all the contents.

-Chris

On Wed, May 31, 2006 at 03:10:53PM +0800, majj81 wrote:
>hi:
>  Good afternoon.
>  Has this problem solved in the URL
>[1]http://mail.python.org/pipermail/python-list/2006-April/338849.html .
>Now I have the same problem to deal with. If you have any suggestion
>please tell me.
>  Thanks.
>Johnny Ma
>come from China
> 
> 
> 
> 
>?? ?? ?? ?? ??  1/2? ?? ?? ?? ?? ?? ?? ?? ??
>[2]?? ? ?? ?? '? ?? ?? ?? ?? ??  1/2? ?? ?? ??  1/4 1/4 ?? '' ?? Ajax
>1/4 1/4 126 ??D  1/4? ?? ?? ?? ?? ?? ??
> 
> References
> 
>Visible links
>1. http://mail.python.org/pipermail/python-list/2006-April/338849.html
>2. http://www.126.com/

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

Re: Replace one element of a tuple

2006-06-01 Thread [EMAIL PROTECTED]

Captain Dondo wrote:
> I have an array(?) (sorry, I'm new* to python so I'm probably mangling
> the terminology) that looks like this:
>
> [((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006,
> 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the
> Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects
> a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L,
> 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5,
> 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L,
> 0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0),
> datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues',
> '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default',
> 6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31,
> 30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)]
>
> I want to replace every instance of 'tooth.seiner.lan' with 'localhost'.
>   There may be lots and lots of these entries (they're pulled from my
> mythtv database).
>
> I could brute-force this by rewriting the whole thing and replacing
> every 9th element but there has to be a better way
>
> I've looked at various search-and-replace snippets but none that address
> what I am trying to do
>
> --Yan
>
> *I'm not really new to python, just very very rusty.  Last time I used
> it was about 3 years ago, and I was equally clueless


There's a lot of parenthesis :)  not easy to read, but unless I'm
seeing something odd, you have string literals in a tuple.  So I don't
think your going to find a better way than brute force recreation.

FYI lists are between []  and are mutable
Tuples are between () and are immutable.  If I'm countin paren's right
you have a list that contains a tuple, that contains another tuple with
1 element in it.

so you can recreate the tuples... or convert the whole thing to a list
of lists.

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


Re: Using print instead of file.write(str)

2006-06-01 Thread Jon Clements
Didn't know of the >> syntax:  lovely to know about it Bruno - thank
you.

To the OP - I find the print statement useful for something like:
print 'this','is','a','test'
>>> 'this is a test'
(with implicit newline and implicit spacing between parameters)

If you want more control (more flexibility, perhaps?) over the
formatting of the output: be it spacing between parameters or newline
control, use the methods Bruno describes below.

I'm not sure if you can suppress the spacing between elements (would
love to be corrected though); to stop the implicit newline use
something like
print 'testing',
>>> 'testing'
(but - with the leading comma, the newline is suppressed)

I personally find that print is convenient for sentences (or writing
'lines').

Thought it worth pointing this out in case, like some I know, you come
across a cropper with certain output streams.

All the best,

Jon.



Bruno Desthuilliers wrote:
> A.M a écrit :
> > Hi,
> >
> >
> > I found print much more flexible that write method. Can I use print instead
> > of file.write method?
> >
>
> f = open("/path/to/file")
> print >> f, "this is my %s message" % "first"
> f.close()
>
> To print to stderr:
>
> import sys
> print >> sys.stderr, "oops"
>
> FWIW, you and use string formating anywhere, not only in print statements:
>
> s = "some %s and % formating" % ("nice", "cool")
> print s
>
> You can also use "dict formating":
>
> names = {"other": "A.M.", "me" : "bruno"}
> s = "hello %(other)s, my name is %(me)s" % names

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


Re: integer to binary...

2006-06-01 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> does anyone know a module or something to convert numbers like integer
> to binary format ?
>
> for example I want to convert number 7 to 0111 so I can make some
> bitwise operations...
>
> Thanks

Use the gmpy module.

>>> import gmpy
>>> a = 14
>>> b = 7
>>> c = 8

>>> help(gmpy.digits)
Help on built-in function digits:

digits(...)
digits(x[,base]): returns Python string representing x in the
given base (2 to 36, default 10 if omitted or 0); leading '-'
present if x<0, but no leading '+' if x>=0. x must be an mpz,
or else gets coerced into one.

>>> print gmpy.digits(a,2)
1110
>>> print gmpy.digits(b,2)
111
>>> print gmpy.digits(c,2)
1000


>>> help(gmpy.setbit)
Help on built-in function setbit:

setbit(...)
setbit(x,n,v=1): returns a copy of the value of x, with bit n set
to value v; n must be an ordinary Python int, >=0; v, 0 or !=0;
x must be an mpz, or else gets coerced to one.

>>> d = gmpy.setbit(c,1,1)
>>> print gmpy.digits(d,2)
1010



>>> help(gmpy.scan1)
Help on built-in function scan1:

scan1(...)
scan1(x, n=0): returns the bit-index of the first 1-bit of x (that
is at least n); n must be an ordinary Python int, >=0.  If no more
1-bits are in x at or above bit-index n (which can only happen for
x>=0, notionally extended with infinite 0-bits), None is returned.
x must be an mpz, or else gets coerced to one.

>>> help(gmpy.scan0)
Help on built-in function scan0:

scan0(...)
scan0(x, n=0): returns the bit-index of the first 0-bit of x (that
is at least n); n must be an ordinary Python int, >=0.  If no more
0-bits are in x at or above bit-index n (which can only happen for
x<0, notionally extended with infinite 1-bits), None is returned.
x must be an mpz, or else gets coerced to one.

>>> print gmpy.scan1(a)
1
>>> print gmpy.scan1(b)
0
>>> print gmpy.scan1(c)
3
>>> print gmpy.scan1(d)
1
>>> print gmpy.scan0(a)
0
>>> print gmpy.scan0(b)
3
>>> print gmpy.scan0(c)
0
>>> print gmpy.scan0(d)
0

>>> help(gmpy.popcount)
Help on built-in function popcount:

popcount(...)
popcount(x): returns the number of 1-bits set in x; note that
this is 'infinite' if x<0, and in that case, -1 is returned.
x must be an mpz, or else gets coerced to one.

>>> print gmpy.popcount(a)
3
>>> print gmpy.popcount(b)
3
>>> print gmpy.popcount(c)
1
>>> print gmpy.popcount(d)
2


>>> help(gmpy.hamdist)
Help on built-in function hamdist:

hamdist(...)
hamdist(x,y): returns the Hamming distance (number of bit-positions
where the bits differ) between x and y.  x and y must be mpz, or
else
get coerced to mpz.

>>> print gmpy.hamdist(a,b)
2
>>> print gmpy.hamdist(a,c)
2
>>> print gmpy.hamdist(a,d)
1
>>> print gmpy.hamdist(b,c)
4
>>> print gmpy.hamdist(b,d)
3
>>> print gmpy.hamdist(c,d)
1

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


grouping a flat list of number by range

2006-06-01 Thread joh12005
hello,

i'm looking for a way to have a list of number grouped by consecutive
interval, after a search, for example :

[3, 6, 7, 8, 12, 13, 15]

=>

[[3, 4], [6,9], [12, 14], [15, 16]]

(6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
[6:9], and so on)

i was able to to it without generators/yield but i think it could be
better with them, may be do you an idea?

best regards,

J.

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


Re: WinPops

2006-06-01 Thread Peter Gsellmann
Roger Upole wrote:

> 
> "Hari Sekhon" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> Hi,
>>   Is there a way of sending winpops (Windows Pop-Up / Net Send messages)
>>   in python?
>>
>> Perhaps some library or something that I can use under both Windows and
>> Linux?
>>
>> Hari
> 
> On Windows, you can use win32net.NetMessageBufferSend.
> 
> Roger
> 
On Linux, i use the smbclient binary:
  from subprocess import *
  q=Popen(['smbclient','-M','maggy'],stdin=PIPE)
  q.stdin.write('hello!')
  q.stdin.close()
  q.wait()

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


Replace one element of a tuple

2006-06-01 Thread Captain Dondo
I have an array(?) (sorry, I'm new* to python so I'm probably mangling 
the terminology) that looks like this:

[((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 
5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the 
Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects 
a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 
'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 
30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 
0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0), 
datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues', 
'', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 
6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31, 
30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)]

I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. 
  There may be lots and lots of these entries (they're pulled from my 
mythtv database).

I could brute-force this by rewriting the whole thing and replacing 
every 9th element but there has to be a better way

I've looked at various search-and-replace snippets but none that address 
what I am trying to do

--Yan

*I'm not really new to python, just very very rusty.  Last time I used 
it was about 3 years ago, and I was equally clueless
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread A.M

"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> A.M wrote:
>
>> This is my 1st day that I am seriously diving into Python and I have to 
>> finish this application by the end of today. Maybe it wasn't a good idea 
>> to choose the language that I don't know when I have to deliver my work 
>> in such short time.
>
> are your boss aware of this ?
>
> 
>


> are your boss aware of this ?

In fact my boss is quite impressed with my progress so far.



I am a little confused about the fact that you got frustrated with my posts 
today. I am not asking for a big tutorial or

deepest philosophy behind the concepts. The answer to this post could be 
just the word "Dictionary" which is 10 key stroke !

Does this hurt?






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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> With all due respect to your well-deserved standing in the Python
> community, I'm not convinced that equality shouldn't imply invariance
> under identical operations.

Doo you really want

2 == 2.0

to be False?

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Without victory there is no survival.
   -- Winston Churchill
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: select multiple entries in Listbox widget?

2006-06-01 Thread Bernard Lebel
Oh, thanks a lot Rob.


Bernard



On 6/1/06, Rob Williscroft <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python-
> [EMAIL PROTECTED] in comp.lang.python:
>
> > Hello,
> >
> > Is there an option or a way to allow the selection of multiple entries
> > in the Listbox widget? I could not find any, and would like to allow
> > the end user to select multiple entries.
> >
> >
>
> When configuring use:
>
>   selectmode = "multiple"
>
> e.g.:
>
> import Tkinter as tk
>
> root = tk.Tk()
>
> a = tk.Listbox( root, selectmode = "multiple" )
> for i in range(10):
>   a.insert( i, str(i) + " item" )
>
> a.pack()
> root.mainloop()
>
> I found the answer here:
>
> http://www.python.org/doc/life-preserver/ClassListbox.html
>
> Though I had to guess the `= "multiple"` part.
>
> Rob.
> --
> http://www.victim-prime.dsl.pipex.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An oddity in list comparison and element assignment

2006-06-01 Thread michael . f . ellis
Yes (unless I was testing the assertion that the second envelope did
not contain counterfeits of the first)

Scott David Daniels wrote:
> Would you say that envelope containing five $100 bills is equal to
> an envelope containing five $100 bills with different serial numbers?

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


Re: how to print newline in xml?

2006-06-01 Thread [EMAIL PROTECTED]
I use Python/XML packages are xml.dom.minidom and xml.dom.ext (second
just for PrettyPrint)

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


if not CGI:

2006-06-01 Thread Max
I've never done anything on the web. I mean, never developed anything. 
(I've got accounts on dA and wikipedia and half-a-dozen other things; I 
know HTML and enough JavaScript to hack away at it when friends need help).

Mostly because I've never had anything worth doing: I've written a set 
of python CGI programs (an eCards site) and set up apache, just because 
I wanted to learn how. It used raw files; no database. And it sits 
there, working just about flawlessly, at http://localhost/maxecards/. 
I've even done a minor security audit, just to learn how (I met a hacker 
and he impressed me).

But now I'm ready to do it in the real world. Nothing complicated, but a 
real project. And I have to choose my tools. Zope, Plone, Django, what 
are these? I don't have to stick with Python, although it's my preferred 
language. I know Python, Java and C++. But I'm ready to learn Ruby if 
RoR is as good as they say.

I could do it in Python cgi (or mod_python). But it seems from all the 
hype that this is not a good way to write scaleable, extensible web 
applications.

There's a reason I'm asking here: I like Python. But I only learned it 
because I had incentive (3 local monetary units in the computer 
olympiad; I won 1). Is RoR incentive enough?

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


Re: An oddity in list comparison and element assignment

2006-06-01 Thread michael . f . ellis
Considering the number of new programmers who get bit by automatic
coercion, I wish Dennis Ritchie had made some different choices when he
designed C.  But then I doubt he ever dreamed it would become so wildly
successful.

Being a curmudgeon purist I'd actually prefer it if Python raised a
TypeError on float vs integer comparisons.

Cheers,
Mike

Kent Johnson wrote:
> [EMAIL PROTECTED] wrote:
> > Hi Alex,
> > With all due respect to your well-deserved standing in the Python
> > community, I'm not convinced that equality shouldn't imply invariance
> > under identical operations.
> >
> > Perhaps the most fundamental notion is mathematics is that the left and
> > right sides of an equation remain identical after any operation applied
> > to both sides.  Our experience of the physical world is similar.  If I
> > make identical modifications to the engines of two identical
> > automobiles, I expect the difference in performance to be identical.
> > If my expectation is met, I would assert that either the two vehicles
> > were not identical to begin with or that my modifications were not
> > performed identically.
>
> But programming is not mathematics and assignment is not an equation.
> How about this:
>
> In [1]: a=3.0
>
> In [2]: b=3
>
> In [3]: a==b
> Out[3]: True
> 
> In [4]: a/2 == b/2
> Out[4]: False
> 
> Kent

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


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-01 Thread A.M


"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> A.M wrote:
>
>> This is my 1st day that I am seriously diving into Python and I have to 
>> finish this application by the end of today. Maybe it wasn't a good idea 
>> to choose the language that I don't know when I have to deliver my work 
>> in such short time.
>
> are your boss aware of this ?
>
> 
>


> are your boss aware of this ?

What is wrong with *this*?
Yes, they are aware of *this*.
The application is not mission critical system. It is just a simple 
reporting tool. 


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


Re: Best Python Editor

2006-06-01 Thread Jarek Zgoda
Fredrik Lundh napisał(a):

>>Can anyone tell me a good python editor/IDE?
> 
> vim!

jEdit!

>>It would be great if you can provide the download link also.
> 
> google it!

google it!

:D(I love these Vim <-> Emacs disputes)

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using print instead of file.write(str)

2006-06-01 Thread Bruno Desthuilliers
A.M a écrit :
> Hi,
> 
> 
> I found print much more flexible that write method. Can I use print instead 
> of file.write method?
> 

f = open("/path/to/file")
print >> f, "this is my %s message" % "first"
f.close()

To print to stderr:

import sys
print >> sys.stderr, "oops"

FWIW, you and use string formating anywhere, not only in print statements:

s = "some %s and % formating" % ("nice", "cool")
print s

You can also use "dict formating":

names = {"other": "A.M.", "me" : "bruno"}
s = "hello %(other)s, my name is %(me)s" % names
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to format datetime values

2006-06-01 Thread A.M

"BartlebyScrivener" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Are you trying to get banned, or what?
>
> It's the equivalent of me asking you:
>
> Hey, does Ruby have anything like dictionaries and will you teach me
> about strings?  Oh, and what's an object?
>
> Go read the bleeping tutorial.
>
> rd
>

Well, I did investigate all tutorial and google and I wasn't able to find 
any built-in way for datetime formatting in Python. In fact I cannot find 
any way to format a long integer into 99,999, format. I know how to 
format strings with C printf like formatter, but I am sure what I am trying 
to do can't be done with C printf formatting.



I also found that mx.DateTime perfectly does date formatting and much more, 
but I don't want to add another step to the deployment process.



>> It's the equivalent of me asking you:
>> and will you teach me about strings?  Oh, and what's an object?



The answer to this post could be just a function name. I don't think I asked 
about broad concepts such as the object or strings. What I am asking here is 
just a clue.


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


  1   2   3   >