Re: Creating single .exe file without py2exe and pyinstaller

2008-10-18 Thread Tino Wildenhain

Hi,

Abah Joseph wrote:
I have written a small application of about 40-45 lines which is about 
4KB, so I want to create a single .exe file from it, using py2exe it 
created unnecessary files, that just increase the size of the program 
and also less portable to me. What else can I use?


the "unneccessary files" you say, are what your 40-45 lines bring to
life.

1) just distribute the 40-45 lines - but this requires python
   installation on users end

2) use a python to C(++) compiler and compile the result to .exe,
   works pretty well for simple applications:

   http://shed-skin.blogspot.com/

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


keyword in package name.

2008-10-18 Thread Abhishek Mishra
Hello Everyone,

I have the habit of using domain names (of either the application or
company) in reverse in package names.

for e.g. com.spam.app1

I've recently started a project for an indian domain (tld = .in),
which leads to a package name like

in.spam.app1

This causes a syntax error, as "in" is a keyword.
I understand that this is an unfortunate "feature", but has anyone
faced this problem before,
and is there a possible workaround.

P.S. this would also be a problem for the iceland domains (tld = .is).
TLDs: http://data.iana.org/TLD/tlds-alpha-by-domain.txt
Python Keywords: http://www.python.org/doc/2.5.2/ref/keywords.html

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


Re: loops

2008-10-18 Thread Paul Rubin
"James Mills" <[EMAIL PROTECTED]> writes:
> > for x in (2**i for i in xrange(10)):
> >print x
> This is by far the most concise solution I've seen so far.

print '\n'.join(str(2**i) for i in xrange(10))
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-18 Thread Steven D'Aprano
On Sun, 19 Oct 2008 02:52:52 +, Aaron Brady wrote:

> Steven D'Aprano wrote:
> 
>> On Sat, 18 Oct 2008 09:17:28 +1300, Lawrence D'Oliveiro wrote:
>>
>>> In message
>>> <[EMAIL PROTECTED]>,
>>> Aaron "Castironpi" Brady wrote:
>>> 
 The purpose of a parameter is something that the caller can supply,
 but doesn't have to.  It is not for internal-use-only items.
>>> 
>>> Exactly!
>>
>> Says who?
>>
>> Using arguments for internal-use-only is a perfectly acceptable example
>> of practicality beating purity.
> 
> That's a stretch.


It's a standard Python idiom used by the standard library.



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


Re: Finding the instance reference of an object

2008-10-18 Thread Steven D'Aprano
On Fri, 17 Oct 2008 15:39:33 -0600, Joe Strout wrote:

> On Oct 17, 2008, at 3:19 PM, Grant Edwards wrote:
> 
>>> And my real point is that this is exactly the same as in every other
>>> modern language.
>>
>> No, it isn't.  In many other languages (C, Pascal, etc.), a "variable"
>> is commonly thought of as a fixed location in memory into which one can
>> put values.  Those values may be references to objects.
> 
> Right, though not in languages like C and Pascal that don't HAVE the
> notion of objects.  We really ought to stop bringing up those dinosaurs
> and instead compare Python to any modern OOP language.

You really should stop assuming that languages still in use are 
"dinosaurs". There are many, many people whose understanding of such 
terms as "call by value" or "variable" are based on C or Pascal or even 
Fortran.

Besides, while the Pascal language itself doesn't have objects, plenty of 
Pascal implementations do.


>>  In Python, that's not how it works.  There is no
>> "location in memory" that corresponds to a variable with a particular
>> name the way there is in C or Pascal or Fortran or many other
>> languages.
> 
> No?  Is there any way to prove that, without delving into the Python
> source itself?

>>> x = 1
>>> id(x)  # a unique identifier, in CPython equal to its address
135536432
>>> x = 2
>>> id(x)
135536420

Notice that the address of x changes. Actually, that's a lie. The name 
'x' doesn't have an address, except in the sense that the string 'x' must 
occur somewhere in memory. But that's an unimportant implementation 
detail. In reality, what we see is:

the object 1 is bound to the name 'x';
we ask for the id() of the object bound to 'x' (1), which is 135536432;
the object 2 is bound to the name 'x';
we ask for the id() of the object bound to 'x' (2), which is 135536420.

That's what is happening at the Python level of code. Anything else is 
just implementation details.



> If not, then I think you're talking about an internal implementation
> detail.

Namespaces aren't an internal implementation detail, they are fundamental 
to how Python works.


>> All that exists in Python is a name->object mapping.
> 
> And what does that name->object mapping consist of?  At some level,
> there has to be a memory location that stores the reference to the
> object, right?

Who cares? That's the *wrong* level. At *some* level, everything is just 
flipping electrons from one state to another, but I think even you would 
object if I claimed that:

"All computer languages are call-by-flipping-electrons, with no 
exceptions."


Somebody could implement a Python interpreter using literal post-it notes 
for names and literal boxes for objects. The fact that our CPUs are 
optimized for flipping bits instead of (say) water flowing through tubes, 
or clockwork, or punching holes in paper tape, is irrelevant. When 
discussing what Python code does, the right level is to discuss the 
Python virtual machine, not the implementation of that VM.

If you want to discuss the deeper levels, it's perfectly acceptable to 
say that the CPython implementation uses memory locations holding 
pointers. But that's not *Python*, that's hidden detail that the Python 
programmer can't reach.



>>> Nothing unusual here at all (except that some of us here seem to want
>>> to make up new terminology for standard behavior, perhaps in order to
>>> make Python seem more exotic).
>>
>> That's because it is fundamentally different from what happens in
>> languages like C.
> 
> What happens in a modern OOP language is just as fundamentally different
> (which is to say, not really very much) from what happens in C or
> FORTRAN or COBOL, too.

Which is why modern OOP languages like Python shouldn't use the same 
terminology invented to describe what Fortran and Pascal do.


> If you make up new terms like "rebinds," 

This is not something that is just "made up", it is an actual description 
of what the Python VM does.


> well, I guess at least that
> avoids giving the listener the wrong idea.

As opposed to call-by-value, call-by-reference, and "call-by-value-where-
the-value-is-the-reference", all of which do give the listener the wrong 
idea.


> Instead it gives them no
> idea at all, which may be better, but not as good as giving them the
> right idea.

But it is the right idea. They just don't know what it means, because 
they've been listening to people like you who insist on using Pascal 
terminology with a definition unrecognizable to Pascal programmers. To an 
ex-Pascal programmer like myself, when you talk about "call by value 
where the value is a reference", it sounds to me as if you are insisting 
that cars are ACTUALLY horse and buggies, where the horse is the engine, 
why are we inventing new terms like 'automobile', that just confuses 
people.



> It still leaves them to investigate what actually happens,
> and ultimately they will find that the parameters are always passed by
> value in Python.

But they ar

Re: Porting VB apps to Python for Window / Linux use

2008-10-18 Thread Dotan Cohen
2008/10/19 Lawrence D'Oliveiro <[EMAIL PROTECTED]>:
> In message <[EMAIL PROTECTED]>, Dotan
> Cohen wrote:
>
>> I often see mention of SMBs that either want to upgrade their Windows
>> installations, or move to Linux, but cannot because of inhouse VB
>> apps.
>
> Probably best to leave those legacy VB apps alone and develop new
> replacements in a more open, cross-platform language, like Python.

That is quite the reason why I asked here, so that I could find
someone who can port these things to Python.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Air Max Air Max 90 man Air Max 90 women Air Max LTD man Air Max LTD

2008-10-18 Thread 128
( paypal payment )( www.yourbestshoes.cn )Air Jordans Air Jordans 1
Air
Jordans 2 Air Jordans 3 Air Jordans 3.5 Air Jordans 4 Air Jordans 4.5
Air Jordans 5
Air Jordans 6 (paypal payment )( www.yourbestshoes.cn )Air Jordans 7
Air Jordans 8 Air
Jordans 9 Air Jordans 10 Air Jordans 11 Air Jordans 12 Air Jordans 13
Air Jordans 14
Air Jordans 16 ( paypal payment )( www.yourbestshoes.cn )Air Jordans
17 Air Jordans 18
Air Jordans 23 Air Jordans DMP Air Jordans Kids Air Jordans 15.5 Air
Jordans 23 women
Air Jordans 5 ( paypal payment )( www.yourbestshoes.cn )women Air
Jordans 3.5 women Air
Jordans 13 & Air Jordans 23 Air Jordans 13 & Air Jordans 11
( paypal payment )( www.yourbestshoes.cn )Air Force Jordan Fusion
AF&J1
AF&J3 AF&J5 AF&J12 AF&J23 AF&J5 women AF&J23 women AF&J20 AF&J7 AF&J12
women
Air Max Air Max 90 man Air Max 90 women Air Max LTD man Air Max LTD
women Air Max TN ( paypal payment )( www.yourbestshoes.cn )man Air Max
TN women Air Max 87
man Air Max 87 women Air Max 88 man Air Max 89 man Air Max 91 man Air
Max 95 man Air
Max 95 women Air Max 97 man Air Max 97 women Air Max 360 man Air Max
360 women Air
Max 180 man Air ( paypal payment )( www.yourbestshoes.cn )man Air Max
TN women Air Max 87
man Air Max 87 ( paypal payment )( www.yourbestshoes.cn )Max 180 women
Air Max 2003 man
Air Max 2003 women Air Max 95 360 man
DUNK DUNK man DUNK women DUNK High man DUNK High women
( paypal payment )( www.yourbestshoes.cn )Adiadis Adiadis 35th man
Adiadis 35th women Adicolor man Adicolor women football shoe Good Year
man
NIKE NIKE man NIKE women ( paypal payment )( www.yourbestshoes.cn )Air
Force One AF1 25th man AF1
25th women AF1 man AF1 women AF1 High man PUMA PUMA man PUMA women
--
http://mail.python.org/mailman/listinfo/python-list


Re: xor: how come so slow?

2008-10-18 Thread Tim Roberts
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>
>On Fri, 17 Oct 2008 20:51:37 +1300, Lawrence D'Oliveiro wrote:
>
>> Is piece really meant to be random? If so, your create_random_block
>> function isn't achieving much--xoring random data together isn't going
>> to produce anything more exciting than less random data than you started
>> with.
>
>Hmmm... why do you say that xoring random data with other random data 
>produces less randomness than you started with?
>
>I'm not saying that you're wrong, and certainly it is pointless since 
>you're not going to improve on the randomness of /dev/urandom without a 
>lot of work. But less random? 

For those who got a bit lost here, I'd would point out that Knuth[1] has an
excellent chapter on random numbers that includes a detailed discussion of
this effect.  His net takeaway is that most of the things people do to
increase randomness actually have exactly the opposite effect.
-
[1] Knuth, Donald.  The Art of Computer Programming, Volume 2,
Seminumerical Algorithms.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Kay Schluehr
On 18 Okt., 22:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:

> Perhaps it also omitted the fact that nothing prevents you from defining a
> function to write things to stdout (or elsewhere) in Python 2.5, making the
> Python 3.x change largely a non-feature. ;)
>
> Jean-Paul

Even more. If someone had solved the hard problem of finding a less
cumbersome way of writing sys.stdout.write(...) the request for
multiline lambdas ( multi expression lambdas actually ) could have
been decreased about 75-80%.

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


Re: __metaclass__ and deepcopy issue

2008-10-18 Thread Raymond Hettinger
On Oct 17, 1:00 am, Wouter DW <[EMAIL PROTECTED]> wrote:
> I read the article 
> onhttp://www.python.org/download/releases/2.2/descrintro/#metaclasses
> and started using autoprop.
> But now I have a problem I can't seem to solve myself.
>
> class autoprop(type):
>   def __init__(cls, name, bases, dict):
>     super(autoprop, cls).__init__(name, bases, dict)
>     props = {}
>     for name in dict.keys():
>       if name.startswith("_get_") or name.startswith("_set_"):
>         props[name[5:]] = 1
>     for name in props.keys():
>       fget = getattr(cls, "_get_%s" % name, None)
>       fset = getattr(cls, "_set_%s" % name, None)
>       setattr(cls, name, property(fget, fset))
> class InvertedX:
>   __metaclass__ = autoprop
>   def _get_x(self):
>     return -self.__x
>   def _set_x(self, x):
>     self.__x = -x
>
> a = InvertedX()
> from copy import deepcopy
> b = deepcopy(a)
>
> The deepcopy gives an error inside copy.py of the python lib.

Hmm, your code works just fine for me in Py2.6.
If I add "a.x = 10" before the deepcopy and
"print b.x" after the deepcopy, it also shows
the desired result.


>
> TypeError: descriptor '__reduce__' of 'object' object needs an
> argument
>
> Does anybody know how to solve this issue?

Usually, when you get errors of this kind with copy, deepcopy, or
pickle, it means that the copier can't figure out how to extract
the relevant components and then re-assemble them into a new instance.

This means that you need to define some combination of __copy__,
__deepcopy__, __reduce__, __getstate__, __setstate__, __getinitargs__,
and/or __getnewargs__.  See the pickle module and copy module for
all the gory details.

One other thought, class decorators can be much easier to use and
understand than an equivalent metaclass:

def autoprop(cls):
for name in cls.__dict__.keys():
if name.startswith("_get_") or name.startswith("_set_"):
name = name[5:]
fget = getattr(cls, "_get_%s" % name, None)
fset = getattr(cls, "_set_%s" % name, None)
setattr(cls, name, property(fget, fset))
return cls

@autoprop
class InvertedX:
  def _get_x(self):
return -self.__x
  def _set_x(self, x):
self.__x = -x

a = InvertedX()
a.x = 10
print a.x
from copy import deepcopy
b = deepcopy(a)
print b.x


Raymond


P.S.  Minor nits in the original code.  When you use a dict like
"props" but care only about the key, not the value, that usually means
that you're better-off with a set() than a dict().  Also, you don't
even need to build-up "props" since the values can be used immediately
(like in my example code).  But the most important part is that
whenever you're using metaclasses for registration, validation, or
simple transformation (as in your example), then a simple class
decorator is often a better choice.  If you don't have Py2.6 yet, then
you can get the same effect by defining the class and *then* writing,
"Inverted = autoprop(Inverted).

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


Re: loops

2008-10-18 Thread John Machin
On Oct 19, 2:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
[snip]
> making your code easy to read and easy to maintain is far more important.
>
> for x in (2**i for i in xrange(10)):
>     print x
>
> will also print 1, 2, 4, 8, ... up to 1000.

I would say up to 512; perhaps your understanding of "up to" differs
from mine.

Easy to read? I'd suggest this:

for i in xrange(10):
print 2 ** i

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


Re: loops

2008-10-18 Thread James Mills
On Sun, Oct 19, 2008 at 1:44 PM, James Mills
<[EMAIL PROTECTED]> wrote:
> On Sun, Oct 19, 2008 at 1:30 PM, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
>> for x in (2**i for i in xrange(10)):
>>print x
>
> This is by far the most concise solution I've seen so far.
> And it should never be about conserving code.
> Also, Python IS NOT C (to be more specific: Python
> is not a C-class language).

Also, if the OP is finding himself writing such manual
and mundane looking loops, he/she should reconsider
what it is he/she is doing. You would normally want
to iterate (vs. loop) over a sequence of items.

--JamesMills

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Creating single .exe file without py2exe and pyinstaller

2008-10-18 Thread Abah Joseph
I have written a small application of about 40-45 lines which is about 4KB,
so I want to create a single .exe file from it, using py2exe it created
unnecessary files, that just increase the size of the program and also less
portable to me. What else can I use?
I am on windows XP.
Python 2.5
--
http://mail.python.org/mailman/listinfo/python-list


Re: heapreplace, methodcaller

2008-10-18 Thread Raymond Hettinger
On Oct 18, 7:01 am, [EMAIL PROTECTED] wrote:
> To improve name coherence I think this method of the heapq module:
> heapq.heapreplace(heap, item)
>
> can grow an alias in Python 2.6.1/2.7 and 3.0/3.1:
> heapq.heappoppush(heap, item)
>
> So later the heapreplace() name can be deprecated.

Too late for 2.6 and possibly too late and too disruptive for 3.0
(which needs to minimize transitions from 2.6).


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


Re: loops

2008-10-18 Thread James Mills
On Sun, Oct 19, 2008 at 1:30 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> for x in (2**i for i in xrange(10)):
>print x

This is by far the most concise solution I've seen so far.
And it should never be about conserving code.
Also, Python IS NOT C (to be more specific: Python
is not a C-class language).

--JamesMills

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: xor: how come so slow?

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Steven D'Aprano
wrote:

> On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote:
> 
>> Data can come in fractional bits. That's how compression works.
> 
> If you don't believe me, try compressing a single bit and see if you get
> a "fractional bit".

If both states of the bit are not equally likely, then you do indeed have a
fractional bit, since

nrbits = (- logbase2(P[bit = 0]) - logbase2(P[bit = 1])) / 2
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-18 Thread Steven D'Aprano
On Sat, 18 Oct 2008 03:52:51 -0700, Gandalf wrote:

> I was hopping to describe it with only one command. most of the
> languages I know use this.
> It seems weird to me their is no such thing in python. it's not that I
> can't fined a solution it's all about saving code

It shouldn't be about saving code. There's no shortage of code so that we 
have to conserve it. But there is a shortage of time and effort, so 
making your code easy to read and easy to maintain is far more important.

for x in (2**i for i in xrange(10)):
print x

will also print 1, 2, 4, 8, ... up to 1000.



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


Re: loops

2008-10-18 Thread Terry Reedy

MRAB wrote:

On Oct 18, 7:31 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:



Python provide while loops for more fine-grain control, and a protocol
so *reuseable* iterators can plug into for loops. Duncan showed you
both.  If you *need* a doubling loop variable once, you probably need
one more than once, and the cost of the doubling generator is amortized
over all such uses.  Any Python proprammer should definitely know how to
write such a thing without hardly thinking.  We can squeeze a line out
of this particular example:

def doubling(value, limit):
   while value <= limit:
 yield value
 value += value


Shouldn't the upper limit be exclusive in order to be Pythonic?


Yes, and perhaps I could have mentioned that, but the OP wanted a port 
of the C construct.


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


Re: memory use with regard to large pickle files

2008-10-18 Thread Aaron Brady
Catherine Moroney wrote:

> I'm writing a python program that reads in a very large
> "pickled" file (consisting of one large dictionary and one
> small one), and parses the results out to several binary and hdf
> files.
>
> The program works fine, but the memory load is huge.  The size of
> the pickle file on disk is about 900 Meg so I would theoretically
> expect my program to consume about twice that (the dictionary
> contained in the pickle file plus its repackaging into other formats),
> but instead my program needs almost 5 Gig of memory to run.
> Am I being unrealistic in my memory expectations?
>
> I'm running Python 2.5 on a Linux box (Fedora release 7).
>
> Is there a way to see how much memory is being consumed
> by a single data structure or variable?  How can I go about
> debugging this problem?
>
> Catherine

There's always the 'shelve' module.


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


Re: xor: how come so slow?

2008-10-18 Thread Steven D'Aprano
On Sat, 18 Oct 2008 09:16:11 +1300, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Sion Arrowsmith
> wrote:
> 
>> Maybe it should be "fewer random data".
> 
> Except these days we tend to think of "data" being, say, more like
> "flour" than "bees", so it's "less data", like "less flour", rather than
> like "fewer bees". :)
> 
>> After all, each byte in the block is discrete.
> 
> Data can come in fractional bits. That's how compression works.

Compression works by removing redundant data so the same amount of useful 
information requires fewer bits. If you don't believe me, try compressing 
a single bit and see if you get a "fractional bit". I leave it to you to 
choose whether the bit should be on or off.

That's why compressing data twice doesn't gain much, if anything. Try 
compressing a typical JPEG image, chances are it won't get any smaller. 
That's because JPEGs already remove the redundancy in the data, 
compressing it. With no redundancy, there can be no compression.

Due to the pigeon-hole principle, any reversible compression scheme must 
cause some data to be expanded rather than compressed. (If not, then 
there must be two different pieces of data that compress to the same 
thing, which means the scheme is not reversible.) If there were 
fractional bits, that wouldn't apply, because you can always divide a 
pigeon-hole (a bit) into two smaller pigeon-holes.



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


Re: Help with Iteration

2008-10-18 Thread Aaron Brady
Chris McComas wrote:

> On Oct 18, 3:46 pm, Aaron Brady <[EMAIL PROTECTED]> wrote:
>> Chris McComas wrote:
>> > actually i'm running it online, with a mysql db. so in the db there is
>> > a table CollegeYear with the following fields:
>>
>> > name
>> > rating
>> > change
>> > wp
>>
>> > then another table Games
>>
>> > date
>> > year
>> > team_1
>> > team_1_score
>> > team_2
>> > team_2_score
>>
>> > it goes through and calculates everything, then when it's time to
>> > compute the rating i have say this code:
>>
>> >http://dpaste.com/85300/
>>
>> > it goes through and computes them, then add the new rating and
>> > absolute value of the changed rating to the db. what i need now is a
>> > way to get the largest entry for 'change' and if it is greater than
>> > 0.5 then do this code again. if it is less than 0.5 then we're
>> > done.
>>
>> What about "SELECT MAX( rating ) FROM CollegeYear"?
>
> Aaron,
>
> Thnx. To clarify I can get the max, that wasn't the issue, what I'm
> failing to try and visualise/figure out is how do I say, okay if MAX >
> 0.5 run this again, if MAX < 0.5 you're done.

I don't know.

while 1:
calculate_stuff( )
if stuff < 0.5:
break



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


Re: Kicking off a python script using Windows Scheduled Task

2008-10-18 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
korean_dave wrote:

> Does anyone know how to properly kick off a script using Windows
> Scheduled Task? The script calls other python modules within itself.
> HERE'S THE CATCH:
> I am used to running the script directly from the command window and
> the print() is very handy for us to debug and monitor. When running
> the task from Windows Scheduled Task, we'd like to be able to view the
> command window and keep it up after the Task has completed...

Why not redirect stdout and stderr to a log file, and tail that?

Another option might be screen .
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-18 Thread Aaron Brady
Steven D'Aprano wrote:

> On Sat, 18 Oct 2008 09:17:28 +1300, Lawrence D'Oliveiro wrote:
>
>> In message
>> <[EMAIL PROTECTED]>,
>> Aaron "Castironpi" Brady wrote:
>> 
>>> The purpose of a parameter is something that the caller can supply, but
>>> doesn't have to.  It is not for internal-use-only items.
>> 
>> Exactly!
>
> Says who?
>
> Using arguments for internal-use-only is a perfectly acceptable example 
> of practicality beating purity.

That's a stretch.


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


Re: memory use with regard to large pickle files

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Catherine Moroney wrote:

> I'm writing a python program that reads in a very large
> "pickled" file (consisting of one large dictionary and one
> small one), and parses the results out to several binary and hdf
> files.

Job for a database?
--
http://mail.python.org/mailman/listinfo/python-list


Re: IO error

2008-10-18 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Rajan
Arora wrote:

> On Oct 18, 5:52 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
> central.gen.new_zealand> wrote:
>> In message
>> <[EMAIL PROTECTED]>,
>> Rajan
>>
>> Arora wrote:
>> > I am trying to get the data out of an instrument through its GPIB
>> > port...
>>
>> > When i try read() command it gives me an IO timeout error.
>>
>> What's the device name, device driver module name, do you have any sample
>> or diagnostic code you can run to prove that your PC is communicating
>> properly with the device?
> 
> I am trying to automate an HP 4156. I am getting some of the data that
> i need, but when i specify the whole data set i want it to read, it
> takes some time and gives a IO Timeout error.
> Will making IO timeout=0 help?

What's the device name as far as the OS is concerned that you are specifying
to open the device, device driver module name, do you have any sample or
diagnostic code you can run to prove that your PC is communicating properly
with the device?

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


Re: default value in __init__

2008-10-18 Thread Steven D'Aprano
On Sat, 18 Oct 2008 09:17:28 +1300, Lawrence D'Oliveiro wrote:

> In message
> <[EMAIL PROTECTED]>,
> Aaron "Castironpi" Brady wrote:
> 
>> The purpose of a parameter is something that the caller can supply, but
>> doesn't have to.  It is not for internal-use-only items.
> 
> Exactly!

Says who?

Using arguments for internal-use-only is a perfectly acceptable example 
of practicality beating purity.




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


Re: xor: how come so slow?

2008-10-18 Thread Steven D'Aprano
On Fri, 17 Oct 2008 13:59:27 +0100, Sion Arrowsmith wrote:

> [I think these attributions are right] Steven D'Aprano 
> <[EMAIL PROTECTED]> wrote:
>>On Fri, 17 Oct 2008 22:45:19 +1300, Lawrence D'Oliveiro wrote:
>>> In message <[EMAIL PROTECTED]>, Steven
>>> D'Aprano wrote:
 ... why do you say that xoring random data with other random data
 produces less randomness than you started with?
>>> blocksize <= number_of_blocks * blocksize
>>I must be thick, because that looks like a non sequitor to me. I don't
>>see the relevance.
> 
> Lawrence originally said something along the lines of this just being a
> way of taking some random data and producing "less random data". You're
> reading it as "(less random) data". The intent (I assume) is for it to
> be read as "less (random data)".


Ah. That was how I read it.


> Maybe it should be "fewer random data". After all, each byte in the
> block is discrete.


Or "a smaller amount of random data".



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


Re: Help with Iteration

2008-10-18 Thread John Machin
On Oct 19, 11:59 am, Chris McComas <[EMAIL PROTECTED]> wrote:
> On Oct 18, 3:46 pm, Aaron Brady <[EMAIL PROTECTED]> wrote:
>
>
>
> > Chris McComas wrote:
> > > actually i'm running it online, with a mysql db. so in the db there is
> > > a table CollegeYear with the following fields:
>
> > > name
> > > rating
> > > change
> > > wp
>
> > > then another table Games
>
> > > date
> > > year
> > > team_1
> > > team_1_score
> > > team_2
> > > team_2_score
>
> > > it goes through and calculates everything, then when it's time to
> > > compute the rating i have say this code:
>
> > >http://dpaste.com/85300/

What is the point of this:

if games.team_1_score > games.team_2_score
t1_rating = t2_rating + t1_wp - .5
t2_rating = t1_rating + t2_wp - .5
elif games.team_1_score < games.team_2_score
t1_rating = t2_rating + t1_wp - .5
t2_rating = t1_rating + t2_wp - .5
elif games.team_1_score == games.team_2_score
t1_rating = t2_rating + t1_wp - .5
t2_rating = t1_rating + t2_wp - .5

You have the same code for each of the three conditions. Where are the
colons? Have you actually tried to execute this code? Any good reason
why the second elif is not an else?


>
> > > it goes through and computes them, then add the new rating and
> > > absolute value of the changed rating to the db. what i need now is a
> > > way to get the largest entry for 'change' and if it is greater than
> > > 0.5 then do this code again. if it is less than 0.5 then we're
> > > done.
>
> > What about "SELECT MAX( rating ) FROM CollegeYear"?
>
> Aaron,
>
> Thnx. To clarify I can get the max, that wasn't the issue, what I'm
> failing to try and visualise/figure out is how do I say, okay if MAX >
> 0.5 run this again, if MAX < 0.5 you're done.

[Aside: if MAX == 0.5, what? Go into a catatonic trance?]

Let me get this straight: Is this your first program? Are you asking
how to code a while loop?
--
http://mail.python.org/mailman/listinfo/python-list


Re: IO error

2008-10-18 Thread Rajan Arora
On Oct 18, 5:52 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, Rajan
>
> Arora wrote:
> > I am trying to get the data out of an instrument through its GPIB port...
>
> > When i try read() command it gives me an IO timeout error.
>
> What's the device name, device driver module name, do you have any sample or
> diagnostic code you can run to prove that your PC is communicating properly
> with the device?

Hi..
I am trying to automate an HP 4156. I am getting some of the data that
i need, but when i specify the whole data set i want it to read, it
takes some time and gives a IO Timeout error.
Will making IO timeout=0 help?

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


Re: Help with Iteration

2008-10-18 Thread Chris McComas
On Oct 18, 3:46 pm, Aaron Brady <[EMAIL PROTECTED]> wrote:
> Chris McComas wrote:
> > actually i'm running it online, with a mysql db. so in the db there is
> > a table CollegeYear with the following fields:
>
> > name
> > rating
> > change
> > wp
>
> > then another table Games
>
> > date
> > year
> > team_1
> > team_1_score
> > team_2
> > team_2_score
>
> > it goes through and calculates everything, then when it's time to
> > compute the rating i have say this code:
>
> >http://dpaste.com/85300/
>
> > it goes through and computes them, then add the new rating and
> > absolute value of the changed rating to the db. what i need now is a
> > way to get the largest entry for 'change' and if it is greater than
> > 0.5 then do this code again. if it is less than 0.5 then we're
> > done.
>
> What about "SELECT MAX( rating ) FROM CollegeYear"?

Aaron,

Thnx. To clarify I can get the max, that wasn't the issue, what I'm
failing to try and visualise/figure out is how do I say, okay if MAX >
0.5 run this again, if MAX < 0.5 you're done.
--
http://mail.python.org/mailman/listinfo/python-list


Re: inserting Unicode character in dictionary - Python

2008-10-18 Thread gitaziabari
On Oct 17, 2:38 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> Thanks for the answers.  That clears things up quite a bit.
>
> >> What if your source file is set to utf-8?  Do you then have a proper
> >> UTF-8 string, but the problem is that none of the standard Python
> >> library methods know how to properly interpret UTF-8?
>
> > Well, the decode method knows how to decode that bytes into a
> > `unicode`
> > object if you call it with 'utf-8' as argument.
>
> OK, good to know.
>
> >> 4. In Python 3.0, this silliness goes away, because all strings are
> >> Unicode by default.
>
> > Yes and no.  The problem just shifts because at some point you get
> > into
> > similar troubles, just in the other direction.  Data enters the
> > program
> > as bytes and must leave it as bytes again, so you have to deal with
> > encodings at those points.
>
> Yes, but that's still much better than having to litter your code with
> 'u' prefixes and .decode calls and so on.  If I'm using a UTF-8-savvy
> text editor (as we all should be doing in the 21st century!), and type
> "foo = '2π'", I should get a string containing a '2' and a pi
> character, and all the text operations (like counting characters,
> etc.) should Just Work.
>
> When I read and write files or sockets or whatever, of course I'll
> have to think about what encoding the text should be... but internal
> to my own source code, I shouldn't have to.
>
> I understand the need for a transition strategy, which is what we have
> in 2.x, and that's working well enough.  But I'll be glad when it's
> over.  :)
>
> Cheers,
> - Joe

Thanks for the answers. The following factors should be considerd when
dealing with unicode characters in python:
1. Declaring # -*- coding: utf-8 -*- at the top of script
2. Opening files with appropriate encoding:
txt = codecs.open (filename, 'w+', encoding='utf-8')

My program works fine now. There is no specific way of adding unicode
characters in list or dictionaies. The character itself has to be in
unicode.

Cheers,

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


Re: better scheduler with correct sleep times

2008-10-18 Thread James Mills
On Sat, Oct 18, 2008 at 10:09 PM, qvx <[EMAIL PROTECTED]> wrote:

[ ... ]

> Is there a better way or some library that does that?

How about this ?

$ ./timerexamples.py
Time: 1224375945.336958
Timer 2 fired at: 1224375945.840600
Timer 1 fired at: 1224375955.336889


#!/usr/bin/env python

import time

from circuits.core import Manager, Component, Event, listener
from circuits.timers import Timer

class TimerExamples(Component):

   @listener("timer1")
   def onTIMER1(self):
  print "Timer 1 fired at: %f" % time.time()

   @listener("timer2")
   def onTIMER2(self):
  print "Timer 2 fired at: %f" % time.time()

m = Manager()
m += TimerExamples()

timers = []
timers.append(Timer(10, Event(), "timer1"))
timers.append(Timer(0.5, Event(), "timer2"))

for timer in timers:
   m += timer

print "Time: %f" % time.time()

while True:
   try:
  m.flush()
  for timer in timers:
 timer.poll()
   except KeyboardInterrupt:
  break


cheers
James

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porting VB apps to Python for Window / Linux use

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Dotan
Cohen wrote:

> I often see mention of SMBs that either want to upgrade their Windows
> installations, or move to Linux, but cannot because of inhouse VB
> apps.

Probably best to leave those legacy VB apps alone and develop new
replacements in a more open, cross-platform language, like Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Aahz wrote:

> In article <[EMAIL PROTECTED]>,
> Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>
>>In message <[EMAIL PROTECTED]>, Terry
>>Reedy wrote:
>>>
>>> "For instance, the print statement got turned into a print function ...
>>> "
>>
>>Except I never use print in scripts.
> 
> "What, never?"

No, never. Not even "hardly ever".
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-18 Thread MRAB
On Oct 18, 7:31 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Gandalf wrote:
> > On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
> > wrote:
> >> Gandalf <[EMAIL PROTECTED]> wrote:
> >>> how can I do width python a normal for loop width tree conditions like
> >>> for example :
> >>> for x=1;x<=100;x+x:
> >>>     print x
> >> What you wrote would appear to be an infinite loop so I'll assume you meant
> >> to assign something to x each time round the loop as well. The simple
> >> Python translation of what I think you meant would be:
>
> >> x = 1
> >> while x <= 100:
> >>    print x
> >>    x += x
>
> >> If you really insist on doing it with a for loop:
>
> >> def doubling(start, limit):
> >>     x = start
> >>     while x <= limit:
> >>         yield x
> >>         x += x
>
> >> ...
>
> >> for x in doubling(1, 100):
> >>     print x
>
> > I was hopping to describe it with only one command. most of the
> > languages I know use this.
> > It seems weird to me their is no such thing in python. it's not that I
> > can't fined a solution it's all about saving code
>
> Python: 'makes common things easy and uncommon things possible'.
>
> The large majority of use cases for iteration are iterating though
> sequences, actual and virtual, including integers with a constant step
> size.  Python make that trivial to do and clear to read. Your example is
> trivially written as
>
> for i in range(11):
>    print 2**i
>
> Python provide while loops for more fine-grain control, and a protocol
> so *reuseable* iterators can plug into for loops. Duncan showed you
> both.  If you *need* a doubling loop variable once, you probably need
> one more than once, and the cost of the doubling generator is amortized
> over all such uses.  Any Python proprammer should definitely know how to
> write such a thing without hardly thinking.  We can squeeze a line out
> of this particular example:
>
> def doubling(value, limit):
>    while value <= limit:
>      yield value
>      value += value
>
Shouldn't the upper limit be exclusive in order to be Pythonic?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>In message <[EMAIL PROTECTED]>, Terry
>Reedy wrote:
>>
>> "For instance, the print statement got turned into a print function ... "
>
>Except I never use print in scripts.

"What, never?"
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>In message <[EMAIL PROTECTED]>, Aahz wrote:
>>
>> (There's a significant amount of JavaScript, much of which is generated by
>> Python code.)
>
>Been there, done that. Triple backslashes, anybody? :)

Why would you need a triple-backslash?  Ever used raw strings?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: IO error

2008-10-18 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Rajan
Arora wrote:

> I am trying to get the data out of an instrument through its GPIB port...
> 
> When i try read() command it gives me an IO timeout error.

What's the device name, device driver module name, do you have any sample or
diagnostic code you can run to prove that your PC is communicating properly
with the device?
--
http://mail.python.org/mailman/listinfo/python-list


Re: windows / unix path

2008-10-18 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>,
Marcin201 wrote:

> os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on
> Win.  When I read files created on Win under Unix this is a problem,
> python cannot open 'Pictures\\01.jpg'

But it can on Windows, right?

os.path contains functions specific to the _current_ platform (the one your
script is running on). If you're trying to perform pathname manipulations
on behalf of another platform, you shouldn't be using os.path.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Terry
Reedy wrote:

> "For instance, the print statement got turned into a print function ... "

Except I never use print in scripts.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Aahz wrote:

> (There's a significant amount of JavaScript, much of which is generated by
> Python code.)

Been there, done that. Triple backslashes, anybody? :)

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


Re: unicode .replace not working - why?

2008-10-18 Thread Kurt Peters
Thanks,
  The "distraction" was my problem.  I replaced the textu.replace as you 
suggested and it works fine.
Kurt

On Sun, 12 Oct 2008 19:53:09 -0700, Mark Tolonen wrote:

> In your original code:
> 
>textu.replace(unichr(167),'\n')
> 
> as Dennis suggested (but maybe you were distracted by his 'fn'
> replacement, so I'll leave it out):
> 
>textu = textu.replace(unichr(167),'\n')
> 
> .replace does not modify the string in place.  It returns the modified
> string, so you have to reassign it.
> 
> -Mark
> 
> "Kurt Peters" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> Thanks,
>>  clearly though, my "For loop" shows a character using ord(167), and
>>  using
>> print repr(textu), it shows the character \xa7 (as does Peter Oten's
>> post). So you can see what I see, here's the document I'm using - the
>> Special Use Airspace document at
>> http://www.faa.gov/airports_airtraffic/air_traffic/publications/ which
>> is = JO 7400.8P (PDF)
>>
>> if you just look at page three, it shows those unusual characters. Once
>> again, using a "simple" replace, doesn't seem to work.  I can't seem to
>> figure out how to get it to work, despite all the great posts
>> attempting to shed some light on the subject.
>>
>> Regards,
>> Kurt
>>
>>
>> "John Machin" <[EMAIL PROTECTED]> wrote in message
>> news:42f39e4c-
[EMAIL PROTECTED]
>> On Oct 12, 7:05 am, Kurt Peters <[EMAIL PROTECTED]> wrote:
>>> I'm using the code below to read a pdf document, and it has no line
>>> feeds or carriage returns in the imported text. I'm therefore trying
>>> to just replace the symbol that looks like it would be an end of line
>>> (found by examining the characters in the "for loop") unichr(167).
>>> Unfortunately, the replace isn't working, does anyone know what I'm
>>> doing wrong? I tried a number of things so I left comments in place as
>>> a subset of the bunch of things I tried to no avail.
>>
>> This is the first time I've ever looked inside a PDF file, and *only*
>> one file, but:
>>
>> import pyPdf, sys
>> filename = sys.argv[1]
>> doc = pyPdf.PdfFileReader(open(filename, "rb")) for pageno in
>> range(doc.getNumPages()):
>>page = doc.getPage(pageno)
>>textu = page.extractText()
>>print "pageno", pageno
>>print type(textu)
>>print repr(textu)
>>
>> gives me  and text with lots of \n at places where
>> you'd expect them.
>>
>> The only problem I can see is that where I see (and expect) quotation
>> marks (U+201C and U+201D) when viewing the file with Acrobat Reader,
>> the repr is showing \ufb01 and \ufb02. Similar problems with em-dashes
>> and apostrophes. I had a bit of a poke around:
>>
>> 1. repr(result of FlateDecode) includes *both* the raw bytes \x93 and
>> \x94, *and* the octal escapes \\223 and \\224 (which pyPdf translates
>> into \x93 and \x94).
>>
>> 2. Then pyPdf appears to push these through a fixed transformation
>> table (_pdfDocEncoding in generic.py) and they become \ufb01 and
>> \ufb02.
>>
>> 3. However:
>> |>>> '\x93\x94'.decode('cp1252') # as suspected |u'\u201c\u201d' # as
>> expected
>> |>>>
>>
>> AFAICT there is only one reference to encoding in the pyPdf docs: "if
>> pyPdf was unable to decode the string's text encoding" ...
>>
>> Cheers,
>> John
>>

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


Re: Loosely-coupled development environment

2008-10-18 Thread Ben Finney
Jorgen Grahn <[EMAIL PROTECTED]> writes:

> On Thu, 16 Oct 2008 07:47:36 +1100, Ben Finney <[EMAIL PROTECTED]> wrote:
> > Instead, I find the greater gain comes from a working environment
> > of *loosely-coupled* tools, with standard well-defined interfaces,
> > that one can flexibly mold and reconnect to meet whatever task is
> > at hand. The deeper this extends into the operating system, the
> > more the system as a whole will be able to support this
> > flexibility, and the more likely the tools will have been designed
> > to do so.
> >
> > Because of the inescapable central role in our craft of
> > manipulating text files, essential in this development environment
> > is a highly-customisable text editor with a broad *and* deep
> > library of existing customisations, to maximise the amount of work
> > already done for you when embarking on work in an area that is, to
> > you, new.
> 
> You think like I think, but I think your standards are too high. I
> like claiming "my IDE is Emacs and Unix", but in fact I know very
> little about how to customize Emacs using elisp

No, I'm in the same situation: my Emacs Lisp knowledge is virtually
non-existent. Fortunately, just about anything I want Emacs to do has
already been programmed by someone else, so in practice all I need to
know is how to access the community's extenstions, as said above.

> I use a Unix shell on the side to do the non-editing tasks which I
> guess you train your editor to do.

Yes, I didn't stress the importance of a full-blown Unix shell (with
all the commands one normally expects at such a shell) in such an
environment. I think “powerful editor (Emacs or Vim) plus Unix shell
environment” is a good first approximation of my recommended
development environment.

(good sigmonster, have a cookie)

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


Re: IDE Question

2008-10-18 Thread Fabio Zadrozny
> Isn't Eclipse kind of project oriented? I.e. not suited for opening a
> single file, anywhere, and viewing/editing it.  I get the impression
> that it prefers to have some "project" or "workspace" file which
> groups a set of files and contains configuration, build rules and so
> on.  The guy three postings up suggested a general-purpose text editor.

Yes, it prefers to have a project or workspace (which really helps you
navigating through the source, so, it's one thing I usually see as
positive, not negative). Still, you can use it to edit files outside
of its workspace -- that's supported on Pydev -- but it looses some of
those features (which are not usually available on regular editors
anyway, so, that'd probably be ok if comparing with an editor, not an
IDE)

> (As a side note: I don't use Eclipse myself, but I have seen novice
> programmers editing Python code with it, and what saw wasn't
> impressive. They *did* some kind of Python "plugin" installed, but
> were sitting there pressing SPACE to indent every line manually.)

Not sure which plugin they had, but I'm pretty positive that if they
had Pydev installed they'd have auto-indent without any problems (I
can assure you that auto-indent is a feature that received a lot of
attention in Pydev).

Cheers,

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


Re: algorizm to merge nodes

2008-10-18 Thread Scott David Daniels

JD wrote:

It could be a very good "homework assignment".
This is for a real application.


def do_nets(pairs):
r = {}
for a, b in pairs:
if a in r:
a_net = r[a]
if b not in a_net: # if not redundant link
if b in r: # Need to merge nets
a_net |= r[b]
for x in r[b]:
r[x] = a_net
else: # add a single node to the net
a_net.add(b)
r[b] = a_net
elif b in r: # add this node to another net
r[b].add(a)
r[a] = q[b]
else: # create a new net
r[a] = r[b] = set([a, b])
# r holds the result nets, but each net is in values multiple times
# So, get the unique elements in r's values.
return dict((id(x), x) for x in r.values()).values()

for group in do_nets([['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'],
  ['e', 'k'], ['c', 'u'], ['b', 'p']]):
print group

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


Re: PythonWin --> drwatson

2008-10-18 Thread Frank L. Thiel

On 18-Oct-08 16:31, this message was sent by Dennis Lee Bieber:


On Sat, 18 Oct 2008 15:00:03 GMT, "Frank L. Thiel" <[EMAIL PROTECTED]>
declaimed the following in comp.lang.python:

Thanks for your reply, Allan.  I am not sure what you mean by "the 
Windows installer package" -- a *.msi file?.  I cannot find a *.msi file 
at Sourceforge, which is where the  came 
from.  When I use the latter (I have uninstalled and reinstalled using 
this many times now!), I get no error entries in the Event Viewer. 
However, when I try to open PythonWin, the Event Viewer shows the 
following message:



Do you have a version of python 2.6 installed? (I'm surprised the
standalone win32 package for Python 2.6 is even available already).
Granted, win32 is maintained as a separate package, but the ActiveState
Python download (which includes it by default) is still only on Python
2.5.2


Yes, Dennis, I have Python 2.6 installed, and it works perfectly from a 
cmd window and from IDLE.

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


Re: PythonWin --> drwatson

2008-10-18 Thread [EMAIL PROTECTED]
On Oct 18, 4:31 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sat, 18 Oct 2008 15:00:03 GMT, "Frank L. Thiel" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> > Thanks for your reply, Allan.  I am not sure what you mean by "the
> > Windows installer package" -- a *.msi file?.  I cannot find a *.msi file
> > at Sourceforge, which is where the  came
> > from.  When I use the latter (I have uninstalled and reinstalled using
> > this many times now!), I get no error entries in the Event Viewer.
> > However, when I try to open PythonWin, the Event Viewer shows the
> > following message:
>
>         Do you have a version of python 2.6 installed? (I'm surprised the
> standalone win32 package for Python 2.6 is even available already).
> Granted, win32 is maintained as a separate package, but the ActiveState
> Python download (which includes it by default) is still only on Python
> 2.5.2
 The standalone package has been available for months, since the Alpha
stage I believe. I don't believe it will install without an installed
Python 2.6.
 PythonWin 2.6 of Oct 2 2008 works for me.  XP Pro service pack 3.
[ActiveState is not really relevant to this discussion.]
--
http://mail.python.org/mailman/listinfo/python-list


Re: better scheduler with correct sleep times

2008-10-18 Thread sokol

> > I started googling for scheduler and found one in standard library
> > but ih has the same code as mine (it calls the  functions in the
> > right order and my doesn't, but it still waits too long).
> > The other schedulers from web are dealing with
> > repeating tasks and such.
>
>
> I believe you're looking for the 'sched' 
> module:http://www.python.org/doc/2.5.2/lib/module-sched.html

The sched module behaves just like mine version because
it uses almost the same code. My observations include the
sched module as well. Check it's source code. It is flawed:
it calls the sleep method and while it sleeps (presumably
for a long time) all newly scheduled events are on hold.
See my example in original post.

My code solves this problem (or so it looks to me right now).
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-18 Thread robert

Aaron Brady wrote:

Gandalf wrote:


On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:

Gandalf <[EMAIL PROTECTED]> wrote:

how can I do width python a normal for loop width tree conditions like
for example :
for x=1;x<=100;x+x:
print x

What you wrote would appear to be an infinite loop so I'll assume you meant
to assign something to x each time round the loop as well. The simple
Python translation of what I think you meant would be:

x = 1
while x <= 100:
   print x
   x += x

If you really insist on doing it with a for loop:

def doubling(start, limit):
x = start
while x <= limit:
yield x
x += x

...

for x in doubling(1, 100):
print x

I was hopping to describe it with only one command. most of the
languages I know use this.
It seems weird to me their is no such thing in python. it's not that I
can't fined a solution it's all about saving code


Do you anticipate reusing it?  You could make something a little more
extendable.

for x in iexpression( 'x', 1, 100, 'x+x' ):
print x

or

for x in iexpression( lambda x: x+x, 1, 100  ):
print x

I'm assuming you don't want or have a closed form, in this case x= 2**
_x.




#and to learn even more about this, import this:
import this   # ;-)
--
http://mail.python.org/mailman/listinfo/python-list


IO error

2008-10-18 Thread Rajan Arora
Hi,
I am trying to get the data out of an instrument through its GPIB port
and using python code. I am able to perfectly control the operation of
the instrument with my code. But I have not figured out a way as yet
to get the data of the GPIB.
I thin that it will go through 2 steps:
1) instrument transfers data to its output buffer
2) Read from the output buffer.

When i try read() command it gives me an IO timeout error.

Any suggestions?

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


Re: windows / unix path

2008-10-18 Thread John Machin
On Oct 19, 6:00 am, Marcin201 <[EMAIL PROTECTED]> wrote:
> Is there an built-in functionality in python to convert Windows paths
> to Unix paths?  I am running into problems when creating data files on
> Windows and the running them on a Unix platform.  I create paths using
> os.path.join.
>
> os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on
> Win.  When I read files created on Win under Unix this is a problem,
> python cannot open 'Pictures\\01.jpg'
>

Note that os.path.join('Pictures', '01.jpg') returns 'Pictures/01.jpg'
on Unix.
Note that 'Pictures\\01.jpg' == r'Pictures\01.jpg' i.e. there is only
one backslash.
Have you considered unix_path = windows_path.replace('\\', '/')?

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


Re: loops

2008-10-18 Thread Duncan Booth
wbowers <[EMAIL PROTECTED]> wrote:

> I agree that using range() for simple iterations is the way to go.

except that as Terry said, "The large majority of use cases for iteration 
are iterating though sequences"

I very rarely use range() in iterations.

> Here are some examples of python expressions you'd use in specific
> situations:
> 

...

> # instead of for (i = 99; i >= 0; i--)
> for i in range(100)[::-1]: pass

or:
  for i in xrange(99, -1, -1): pass


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


Re: better scheduler with correct sleep times

2008-10-18 Thread Chris Rebert
On Sat, Oct 18, 2008 at 5:09 AM, qvx <[EMAIL PROTECTED]> wrote:
> I need a scheduler which can delay execution of a
> function for certain period of time.
> My attempt was something like this:
>
[code snipped]
>
> But then I came up with the following case:
>
> 1. I call delay with delay_sec = 10
> 2. The scheduler goes to sleep for 10 seconds
> 3. In the meantime (lets say 1 second later) I delay
>   another func but this time with delay_sec=0.5
> 4. The scheduler is sleeping and won't know call my
>   second function for another 9 seconds insted of 0.5
>
> I started googling for scheduler and found one in standard library
> but ih has the same code as mine (it calls the  functions in the
> right order and my doesn't, but it still waits too long).
> The other schedulers from web are dealing with
> repeating tasks and such.
>
> So, I wrote this:
>
[more code snipped]
>
> Is there a better way or some library that does that?

I believe you're looking for the 'sched' module:
http://www.python.org/doc/2.5.2/lib/module-sched.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> My observations:
>
> 1. Threading module uses time.sleep instead of time.clock
>   which results in less precise results (on windows platform)
>
>if sys.platform=="win32":  #take care of differences in clock
> accuracy
>wallclock = time.clock
>else:
>wallclock = time.time
>
> 2. while analyzing threading module i noticed that wait() is
>   implemented via loop and tiny sleep periods. I was expecting
>   the usage of underlaying OS primitives and functions but
>   then I remembered about GIL and quasi-multithreaded nature
>   of Python. But still, isn't there a more precise method
>   that interpreter itself could implement?
>
> Thanks,
> Tvrtko
>
> P.S. This was Python 2.5
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
Terry Reedy  <[EMAIL PROTECTED]> wrote:
>
>http://www.linux.com/feature/150399

Although I have no objections to the way I was quoted, the article didn't
include the points I wanted to make.  Here's my original interview:

On Sat, Oct 04, 2008, [EMAIL PROTECTED] wrote:
>
> Terrific! Thanks for participating. I'll be sure to put a link in the
> story to your book.

That would be great!  Please use http://www.pythonfood.com/

> Could you say approximately how much Python 2.3 or 2.4 code you have
> in your current job? What is this code used for, broadly speaking?

The company I work for is http://www.pagedna.com/ -- it has been in
business for more than ten years and was started with Python 1.4.  I've
been working there for more than four years.  Our software is a web
application for taking orders and sending EPS/PDF files to printing
plants.

There's more than 200K lines of code, most of it Python.  A lot of the
code resides in template files for generating web pages.  (There's a
significant amount of JavaScript, much of which is generated by Python
code.)  Although EPS/PDF generation is the heart of our application,
there are many ancillary features to meet our customer needs (such as
approval workflow, inventory management, and reporting).

> What are your thoughts about eventually moving that code to 3.0? Would
> this be a big job? At what point, if ever, would it be necessary?

It would be a huge job, made more difficult because many of our bits of
Python code reside in web templates.  However, by the time we do the
conversion the tools for automatic conversion should be much improved.
Although both my boss (Tony Lownds) and I are active in the Python
community, we haven't even talked about 3.0 -- it's at least two or
three years away.

> In your opinion, do you think it's a wise move to forgo backward
> compatibility in Python 3.0, given both the user base and current
> limitations of the language?

First of all, I think it overstates the case to talk about "forgoing
compatibility".  The base Python language is still the same; the only
difference immediately apparent at the simple scripting level is that the
print command has changed to a function.  Python 3.0 is more about
removing mistakes and warts, many of which people have been encouraged to
avoid for years.

In addition, it is the intention to gradually merge the 2.x and 3.x
series; Python 2.6 is already a major step in that direction.

All in all, I think Python 3.0 is the kind of necessary evolution that
software needs.  It certainly isn't as big a change as going from DOS to
Windows or from Mac OS 9 to OS X.

> What qualities about Python first attracted you to the language?

Actually, I was forced to learn Python.  I was a Perl expert at the time,
and I saw no reason to learn yet another scripting language.  Since then,
I have become enamored of Python's readability and how a typical
programmer's pseudocode is trivially translated into running Python.

> Of what you read about Python 3.0, what features do you find most
> intriguing?

The fact that it's getting done at all!  For years, Python 3.0 was
referred to as Python 3000 -- the joke being that it would happen in the
year 3000 (meaning, never).  Work only started seriously three years ago,
and I think that Python 3.0 has done an excellent job of balancing the
past and the future.

> That's about it, though if you have any other thoughts about Python
> 3.0, I'd love to hear them as well.

That pretty much covers it, I think.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: Linux.com: Python 3 makes a big break

2008-10-18 Thread Jean-Paul Calderone

On Sat, 18 Oct 2008 15:30:23 -0400, Terry Reedy <[EMAIL PROTECTED]> wrote:

http://www.linux.com/feature/150399
Interesting article with one minor incompleteness.
"For instance, the print statement got turned into a print function; you 
must now put parentheses around what you want to print to the screen. The 
change allows developers to work with print in a more flexible and uniform 
way. If someone needs to replace the print function with some other action, 
it can be done with a universal search and replace, rather than rewriting 
each print statement by hand."


Even easier, print as a function can be replaced simply by defining a new 
version with the same name.  No search/replace is needed.  And reversion to 
the built-in only requires commenting out the replacement.


Perhaps it also omitted the fact that nothing prevents you from defining a
function to write things to stdout (or elsewhere) in Python 2.5, making the
Python 3.x change largely a non-feature. ;)

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


Re: xml.etree.ElementTree and XPath

2008-10-18 Thread Stefan Behnel
xkenneth wrote:
> Can I execute XPath queries on ElementTree objects ignoring the
> namespace? IE './node' instead of './{http://namespace.com}node'.

The XPath support in ET is very limited. You can use lxml.etree instead, which
has full support for XPath 1.0, i.e. you can do

tree.xpath('//*[local-name() = "node"]')

http://codespeak.net/lxml/

Or you can do the iteration yourself, i.e.

for el in tree.iter(): # or tree.getiterator():
if isinstance(el.tag, basestring):
if el.tag.split('}', 1)[-1] == "node":
print el.tag

which works in both ET and lxml.etree.

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


Re: Interoperating with C

2008-10-18 Thread Aaron Brady
Michele wrote:

> Hi there,
> I would like to call C functions in a Python program, passing
> user-defined objects and primitive python types (str, ints, etc.); of
> course I also want to receive data from these functions, manipulating it
> in my python program.
> First of all: is this possible?
> Secondly, what's the mapping between C types and Python types?
>
> Thank you

Hi,

You can try this thread.  After some confusion there is a solution at
bottom.  Let me know what you think.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d59cb670a345ef/9557483dee0f9294



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


Re: loops

2008-10-18 Thread wbowers
On Oct 18, 11:31 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Gandalf wrote:
> > On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
> > wrote:
> >> Gandalf <[EMAIL PROTECTED]> wrote:
> >>> how can I do width python a normal for loop width tree conditions like
> >>> for example :
> >>> for x=1;x<=100;x+x:
> >>>     print x
> >> What you wrote would appear to be an infinite loop so I'll assume you meant
> >> to assign something to x each time round the loop as well. The simple
> >> Python translation of what I think you meant would be:
>
> >> x = 1
> >> while x <= 100:
> >>    print x
> >>    x += x
>
> >> If you really insist on doing it with a for loop:
>
> >> def doubling(start, limit):
> >>     x = start
> >>     while x <= limit:
> >>         yield x
> >>         x += x
>
> >> ...
>
> >> for x in doubling(1, 100):
> >>     print x
>
> > I was hopping to describe it with only one command. most of the
> > languages I know use this.
> > It seems weird to me their is no such thing in python. it's not that I
> > can't fined a solution it's all about saving code
>
> Python: 'makes common things easy and uncommon things possible'.
>
> The large majority of use cases for iteration are iterating though
> sequences, actual and virtual, including integers with a constant step
> size.  Python make that trivial to do and clear to read. Your example is
> trivially written as
>
> for i in range(11):
>    print 2**i
>
> Python provide while loops for more fine-grain control, and a protocol
> so *reuseable* iterators can plug into for loops. Duncan showed you
> both.  If you *need* a doubling loop variable once, you probably need
> one more than once, and the cost of the doubling generator is amortized
> over all such uses.  Any Python proprammer should definitely know how to
> write such a thing without hardly thinking.  We can squeeze a line out
> of this particular example:
>
> def doubling(value, limit):
>    while value <= limit:
>      yield value
>      value += value
>
> Terry Jan Reedy

I agree that using range() for simple iterations is the way to go.
Here are some examples of python expressions you'd use in specific
situations:

# instead of for (i = 0; i < 100; i++)
for i in range(100): pass

# instead of for (i = 10; i < 100; i++)
for i in range(10, 100): pass

# instead of for (i = 1; i < 100; i += 2)
for i in range(1, 100, 2): pass

# instead of for (i = 99; i >= 0; i--)
for i in range(100)[::-1]: pass

There's always a way to do it, and it's almost always really simple :-D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Iteration

2008-10-18 Thread Aaron Brady
Chris McComas wrote:
> actually i'm running it online, with a mysql db. so in the db there is
> a table CollegeYear with the following fields:
>
> name
> rating
> change
> wp
>
> then another table Games
>
> date
> year
> team_1
> team_1_score
> team_2
> team_2_score
>
> it goes through and calculates everything, then when it's time to
> compute the rating i have say this code:
>
> http://dpaste.com/85300/
>
> it goes through and computes them, then add the new rating and
> absolute value of the changed rating to the db. what i need now is a
> way to get the largest entry for 'change' and if it is greater than
> 0.5 then do this code again. if it is less than 0.5 then we're
> done.

What about "SELECT MAX( rating ) FROM CollegeYear"?

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


xml.etree.ElementTree and XPath

2008-10-18 Thread xkenneth
All,

Can I execute XPath queries on ElementTree objects ignoring the
namespace? IE './node' instead of './{http://namespace.com}node'.

Is there any support for XPath and Minidom?

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


Re: Unicode File Names

2008-10-18 Thread Mark Tolonen


""Martin v. Löwis"" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Oddly, os.getcwd() and os.getcwdu() both still exist in Python 3.0.
Since the behavior is now identical it seems os.getcwdu() should be
dropped.


It is dropped, and os.getcwdb() has been added.


Must be changed post 3.0rc1, but I seem to remember reading about that now 
in another thread:


Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit 
(Intel)]

on win32
Type "help", "copyright", "credits" or "license" for more information.

import os
[s for s in dir(os) if 'cwd' in s]

['getcwd', 'getcwdu']

-Mark












































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


Linux.com: Python 3 makes a big break

2008-10-18 Thread Terry Reedy

http://www.linux.com/feature/150399
Interesting article with one minor incompleteness.
"For instance, the print statement got turned into a print function; you 
must now put parentheses around what you want to print to the screen. 
The change allows developers to work with print in a more flexible and 
uniform way. If someone needs to replace the print function with some 
other action, it can be done with a universal search and replace, rather 
than rewriting each print statement by hand."


Even easier, print as a function can be replaced simply by defining a 
new version with the same name.  No search/replace is needed.  And 
reversion to the built-in only requires commenting out the replacement.


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


hiding modules in __init__.py

2008-10-18 Thread Brendan Miller
How would I implement something equivalent to java's package private in
python?

Say if I have

package/__init__.py
package/utility_module.py

and utility_module.py is an implementation detail subject to change.

Is there some way to use __init__.py to hide modules that I don't want
clients to see? Or is the best practice just to name the module you don't
want clients to use _utility_module and have it private by convention?

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


windows / unix path

2008-10-18 Thread Marcin201
Is there an built-in functionality in python to convert Windows paths
to Unix paths?  I am running into problems when creating data files on
Windows and the running them on a Unix platform.  I create paths using
os.path.join.

os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on
Win.  When I read files created on Win under Unix this is a problem,
python cannot open 'Pictures\\01.jpg'

Thanks,

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


Re: heapreplace, methodcaller

2008-10-18 Thread Marc 'BlackJack' Rintsch
On Sat, 18 Oct 2008 07:01:26 -0700, bearophileHUGS wrote:

> Hello, I'm experimenting more with Python 2.6 and its numerous changes.
> 
> […]
>
> Regarding the operators module, this syntax: methodcaller('replace',
> 'old', 'new')
> 
> Has this meaning:
> lambda s: s.replace('old', 'new')
> 
> I don't know if methodcaller() is faster than that lambda but:
> - It's not shorter;
> - For me it's not more readable;

Then use the ``lambda``.

Your example has just literal constants.  Let's take this example:

methodcaller(meth, arg_a, arg_b)

which is expressed as ``lambda`` function:

lambda x, m=meth, a=arg_a, b=arg_b: getattr(x, meth)(a, b)

Which is longer and IMHO less readable than `methodcaller()`.

> - If it's faster than the lambda, then maybe CPython can start
> performing a little more optimizations, like turning that tiny lambda
> into inlined code.

How?  The functions in `operator` are meant to be passed directly or to 
to create other functions that are passed as HOFs into other functions.  
So the compiler doesn't know in which functions they are used in the end 
and it's possible that different functions are used there too.

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


Re: loops

2008-10-18 Thread Terry Reedy

Gandalf wrote:

On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:

Gandalf <[EMAIL PROTECTED]> wrote:

how can I do width python a normal for loop width tree conditions like
for example :
for x=1;x<=100;x+x:
print x

What you wrote would appear to be an infinite loop so I'll assume you meant
to assign something to x each time round the loop as well. The simple
Python translation of what I think you meant would be:

x = 1
while x <= 100:
   print x
   x += x

If you really insist on doing it with a for loop:

def doubling(start, limit):
x = start
while x <= limit:
yield x
x += x

...

for x in doubling(1, 100):
print x


I was hopping to describe it with only one command. most of the
languages I know use this.
It seems weird to me their is no such thing in python. it's not that I
can't fined a solution it's all about saving code


Python: 'makes common things easy and uncommon things possible'.

The large majority of use cases for iteration are iterating though 
sequences, actual and virtual, including integers with a constant step 
size.  Python make that trivial to do and clear to read. Your example is 
trivially written as


for i in range(11):
  print 2**i

Python provide while loops for more fine-grain control, and a protocol 
so *reuseable* iterators can plug into for loops. Duncan showed you 
both.  If you *need* a doubling loop variable once, you probably need 
one more than once, and the cost of the doubling generator is amortized 
over all such uses.  Any Python proprammer should definitely know how to 
write such a thing without hardly thinking.  We can squeeze a line out 
of this particular example:


def doubling(value, limit):
  while value <= limit:
yield value
value += value

Terry Jan Reedy

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


Re: IDE Question

2008-10-18 Thread Jorgen Grahn
On Wed, 15 Oct 2008 11:02:45 -0700 (PDT), jdd <[EMAIL PROTECTED]> wrote:
> On Oct 15, 1:19 pm, "Steve Phillips" <[EMAIL PROTECTED]> wrote:
>> Hi All,
>> I am just wondering what seems to be the most popular IDE. The reason
>> I ask is I am currently at war with myself when it comes to IDE's. It
>> seems like every one I find and try out has something in it that
>> others don't and viceversa. I am in search for the perfect IDE and
>> after many months of searching, I always come back to IDLE to do what
>> I need to do. I want to use Komodo badly but the one issue I have with
>> that is sometimes the auto-complete works and other times it doesn't.
>> Even if I carbon copy a script.
>>
>> Thanks in advance,
>> Steve P
>
> I would personally recommend that you take the time to learn your way
> around a powerful text editor such as emacs or vim (I use emacs,
> myself), however that may not fit well with your personal editing
> tastes, and the learning curve is a bit steep. The editing tastes
> problem can be solved once you learn your way around a powerful text
> editor (emacs, for instance, is practically infinitely customizable),
> and the power you get from using them is amazing.

I agree.  And the reason is this: learning to use a text editor well
takes years -- meaning that after years you still learn new things
that help you type better/faster/with less strain on your ancles.  You
don't want that to be tied to programming Python.

To pick an example: what Emacs calls dabbrev-expand. You type a
few letters of a word, call on dabbrev-expand, and cycle through
words in your open files which start with those letters. This is
very useful in Python code, but it's equally useful when writing
mail, C code, documentation ...

Most people I've seen programming use their editor as if it was
Windows Notepad. It's easy to get an advantage over them, by being
willing to learn a bit. (The downside is that watching them program
will be like watching someone trying to ride a bike with flat tyres ...)

/Jorgen

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


Re: ANN: pyparsing 1.5.1 released

2008-10-18 Thread Terry Reedy

Paul McGuire wrote:

I've just uploaded to SourceForge and PyPI the latest update to



(Python 3.0 uses syntax for catching exceptions that is incompatible
with Python versions pre 2.6, so there is no way for me to support
both existing Python releases and Python 3.0 with a common source code
base. 


I thought 2to3.py was supposed to make that change automatically. Have 
you tried it and found it not to work?


tjr

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


Re: Loosely-coupled development environment (was: IDE Question)

2008-10-18 Thread Jorgen Grahn
On Thu, 16 Oct 2008 07:47:36 +1100, Ben Finney <[EMAIL PROTECTED]> wrote:
> "Steve Phillips" <[EMAIL PROTECTED]> writes:
>
>> I am just wondering what seems to be the most popular IDE. The
>> reason I ask is I am currently at war with myself when it comes to
>> IDE's. It seems like every one I find and try out has something in
>> it that others don't and viceversa.
>
> This speaks to the twin facts that people want different things, and
> that Python is flexible enough to accommodate these differing desires.
>
>> I am in search for the perfect IDE
>
> Perfect for whom, exactly? Perfect for what, exactly?
>
> These are not facetious questions: they cut to the core of your quest.
> I am convinced that your quest for a development environment that is
> ?integrated? (or ?tightly-coupled?, in programming terminology) is
> incompatible with any useful criterion of ?perfect?.
>
> Instead, I find the greater gain comes from a working environment of
> *loosely-coupled* tools, with standard well-defined interfaces, that
> one can flexibly mold and reconnect to meet whatever task is at hand.
> The deeper this extends into the operating system, the more the system
> as a whole will be able to support this flexibility, and the more
> likely the tools will have been designed to do so.
>
> Because of the inescapable central role in our craft of manipulating
> text files, essential in this development environment is a
> highly-customisable text editor with a broad *and* deep library of
> existing customisations, to maximise the amount of work already done
> for you when embarking on work in an area that is, to you, new.
>
> It happens that the text editors which meet these criteria are limited
> to Emacs and Vim, with a sharp decline in suitability (by these
> criteria) beyond those two. Both have powerful user-customisable
> capabilities and a mammoth availability of existing extensions for a
> staggering variety of tasks. Learn one of these editors well,
> familiarise yourself with how to access the rich library of available
> extensions, and make the text editor the core of your loosely-coupled
> development environment.

You think like I think, but I think your standards are too high. I
like claiming "my IDE is Emacs and Unix", but in fact I know very
little about how to customize Emacs using elisp -- I have added a few
keyboard shortcuts, made it use a readable font, and disabled a few
silly features, but that's about it.  I use a Unix shell on the side
to do the non-editing tasks which I guess you train your editor to do.

So, my requirements on the editor boils down to:

- free and universally available
- will still be around when I'm dead
- capable as a pure text editor
- support for colorizing Python code (at least strings and comments)
- helps me indenting Python code
- support for other languages

I hope many editors fulfill those criteria, except maybe the first
two.

/Jorgen

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


Re: IDE Question

2008-10-18 Thread Jorgen Grahn
On Wed, 15 Oct 2008 11:44:59 -0700 (PDT), jdd <[EMAIL PROTECTED]> wrote:
> On Oct 15, 2:13 pm, "Fabio Zadrozny" <[EMAIL PROTECTED]> wrote:
>> Now, following that route, many people call Eclipse is the 21st
>> century Emacs... ;-)
>>
>
> I don't want to kick off an editor war or anything, but I don't think
> that Eclipse is anywhere near being a 21st century emacs, unless
> there's been a whole lot of progress with it since the last time I
> used it. [...]

Isn't Eclipse kind of project oriented? I.e. not suited for opening a
single file, anywhere, and viewing/editing it.  I get the impression
that it prefers to have some "project" or "workspace" file which
groups a set of files and contains configuration, build rules and so
on.  The guy three postings up suggested a general-purpose text editor.

(As a side note: I don't use Eclipse myself, but I have seen novice
programmers editing Python code with it, and what saw wasn't
impressive. They *did* some kind of Python "plugin" installed, but
were sitting there pressing SPACE to indent every line manually.)

/Jorgen

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


Re: Some Problem about Moin

2008-10-18 Thread Paul Boddie
On 18 Okt, 06:18, Kara <[EMAIL PROTECTED]> wrote:
> Hi,everyone.I'm a greenhand on Moin.I want to change my left-side of
> index like Python.org that if you click one link in left-Side, it will
> show sub-dirs under the link.So would you give me some "practise in
> action" or ideas?

The www.python.org site doesn't use MoinMoin, but wiki.python.org
does. Unfortunately, the latter doesn't employ submenus like the main
site does: you only get a customised version of the usual MoinMoin
"navibar" or navigation menu.

For a long time I've been tempted to make a category menu macro for
MoinMoin, especially since this kind of thing is usually the thing
that people show off as a magical feature of certain content
management systems. Perhaps I'll try and write something and upload it
to the macro market:

http://moinmo.in/MacroMarket

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


Re: Interoperating with C

2008-10-18 Thread Grant Edwards
On 2008-10-18, Michele <[EMAIL PROTECTED]> wrote:

> I would like to call C functions in a Python program, passing
> user-defined objects and primitive python types (str, ints, etc.); of
> course I also want to receive data from these functions, manipulating it
> in my python program.
> First of all: is this possible?

Yes.

> Secondly, what's the mapping between C types and Python types?

http://www.python.org/doc/2.5.2/ext/ext.html
http://www.python.org/doc/2.5.2/lib/module-ctypes.html

-- 
Grant Edwards   grante Yow! I want to kill
  at   everyone here with a cute
   visi.comcolorful Hydrogen Bomb!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: PythonWin --> drwatson

2008-10-18 Thread Frank L. Thiel

On 18-Oct-08 01:39, this message was sent by Allan:


"Frank L. Thiel" <[EMAIL PROTECTED]> writes:


I have installed PythonWin from the 
distribution.  When I try to open it, the message "PyWin32 has
encountered a problem ..." appears, and a drwatson error report is
generated.

Python 2.6 itself, from a cmd window or using IDLE, works without problem.
...(snip)

Hello Frank,

Have you tried uninstalling PythonWin and reinstalling it using the
Windows installer package? Is there any entry in the Event Viewer
application log when this happens?



Thanks for your reply, Allan.  I am not sure what you mean by "the 
Windows installer package" -- a *.msi file?.  I cannot find a *.msi file 
at Sourceforge, which is where the  came 
from.  When I use the latter (I have uninstalled and reinstalled using 
this many times now!), I get no error entries in the Event Viewer. 
However, when I try to open PythonWin, the Event Viewer shows the 
following message:


"Faulting application pythonwin.exe, version 2.6.212.0, faulting module 
mfc90.dll, version 9.0.21022.8, fault address 0x0004453f."

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


PyCon 2009 (US) - Call for Tutorials

2008-10-18 Thread Greg Lindstrom
The period for submitting tutorial proposals for Pycon 2009 (US) is open and
will continue through Friday, October 31th. This year features two
"pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday
March 26 in Chicago. This allows for more classes than ever.

Tutorials are 3-hours long on a specific topic of your choice. Last year we
featured classes on Learning Python, Web Development, Scientific Computing,
and many more. Class size varied from 10 to over 60 students. The extended
time spent in class allows teachers to cover a lot of material while
allowing for interaction with students.

The full Call for Tutorial Proposals, including submission details, an
example proposal as well as a template, is available at .

Tutorial selections will be announced in early December to give you time to
prepare your class and PyCon will compensate instructors US$1,500 per
tutorial.

If you have any questions, please contact [EMAIL PROTECTED]

Greg Lindstrom
Tutorial Coordinator, PyCon 2009 (US)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interoperating with C

2008-10-18 Thread bearophileHUGS
Michele:
> I would like to call C functions in a Python program,

First of all take a look at the standard module ctypes.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Interoperating with C

2008-10-18 Thread Michele
Hi there,
I would like to call C functions in a Python program, passing
user-defined objects and primitive python types (str, ints, etc.); of
course I also want to receive data from these functions, manipulating it
in my python program.
First of all: is this possible?
Secondly, what's the mapping between C types and Python types?

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


heapreplace, methodcaller

2008-10-18 Thread bearophileHUGS
Hello, I'm experimenting more with Python 2.6 and its numerous
changes.

To improve name coherence I think this method of the heapq module:
heapq.heapreplace(heap, item)

can grow an alias in Python 2.6.1/2.7 and 3.0/3.1:
heapq.heappoppush(heap, item)

So later the heapreplace() name can be deprecated.

The heapq can also become a Heap class (with methods named as the
functions), with an optional key function; time ago I have written
such class in the cookbook.

--

Regarding the operators module, this syntax:
methodcaller('replace', 'old', 'new')

Has this meaning:
lambda s: s.replace('old', 'new')

I don't know if methodcaller() is faster than that lambda but:
- It's not shorter;
- For me it's not more readable;
- If it's faster than the lambda, then maybe CPython can start
performing a little more optimizations, like turning that tiny lambda
into inlined code.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: python-ldap reading an OU with more than 1000 objects

2008-10-18 Thread Michael Ströder
Erick Perez - Quadrian Enterprises, S.A. wrote:
> I have a MS Windows AD domain, and have one OU with more tan 1000 users
> objects. When I try to read it, I hit the 1000 limit of AD while returning
> objects, so I'm asking for advice as to how to read them.

IIRC with MS AD you can circumvent this limit by using the Simple Paged
Control (see RFC 2696). Check Demo/page_control.py in python-ldap's
source distribution for example code.

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


Re: Help with Iteration

2008-10-18 Thread Chris McComas
On Oct 18, 12:43 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Oct 17, 10:44 pm, Chris McComas <[EMAIL PROTECTED]> wrote:
>
> > i have a python script that is computing ratings of sports teams.
>
> > what i'm trying to do is setup an iteration for the rating so that the
> > python program recomputes the rating if any of the value difference is
>
> > > 0.5. it's common for sports ratings to run such iterations...
>
> > any tips, pointers on where to look on how to do this the best way?
>
> > right now i'm getting the ratings from the file, limiting my results
> > to 1 entry, the biggest number, if it's > 0.5, then i want it to
> > compute the ratings again. if it is < 0.5 then it just goes on to
> > the next step in the file.
>
> > thnx in advance.
>
> Can you cut and paste a few lines?  Otherwise I assume your file looks
> like this:
>
> A 0.1
> B 0.3
> C 0.6
>
> You interpret the file like this:
>
> name= A, rating= 0.1
> name= B, rating= 0.3
> name= C, rating= 0.6
> --recompute--
>
> new values:
> name= A, rating= 0.1
> name= B, rating= 0.2
> name= C, rating= 0.4
>
> new file:
> A 0.1
> B 0.2
> C 0.4
>
> Am I right so far?

actually i'm running it online, with a mysql db. so in the db there is
a table CollegeYear with the following fields:

name
rating
change
wp

then another table Games

date
year
team_1
team_1_score
team_2
team_2_score

it goes through and calculates everything, then when it's time to
compute the rating i have say this code:

http://dpaste.com/85300/

it goes through and computes them, then add the new rating and
absolute value of the changed rating to the db. what i need now is a
way to get the largest entry for 'change' and if it is greater than
0.5 then do this code again. if it is less than 0.5 then we're
done.
--
http://mail.python.org/mailman/listinfo/python-list


Porting VB apps to Python for Window / Linux use

2008-10-18 Thread Dotan Cohen
I often see mention of SMBs that either want to upgrade their Windows
installations, or move to Linux, but cannot because of inhouse VB
apps. Are there any Python experts who I can reference them to for
porting? I have nothing on hand at the moment, but I see this as a
need without an obvious answer.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode File Names

2008-10-18 Thread Martin v. Löwis
> Oddly, os.getcwd() and os.getcwdu() both still exist in Python 3.0.  
> Since the behavior is now identical it seems os.getcwdu() should be
> dropped.

It is dropped, and os.getcwdb() has been added.

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


Re: Emacs users: feedback on diffs between python-mode.el and python.el?

2008-10-18 Thread Rob Wolfe
Alberto Griggio <[EMAIL PROTECTED]> writes:

> Hello,
>
>> I second Bruno's points, the older python-mode.el is much
>> better, 
>
> I agree too. I can't really say what's missing from python.el, but I'm
> much more comfortable with python-mode.el. The triple-quote highlight is
> better in python.el, but I was successful in porting it to
> python-mode.el as well. Unfortunately, I don't have a clean diff, as I
> did some other tweaks...

Many thanks for this suggestion.
Now python-mode.el works like a charm. So many years of frustration. ;-)

I just downloaded python-mode.el from svn:
http://svn.sourceforge.net/viewvc/python-mode/trunk/python-mode/

and applied this patch (code taken from python.el):

--- python-mode.el.org  2008-10-17 21:20:29.0 +0200
+++ python-mode.el  2008-10-17 21:23:13.0 +0200
@@ -500,6 +500,63 @@
  '("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t)
  ))
   "Additional expressions to highlight in Python mode.")
+
+(defconst python-font-lock-syntactic-keywords
+  ;; Make outer chars of matching triple-quote sequences into generic
+  ;; string delimiters.  Fixme: Is there a better way?
+  `((,(rx (or line-start buffer-start
+ (not (syntax escape))); avoid escaped leading quote
+ (group (optional (any "uUrR"))) ; prefix gets syntax property
+ (optional (any "rR"))   ; possible second prefix
+ (group (syntax string-quote))   ; maybe gets property
+ (backref 2) ; per first quote
+ (group (backref 2))); maybe gets property
+ (1 (python-quote-syntax 1))
+ (2 (python-quote-syntax 2))
+ (3 (python-quote-syntax 3)
+
+(defun python-quote-syntax (n)
+  "Put `syntax-table' property correctly on triple quote.
+Used for syntactic keywords.  N is the match number (1, 2 or 3)."
+  ;; Given a triple quote, we have to check the context to know
+  ;; whether this is an opening or closing triple or whether it's
+  ;; quoted anyhow, and should be ignored.  (For that we need to do
+  ;; the same job as `syntax-ppss' to be correct and it seems to be OK
+  ;; to use it here despite initial worries.)  We also have to sort
+  ;; out a possible prefix -- well, we don't _have_ to, but I think it
+  ;; should be treated as part of the string.
+
+  ;; Test cases:
+  ;;  ur"""ar""" x='"' # """
+  ;; x = ''' """ ' a
+  ;; '''
+  ;; x '"""' x """ \ x
+  ;; Fixme:  "" goes wrong (due to syntax-ppss not getting the string
+  ;; fence context).
+  (save-excursion
+(goto-char (match-beginning 0))
+(cond
+ ;; Consider property for the last char if in a fenced string.
+ ((= n 3)
+  (let ((syntax (syntax-ppss)))
+   (when (eq t (nth 3 syntax)) ; after unclosed fence
+ (goto-char (nth 8 syntax)); fence position
+ (skip-chars-forward "uUrR")   ; skip any prefix
+ ;; Is it a matching sequence?
+ (if (eq (char-after) (char-after (match-beginning 2)))
+ (eval-when-compile (string-to-syntax "|"))
+ ;; Consider property for initial char, accounting for prefixes.
+ ((or (and (= n 2) ; leading quote (not prefix)
+  (= (match-beginning 1) (match-end 1))) ; prefix is null
+ (and (= n 1)  ; prefix
+  (/= (match-beginning 1) (match-end 1 ; non-empty
+  (unless (nth 3 (syntax-ppss))
+(eval-when-compile (string-to-syntax "|"
+ ;; Otherwise (we're in a non-matching string) the property is
+ ;; nil, which is OK.
+ )))
+
+
 (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
 
 ;; have to bind py-file-queue before installing the kill-emacs-hook
@@ -1189,7 +1246,10 @@
   (setq major-mode  'python-mode
mode-name   "Python"
local-abbrev-table  python-mode-abbrev-table
-   font-lock-defaults  '(python-font-lock-keywords)
+font-lock-defaults'(python-font-lock-keywords nil nil nil nil
+(font-lock-syntactic-keywords
+ . python-font-lock-syntactic-keywords))
+
paragraph-separate  "^[ \t]*$"
paragraph-start "^[ \t]*$"
require-final-newline   t


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


Re: Emacs users: feedback on diffs between python-mode.el and python.el?

2008-10-18 Thread Rob Wolfe
Alberto Griggio <[EMAIL PROTECTED]> writes:

> Hello,
>
>> I second Bruno's points, the older python-mode.el is much
>> better, 
>
> I agree too. I can't really say what's missing from python.el, but I'm
> much more comfortable with python-mode.el. The triple-quote highlight is
> better in python.el, but I was successful in porting it to
> python-mode.el as well. Unfortunately, I don't have a clean diff, as I
> did some other tweaks...

Many thanks for this suggestion. 
Now python-mode.el works like a charm. So many years of frustration. :-)

I just downloaded python-mode.el from svn:
http://svn.sourceforge.net/viewvc/python-mode/trunk/python-mode/

and applied this patch (code taken from python.el):

--- python-mode.el.org  2008-10-17 21:20:29.0 +0200
+++ python-mode.el  2008-10-17 21:23:13.0 +0200
@@ -500,6 +500,63 @@
  '("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t)
  ))
   "Additional expressions to highlight in Python mode.")
+
+(defconst python-font-lock-syntactic-keywords
+  ;; Make outer chars of matching triple-quote sequences into generic
+  ;; string delimiters.  Fixme: Is there a better way?
+  `((,(rx (or line-start buffer-start
+ (not (syntax escape))); avoid escaped leading quote
+ (group (optional (any "uUrR"))) ; prefix gets syntax property
+ (optional (any "rR"))   ; possible second prefix
+ (group (syntax string-quote))   ; maybe gets property
+ (backref 2) ; per first quote
+ (group (backref 2))); maybe gets property
+ (1 (python-quote-syntax 1))
+ (2 (python-quote-syntax 2))
+ (3 (python-quote-syntax 3)
+
+(defun python-quote-syntax (n)
+  "Put `syntax-table' property correctly on triple quote.
+Used for syntactic keywords.  N is the match number (1, 2 or 3)."
+  ;; Given a triple quote, we have to check the context to know
+  ;; whether this is an opening or closing triple or whether it's
+  ;; quoted anyhow, and should be ignored.  (For that we need to do
+  ;; the same job as `syntax-ppss' to be correct and it seems to be OK
+  ;; to use it here despite initial worries.)  We also have to sort
+  ;; out a possible prefix -- well, we don't _have_ to, but I think it
+  ;; should be treated as part of the string.
+
+  ;; Test cases:
+  ;;  ur"""ar""" x='"' # """
+  ;; x = ''' """ ' a
+  ;; '''
+  ;; x '"""' x """ \ x
+  ;; Fixme:  "" goes wrong (due to syntax-ppss not getting the string
+  ;; fence context).
+  (save-excursion
+(goto-char (match-beginning 0))
+(cond
+ ;; Consider property for the last char if in a fenced string.
+ ((= n 3)
+  (let ((syntax (syntax-ppss)))
+   (when (eq t (nth 3 syntax)) ; after unclosed fence
+ (goto-char (nth 8 syntax)); fence position
+ (skip-chars-forward "uUrR")   ; skip any prefix
+ ;; Is it a matching sequence?
+ (if (eq (char-after) (char-after (match-beginning 2)))
+ (eval-when-compile (string-to-syntax "|"))
+ ;; Consider property for initial char, accounting for prefixes.
+ ((or (and (= n 2) ; leading quote (not prefix)
+  (= (match-beginning 1) (match-end 1))) ; prefix is null
+ (and (= n 1)  ; prefix
+  (/= (match-beginning 1) (match-end 1 ; non-empty
+  (unless (nth 3 (syntax-ppss))
+(eval-when-compile (string-to-syntax "|"
+ ;; Otherwise (we're in a non-matching string) the property is
+ ;; nil, which is OK.
+ )))
+
+
 (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
 
 ;; have to bind py-file-queue before installing the kill-emacs-hook
@@ -1189,7 +1246,10 @@
   (setq major-mode  'python-mode
mode-name   "Python"
local-abbrev-table  python-mode-abbrev-table
-   font-lock-defaults  '(python-font-lock-keywords)
+font-lock-defaults'(python-font-lock-keywords nil nil nil nil
+(font-lock-syntactic-keywords
+ . python-font-lock-syntactic-keywords))
+
paragraph-separate  "^[ \t]*$"
paragraph-start "^[ \t]*$"
require-final-newline   t


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


Re: IDE Question

2008-10-18 Thread Pat

Steve Phillips wrote:

Hi All,
I am just wondering what seems to be the most popular IDE. The reason
I ask is I am currently at war with myself when it comes to IDE's. It
seems like every one I find and try out has something in it that
others don't and viceversa. I am in search for the perfect IDE and
after many months of searching, I always come back to IDLE to do what
I need to do. I want to use Komodo badly but the one issue I have with
that is sometimes the auto-complete works and other times it doesn't.
Even if I carbon copy a script.

Thanks in advance,
Steve P


I've been using Wing IDE Pro for about a month or two and I'm very 
satisfied with it.


Is it "perfect"?  No.  However, I've been communicating the developers 
on some of the minor shortcomings of Wing and they've been extremely 
responsive.  I usually get a return email within a few hours sometimes 
minutes.


The nice thing is that you can download and try a completely 
non-crippled version for 30 days (10 days at a time).


What I particularly like about it is that it's for Python only.  I find 
Wing much easier to use than Eclipse and, thankfully, it's not written 
in Java which seems to takes Eclipse all day to load.


The integrated Python shell recognizes your variables so while you're 
debugging you can interact with your code.


I could go on, but I've got to get back to work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode File Names

2008-10-18 Thread Mark Tolonen


"Jordan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

l = os.listdir(unicode(os.getcwd()))


Other options to get the same result:

l = os.listdir(os.getcwdu())
l = os.listdir(u'.')

Oddly, os.getcwd() and os.getcwdu() both still exist in Python 3.0.   Since 
the behavior is now identical it seems os.getcwdu() should be dropped.


-Mark

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


better scheduler with correct sleep times

2008-10-18 Thread qvx
I need a scheduler which can delay execution of a
function for certain period of time.
My attempt was something like this:

def delay(self, func, arg, delay_sec=0):
fire_at = wallclock() + delay_sec
self.queue.put((fire_at, func, arg))

def runner(self):
while self.alive:
fire_at, func, arg = self.queue.get(block=True)
try:
now = wallclock()
if now < fire_at:
time.sleep(fire_at - now)
func(arg)
except Exception, e:
log('DelayedTaskManager %s: %s\n' % (self.name, e))
finally:
self.queue.task_done()

But then I came up with the following case:

1. I call delay with delay_sec = 10
2. The scheduler goes to sleep for 10 seconds
3. In the meantime (lets say 1 second later) I delay
   another func but this time with delay_sec=0.5
4. The scheduler is sleeping and won't know call my
   second function for another 9 seconds insted of 0.5

I started googling for scheduler and found one in standard library
but ih has the same code as mine (it calls the  functions in the
right order and my doesn't, but it still waits too long).
The other schedulers from web are dealing with
repeating tasks and such.

So, I wrote this:

# modification of http://code.activestate.com/recipes/87369/
class PriorityMinQueue(Queue):
def top(self):
try:
return self.queue[0]
except IndexError:
return None
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _put(self, item):
return heappush(self.queue, item)
def _get(self):
return heappop(self.queue)

class DelayedTaskManager:

def __init__(self, name):
self.name = name
self.queue = PriorityMinQueue()
# can't use queue.not_empty condition because it isn't
# signaled with notifyAll so I have to use my own
self.sleeper = threading.Condition()

def start(self):
log('start delayed task manager %s with %d elements\n' %
(self.name, self.queue.qsize()))
self.alive = True
self.thread = threading.Thread(target=self.runner)
self.thread.setDaemon(True)
self.thread.start()

def stop(self):
log('stop delayed task manager %s with %d elements\n' %
(self.name, self.queue.qsize()))
self.alive = False
self._wake()
self.thread.join()

def delay(self, delay_sec, func, *arg, **kw):
# even if delay is 0 or less, put to queue
# so the function gets executed concurrently
fire_at = wallclock() + delay_sec
self.queue.put((fire_at, func, arg, kw))
self._wake()

def _wake(self):
with self.sleeper:
self.sleeper.notify()

def _wait(self, timeout):
with self.sleeper:
self.sleeper.wait(timeout)

def runner(self):
while self.alive:
fire_at, func, arg, kw = self.queue.get(block=True)
try:
now = wallclock()
while now < fire_at:
self._wait(fire_at - now)
if not self.alive: # canceled
log('delayed task manager %s was stoped\n',
self.name)
return self.queue.put((fire_at, func, arg,
kw))
top = self.queue.top()
if top is not None and top[0] < fire_at:
# temporally closer item, put back the old one
self.queue.put((fire_at, func, arg, kw))
self.queue.task_done()
fire_at, func, arg, kw = self.queue.get()
now = wallclock()
func(*arg, **kw)
except Exception, e:
log('delayed task manager %s: %s\n', self.name, e)
finally:
self.queue.task_done()


Is there a better way or some library that does that?

My observations:

1. Threading module uses time.sleep instead of time.clock
   which results in less precise results (on windows platform)

if sys.platform=="win32":  #take care of differences in clock
accuracy
wallclock = time.clock
else:
wallclock = time.time

2. while analyzing threading module i noticed that wait() is
   implemented via loop and tiny sleep periods. I was expecting
   the usage of underlaying OS primitives and functions but
   then I remembered about GIL and quasi-multithreaded nature
   of Python. But still, isn't there a more precise method
   that interpreter itself could implement?

Thanks,
Tvrtko

P.S. This was Python 2.5
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pan/Zoom with Matplotlib

2008-10-18 Thread Czenek

On Oct 18, 1:48 am, Czenek <[EMAIL PROTECTED]> wrote:
> Hi,
> can I use somehow standard matplotlib's functions pan/zoom? I would
> like to zoom my created graph after double-clicking and move with it
> after keyboard (arrow) pressing (similar as Google Maps). And I want
> also to control how much it zooms and how far is the graph moved after
> pressing a key (or double-clicking).
> So are there any appropriate API functions which can be connected with
> keyboard and mouse events?
>
> Thanks
> Czenek
>
> PS: I'd like to use it with tk.



And

import matplotlib as mpl
f=mpl.figure(figsize(5,5),dpi=100)
sbplt=f.add_subplot(111)

...

while 1:
   x1,x2=sbplt.get_xlim()
   y1,y2=sbplt.get_ylim()
   sbplt.set_xlim(x1+0.1,x2+0.1)
   sbplt.set_ylim(y1+0.1,y2+0.1)
   f.canvas.draw()


this works pretty well on Linux, but the movement on Windows is slow
and therefore it is not smooth.

Any advice for better smoothness?

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


Re: loops

2008-10-18 Thread Aaron Brady
Gandalf wrote:

> On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
> wrote:
>> Gandalf <[EMAIL PROTECTED]> wrote:
>> > how can I do width python a normal for loop width tree conditions like
>> > for example :
>>
>> > for x=1;x<=100;x+x:
>> >     print x
>>
>> What you wrote would appear to be an infinite loop so I'll assume you meant
>> to assign something to x each time round the loop as well. The simple
>> Python translation of what I think you meant would be:
>>
>> x = 1
>> while x <= 100:
>>    print x
>>    x += x
>>
>> If you really insist on doing it with a for loop:
>>
>> def doubling(start, limit):
>>     x = start
>>     while x <= limit:
>>         yield x
>>         x += x
>>
>> ...
>>
>> for x in doubling(1, 100):
>>     print x
>
> I was hopping to describe it with only one command. most of the
> languages I know use this.
> It seems weird to me their is no such thing in python. it's not that I
> can't fined a solution it's all about saving code

Do you anticipate reusing it?  You could make something a little more
extendable.

for x in iexpression( 'x', 1, 100, 'x+x' ):
print x

or

for x in iexpression( lambda x: x+x, 1, 100  ):
print x

I'm assuming you don't want or have a closed form, in this case x= 2**
_x.

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


Re: loops

2008-10-18 Thread robert

Gandalf wrote:

On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:

Gandalf <[EMAIL PROTECTED]> wrote:

how can I do width python a normal for loop width tree conditions like
for example :
for x=1;x<=100;x+x:
print x

What you wrote would appear to be an infinite loop so I'll assume you meant
to assign something to x each time round the loop as well. The simple
Python translation of what I think you meant would be:

x = 1
while x <= 100:
   print x
   x += x


..


I was hopping to describe it with only one command. most of the
languages I know use this.
It seems weird to me their is no such thing in python. it's not that I
can't fined a solution it's all about saving code


You'd not save code, but only lines (and clearness). You'd also 
need more (non-space) characters


Python saves confusion and arbitrariness => you'll usually code 
faster, because you don't think so much about voluptuous 
multimulti..possibilites, not worth the play: one-ness of mind


If insistent, you could sometimes save lines like this ;-)

x=1
while x<=100:  print x; x+=x


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


Re: loops

2008-10-18 Thread Gandalf
On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> Gandalf <[EMAIL PROTECTED]> wrote:
> > how can I do width python a normal for loop width tree conditions like
> > for example :
>
> > for x=1;x<=100;x+x:
> >     print x
>
> What you wrote would appear to be an infinite loop so I'll assume you meant
> to assign something to x each time round the loop as well. The simple
> Python translation of what I think you meant would be:
>
> x = 1
> while x <= 100:
>    print x
>    x += x
>
> If you really insist on doing it with a for loop:
>
> def doubling(start, limit):
>     x = start
>     while x <= limit:
>         yield x
>         x += x
>
> ...
>
> for x in doubling(1, 100):
>     print x

I was hopping to describe it with only one command. most of the
languages I know use this.
It seems weird to me their is no such thing in python. it's not that I
can't fined a solution it's all about saving code
--
http://mail.python.org/mailman/listinfo/python-list


Re: loops

2008-10-18 Thread Gandalf
On Oct 18, 12:39 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> Gandalf <[EMAIL PROTECTED]> wrote:
> > how can I do width python a normal for loop width tree conditions like
> > for example :
>
> > for x=1;x<=100;x+x:
> >     print x
>
> What you wrote would appear to be an infinite loop so I'll assume you meant
> to assign something to x each time round the loop as well. The simple
> Python translation of what I think you meant would be:
>
> x = 1
> while x <= 100:
>    print x
>    x += x
>
> If you really insist on doing it with a for loop:
>
> def doubling(start, limit):
>     x = start
>     while x <= limit:
>         yield x
>         x += x
>
> ...
>
> for x in doubling(1, 100):
>     print x

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


Re: loops

2008-10-18 Thread Duncan Booth
Gandalf <[EMAIL PROTECTED]> wrote:

> how can I do width python a normal for loop width tree conditions like
> for example :
> 
> for x=1;x<=100;x+x:
> print x
> 

What you wrote would appear to be an infinite loop so I'll assume you meant 
to assign something to x each time round the loop as well. The simple 
Python translation of what I think you meant would be:

x = 1
while x <= 100:
   print x
   x += x

If you really insist on doing it with a for loop:

def doubling(start, limit):
x = start
while x <= limit:
yield x
x += x

...

for x in doubling(1, 100):
print x

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


loops

2008-10-18 Thread Gandalf
how can I do width python a normal for loop width tree conditions like
for example :

for x=1;x<=100;x+x:
print x


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


(relative) import trouble, sometimes it works, sometimes it doesn't ...

2008-10-18 Thread Stef Mientki

hello,

I'm running Python 2.5 and want my programs to run at least under 
Windows and Linux (preferable also Mac).

So I guess I should always use relative paths.

From most modules I can call a global function,
that should import a dictionary from path deeper than the module itself.
The import is done in the global function.
In that global function, I get the modules path by

 SourceFile = sys._getframe(1).f_code.co_filename

now to be sure to succeed the import (at least I was thinking this would 
always be successful  :-(

I need to
1- add the path of the module to be imported to sys.path
(or do a dot import)
2- keep track of already done imports, to give a reload the next time
(or maybe always do an import followed by an reload ?)

Now what I don't understand is what relative path should I use in 1:
- relative to the main application
- relative to the working directory were I started the application
- relative to the current working directory
- relative to the module that is doing the import
- relative to the module that called the global function

I would be pleased if someone could enlighten me,
because this information is hard to find.

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


Re: Unicode File Names

2008-10-18 Thread John Machin
On Oct 18, 5:57 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Should the note be removed, or should it say something like "Unicode
> > file names are supported. New in Python 2.6."? Is there anything else
> > that should be mentioned?
>
> The note should be corrected, documenting the behaviour implemented.
>
> > More on cp437: I see where you mentioned to the patch author that a
> > unicode string should be encoded in cp437 if possible, but this was
> > not done -- it first tries ascii. What are your views on what encoding
> > should be assumed if the utf8 flag is not set?
>

[lots of enlightenment snipped]

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


Re: inserting Unicode character in dictionary - Python

2008-10-18 Thread Martin v. Löwis
> 2. Exactly what Unicode you get would be dependent on Python properly
> interpreting the bytes in the source file -- which you can make it do by
> adding something like "-*- coding: utf-8 -*-" in a comment at the top of
> the file.

That depends on the Python version. Up to (and including) 2.4, the bytes
on the disk where interpreted as Latin-1 in absence of an encoding
declaration. In 2.5, not having an encoding declaration is an error. In
3.x, in absence of an encoding declaration, the bytes are interpreted as
UTF-8 (giving an error when ill-formed UTF-8 sequences are encountered).

> 3. Without the "u" prefix, you'll have some 8-bit string, whose
> interpretation is... er... here's where I get a bit fuzzy.  What if your
> source file is set to utf-8?

You need to distinguish between the declared encoding, and the intended
(editor) encoding also. Some editors (like Emacs or IDLE) interpret the
declaration, others may not. What you see on the display is the editor's
interpretation; what Python uses is the declared encoding.

However, Python uses the declared encoding just for Unicode strings.

> Do you then have a proper UTF-8 string,
> but the problem is that none of the standard Python library methods know
> how to properly interpret UTF-8?

There is (probably) no such thing as a "proper UTF-8 string" (in the
sense in which you probably mean it). Python doesn't have a data type
for "UTF-8 string". It only has a data type "byte string". It's up to
the application whether it gets interpreted in a consistent manner.
Libraries are (typically) encoding-agnostic, i.e. they work for UTF-8
encoded strings the same way as for, say, Big-5 encoded strings.

> 4. In Python 3.0, this silliness goes away, because all strings are
> Unicode by default.

You still need to make sure that the editor's encoding and the declared
encoding match.

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


Re: Unicode File Names

2008-10-18 Thread Martin v. Löwis
> Should the note be removed, or should it say something like "Unicode
> file names are supported. New in Python 2.6."? Is there anything else
> that should be mentioned?

The note should be corrected, documenting the behaviour implemented.

> More on cp437: I see where you mentioned to the patch author that a
> unicode string should be encoded in cp437 if possible, but this was
> not done -- it first tries ascii. What are your views on what encoding
> should be assumed if the utf8 flag is not set?

There isn't any standard that is widely followed (just as the note that
you declared bafflegab says). While APPNOTE.TXT specifies it as cp437,
implementations often ignore that, because a) they didn't know, and b)
cp437 was too limited for what they want to do. So we see all kinds of
alternative implementations - often involving the locale's code page
(and on Windows, both OEMCP and ACP get used - often just as a side
effect of whatever internal representation the applications use).

In 2.x, Python doesn't need to decide, so when opening a zip file, the
file names get reported as byte strings unless they have the UTF-8
bit set (in which case they get decoded). In 3.x, file names (in the
zipfile module) uniformly use the (unicode) character string type, hence
that version implements the spec, by decoding as 437.

Upon encoding, chosing between ASCII and CP437 has trade-offs. Notice
how both are formally complying to the spec, as ASCII is a subset of
CP437 (i.e. even though it uses the ASCII codec, it *still* encodes
as CP437). The tradeoffs can be studied by looking at three groups
of file names:
- pure ASCII; choice does not matter (both ascii and cp437 can
  encode the file name, and both get the same result)
- arbitrary string containing non-CP437 characters; choice does
  not matter (neither ascii nor cp437 can encode, so the UTF-8
  bit must be used)
- others; here are the tradeoffs. Pro ASCII: receiver can unambiguously
  reproduce the original file name, as the UTF-8 bit will be set.
  Pro CP437: old software (unaware of the UTF-8 bit) has a chance
  of correctly guessing the file name (if it followed APPNOTE.TXT).

I (now) prefer the tradeoff being taken, as it's the one that
produces more reliable results in the long run (i.e. when more
and more zip readers support UTF-8).

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