ANN: unicode 0.4.9

2006-01-01 Thread garabik-news-2005-05

unicode is a simple python command line utility that
displays properties for a given unicode character, or searches
unicode database for a given name.

It was written with Linux in mind, but should work
almost everywhere (including MS Windows and MacOSX), 
UTF-8 console is recommended.

Changes since previous versions:

  * better directional overriding for RTL characters
  * query wikipedia with -w switch
  * better heuristics guessing argument type

Author:
Radovan Garabík 

URL:
http://kassiopeia.juls.savba.sk/~garabik/software/unicode/

License:
GPL

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Hypergeometric distribution

2006-01-01 Thread Steven D'Aprano
On Sat, 31 Dec 2005 16:24:02 -0800, Raven wrote:

 Thanks to all of you guys, I could resolve my problem using the
 logarithms as proposed by Robert.  I needed to calculate the factorial
 for genomic data, more specifically for the number of genes in the
 human genome i.e. about 30.000 and that is a big number :-)
 I didn't know gmpy
 Thanks a lot, really

Are you *sure* the existing functions didn't work? Did you try them?

 def log2(x):
... return math.log(x)/math.log(2)
...
 n = 0.0
 for i in range(1, 30):  # ten times bigger than you need
... n += log2(i)
...
 n
5025564.6087276665
 t = time.time(); x = 2L**(int(n) + 1); time.time() - t
0.26649093627929688

That's about one quarter of a second to calculate 300,000 factorial
(approximately), and it shows that the calculations are well within
Python's capabilities.

Of course, converting this 1.5 million-plus digit number to a string takes
a bit longer:

 t = time.time(); len(str(x)); time.time() - t
1512846
6939.3762848377228

A quarter of a second to calculate, and almost two hours to convert to a
string. Lesson one: calculations on longints are fast. Converting them to
strings is not.

As far as your original question goes, try something like this:

(formula from memory, may be wrong)

 def bincoeff(n,r):
... x = 1
... for i in range(r+1, n+1):
... x *= i
... for i in range(1, n-r+1):
... x /= i
... return x
...
 bincoeff(10, 0)
1
 bincoeff(10, 1)
10
 bincoeff(10, 2)
45
 bincoeff(10, 3)
120
 import time
 t = time.time(); L = bincoeff(3, 7000); time.time() - t
28.317800045013428

Less than thirty seconds to calculate a rather large binomial coefficient
exactly. How many digits?

 len(str(L))
7076

If you are calculating hundreds of hypergeometric probabilities, 30
seconds each could be quite painful, but it certainly shows that Python is
capable of doing it without resorting to logarithms which may lose some
significant digits. Although, in fairness, the log function doesn't seem
to lose much accuracy for arguments in the range you are dealing with.


How long does it take to calculate factorials?

 def timefact(n):
... # calculate n! and return the time taken in seconds
... t = time.time()
... L = 1
... for i in range(1, n+1):
... L *= i
... return time.time() - t
...
 timefact(3000)
0.054913997650146484
 timefact(3)  # equivalent to human genome
5.069951057434082
 timefact(30)  # ten times bigger
4255.2370519638062

Keep in mind, if you are calculating the hypergeometric probabilities
using raw factorials, you are doing way too much work.


-- 
Steven.

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


Re: IDE for Python ?

2006-01-01 Thread Ravi Teja

[EMAIL PROTECTED] wrote:
 I'm getting realy tired of learning new languages.
 And especially frustrated at the 'syntax errors' when switching
 between them.

 There are basically only a few common concepts needed for
 all the languages.   Hence linux's p2c: Pascal to C translator.

 A good IDE could hide the irrelevant details of the syntax,
 much like DOS/Norton-commander--Linux/mc hides the
 details, and makes visual, the common actions on files:
 move, copy, view ...edit ...search etc.

 Besides, I guess Python itself would be good to make such
 an IDE ?   Is there any such tool available/recomended ?

 == Chris Glur.

You obviously have not learnt many languages. First you have a very
wrong notion that all languages are very similar. Pascal and C are
similar languages (Hence P2C, BCX etc). But Pascal and C do not
constitute *all* languages. There is a world of a difference between
(Lisp and C) or (Haskell and Pascal) or (Prolog and Javascript). The
differences between languages is not syntax but the theory and the
favored model of solving problems behind them. Java, for example favors
problem decomposition into objects. Lisp primarily decomposes problems
to lists. Prolog to rules. Haskell to functions etc. Model
representation (syntax) is secondary to this model.

It is possible to represent problems at a higher level for a given
model. For example OOP models can be represented in UML. MDA attempts
to create executable programs based on these abstract models. These
typically succeed only in well defined domains as 4GL tools.

Can there be a common rendition between models of all languages? Yes.
It is called machine code / byte code and it does not *hide* details
from you. It is the detail. That is the marketing buzz behind .NET's
CLR. Similarly there are about 200 languages / mini languages that
compile to Java byte code.

There have been attempts to create point and click tools for low level
programming constructs like if clauses and for loops in the past. I
came across atleast one for Java. I cannot remember the name now.
Needless to say, none have succeeded.

In short, there is no escape. If you want to create software, you must
learn languages. The more you know (from different models), the better
software you create, even if you can't use them all.

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


Re: Python article in Free Software Magazine

2006-01-01 Thread bonono

Steven D'Aprano wrote:
 On Sat, 31 Dec 2005 14:42:36 -0600, Kirk Strauser wrote:

  I wrote this article which was published in Free Software Magazine:
 
  http://www.freesoftwaremagazine.com/free_issues/issue_09/intro_zope_1/
 
  It's intended as a high-level overview of the language, and therefore
  glosses over some of the details.  For example, I describe its function
  calling mechanism as pass-by-reference, because that's close enough for
  newcomers to get the gist of it.

 Then what you are describing is not Python, it is some mythical language
 that is almost like Python, but just enough like C to confuse programmers
 who think they have discovered a bug when the following doesn't work:

 def increment(n, inc=1):
 n += inc

 n = 1
 increment(n)
 assert n == 2
I assume you mean C++, not C. As in C

int n=1;
void increment(int *n)
{
  n+=1
}
assert(n==2);  /* this one would fail */

Behave exactly like your sample.


 I don't want to nit-pick all my way through the article, which
 is very decent and is worth reading, but I will say one more thing: you
 describe Python as an expressive, interpreted language. Python is no
 more interpreted than Java. Like Java, it is compiled into byte-code which
 is then executed by a virtual machine. It has a separate compilation and
 execution step.

 (Amazing how the Java virtual machine is one of the great buzz-word
 selling features of the language, and yet Python people take it utterly
 for granted.)

 We both know that rational people shouldn't care about the difference
 between compilers and interpreters: it is performance that counts, not
 how you get it. We know that Python doesn't literally analyse the source
 code over and over again, and no major interpreted language has done this
 for probably two decades or more. We can argue about the differences
 between interpretation, tokenization, compilation and execution, and
 pedants like me will mention that machine code is interpreted by the CPU.

 But sadly, many decision makers don't understand these subtleties. To
 them, compiled languages like C++ and Java are Good, interpreted languages
 are Bad and doomed to be slow and weak. As soon as you describe
 Zope/Python as interpreted, you turn off maybe 25% or 50% of the Pointy
 Haired Bosses who are making the decision of what technologies are used.

I don't see that as a problem. In fact, it alarms them the right way.
For those who don't care(I met many who don't, so long the technology
delivers the end result, they don't want to know the difference or the
buzz words), it doesn't matter. For those who knows a little bit(even
not the detail) and care, this interpreted term gives them the right
reason to ask :

1. would that be slow ?
2. does it mean the source cannot be reasonably seperated from the end
product ?

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


Re: Python article in Free Software Magazine

2006-01-01 Thread Dan Sommers
On Sun, 01 Jan 2006 18:06:10 +1100,
Steven D'Aprano [EMAIL PROTECTED] wrote:

 I don't want to nit-pick all my way through the article, which is very
 decent and is worth reading, but I will say one more thing: you
 describe Python as an expressive, interpreted language ...

So does http://www.python.org/doc/Summary.html.

Regards,
Dan

-- 
Dan Sommers
http://www.tombstonezero.net/dan/
-- 
http://mail.python.org/mailman/listinfo/python-list


Numeric RandomArray seed problem

2006-01-01 Thread [EMAIL PROTECTED]
Hello,

I tried calling RandomArray.seed()
by calling RandomArray.get_seed() I get the seed number (x,y).
My problem is that x is always 113611 any advice?

Thanks
pujo

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


Re: Application architecture (long post - sorry)

2006-01-01 Thread Ernst Noch
[EMAIL PROTECTED] wrote:
 Hi all,
 
 I want to create a mobile field worker data solution.
 
 Let me explain...
 
 I work for a company that has some software used by call takers to
 enter information into a database about faults with electrical
 appliances they manufacture, sell to customers, and then provide
 maintenance contracts for.
 
 The company has a number of field workers (growing number) servicing
 these appliances, and information about the faults and customer
 locations is fed to them by printing off job sheets from the call
 taking system and then either faxing them to the engineers or the
 engineers drop in to the office and collect them.
 
 There are lots of problems with this, such as lost job information,
 incomplete forms, incorrect non validated data, the cost of printing
 off job sheets and also the engineers having to collect, regular phone
 calls to the engineers to update them on call informtion, and then the
 fact that all this data then has to be inputted back into another
 system manully.
 
 Basically I want to create a means of getting this data to them
 electronically.
 
 I know there are a few companies who could provide this solution but
 they are very expensive and possibly overkill at the moment, we could
 start developing our own basic system then it can grow over time.

Just one advise from my personal experience:

Don't build it yourself.

This part of your company seems to be growing, and a number of 60 field 
engineers is already considerable.
So, processes will change, managers will ask for specific KPIs, the need 
will come up to dispatch engineers based on their location/skillset etc. 
etc.
You might run into technical problems with the client appliances 
(compability) if you don't do extensive testing.
So, soon a commercial application might not be overkill anymore, but you 
already have a Big Ball of Mud sitting there.
( http://www.laputan.org/mud/mud.html#PiecemealGrowth )

All in all you should at least do a careful cost comparison between 
commercial off-the-shelf software (COTS) and inhouse development for
the next 3 to 5 years.
Don't understimate testing and training costs and the change of your 
business.

I could see two alternatives:
1. Buy a COTS package which has the big additional benefit of being 
implemented for some tried and tested processes, so that your company 
doesn't have to reeinvent their processes from scratch (it worked with 
SAP, didn't it ;) )
2. Go the super cheap route, like buying a blackberry package from a 
local mobile provider and send the jobs to the engineers via email.
The neat thing is that it pushes out the mails to the clients.
Maybe there are also some ready made packages to implement some forms on 
the blackberry's email client.
That way, you have the alternative of cheaply learning how things go in 
practice, and refine the requirements.







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


Line replace

2006-01-01 Thread DarkBlue
Hello

  I need some help

  I have a text file which changes dynamically and has
  200-1800 lines. I need to replace a line , this line
  can be located via a text marker like :

  somelines
  # THIS IS MY MARKER
  This is the line to be replaced
  somemorelines
  
  My question is how to do this in place without
  a temporary file , so that the line after
  the marker is being replaced with mynewlinetext.



Thanks
Nx

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


Re: Python article in Free Software Magazine

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 06:09:14 -0500, Dan Sommers wrote:

 On Sun, 01 Jan 2006 18:06:10 +1100,
 Steven D'Aprano [EMAIL PROTECTED] wrote:
 
 I don't want to nit-pick all my way through the article, which is very
 decent and is worth reading, but I will say one more thing: you
 describe Python as an expressive, interpreted language ...
 
 So does http://www.python.org/doc/Summary.html.

Then it is time it stopped.

In fairness, from a technical perspective, describing Python as
interpreted is not wrong -- as I've pointed out, machine code is
interpreted too -- but neither does it give the correct impression.
Many people have argued that the terms interpreted and compiled are no
longer meaningful in this day and age. I wouldn't go that far, but given
the negative connotations of interpreted I think it is both better and
more accurate to emphasis the fact that Python code is byte-code compiled
and only use the I-word when discussing Python's interactive environment
and eval/exec. If I could think of another word for interpreter, I would
use it even then.

People who are smart and care about correctness -- the reality-based
community -- often don't realise just how many decisions are made on the
basis of unfacts like everybody knows interpreted languages are slow and
inefficient, that's what my professor told me when I did a semester of C
in 1982, we better stick to Java or .Net.



-- 
Steven.

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


Re: Python article in Free Software Magazine

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 02:55:01 -0800, bonono wrote:

 But sadly, many decision makers don't understand these subtleties. To
 them, compiled languages like C++ and Java are Good, interpreted languages
 are Bad and doomed to be slow and weak. As soon as you describe
 Zope/Python as interpreted, you turn off maybe 25% or 50% of the Pointy
 Haired Bosses who are making the decision of what technologies are used.
 
 I don't see that as a problem. In fact, it alarms them the right way.
 For those who don't care(I met many who don't, so long the technology
 delivers the end result, they don't want to know the difference or the
 buzz words), it doesn't matter. For those who knows a little bit(even
 not the detail) and care, this interpreted term gives them the right
 reason to ask :
 
 1. would that be slow ?
 2. does it mean the source cannot be reasonably seperated from the end
 product ?

Dude, if they had the sense to ask the question Will this be slow? they
won't be a PHB now will they? :-)

They should be asking these questions about *any* technology. If you care
about keeping your algorithms secret, you should be asking about source
code, and debugging information, and how easily can attackers disassemble
your code, not just assuming oh it is compiled, it will be fine. If you
care about speed, and let's face it, we all care about speed, you should
ask how fast the code will run regardless of what language it is written
in. I can write C code that will run slower than Python code, and take
longer to do it too.

I'm not worried about people having the sense to judge Python on its
merits. If Python is not suited for a particular job, then we would not
be doing anyone any favours to push Python for that job. I'm worried
about people who pre-judging (as in prejudice) Python negatively on the
basis of buzzwords they barely understand.



-- 
Steven.

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


Re: Line replace

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 19:31:38 +0800, DarkBlue wrote:

 Hello
 
   I need some help
 
   I have a text file which changes dynamically and has
   200-1800 lines. I need to replace a line , this line
   can be located via a text marker like :
 
   somelines
   # THIS IS MY MARKER
   This is the line to be replaced
   somemorelines
   
   My question is how to do this in place without
   a temporary file , so that the line after
   the marker is being replaced with mynewlinetext.

Let me see if I understand your problem... you need to edit a text file
in place at the same time that another process is also changing the file
in place? That's hard. You need some way to decide who gets precedence if
both you and the other process both try to change the same line
simultaneously.

I think the only way this is even half-doable will be if:

- the other process writing to the file only appends to the end of the
file, and does not try to write to the middle;

- the new line you are writing is the same length as the old line you are
replacing; 

- and you are running an operating system that allows two processes to
have simultaneous write access to a file.

What problem are you trying to solve by having simultaneous writes to the
same file? Perhaps there is another way.


-- 
Steven.

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


Re: Application architecture (long post - sorry)

2006-01-01 Thread Martin P. Hellwig
Mike Meyer wrote:
 [EMAIL PROTECTED] writes:
 I have looked at the options for developing the client for these
 electronic job sheets and have decided upon Microsoft Pocket PC and
 the .net compact framework.  It seems the easiest environment for
 developing and the PDA's can be obtained very cheaply as a package from
 a GSM/GPRS data carrier.
 
 That seems like overkill for this application.
 
 Problem 1 - Physical connectivity
 how would I make the actual network connection in to the server from
 the client
 Running a VPN connection over GPRS ?
 Connecting to the web on the client then using web services ?
 
 The physical connectivity isn't your worry. How you access it from
 software depends on your chosen platform.
 
 The above decisions probably depend on the answer to problem 2...
 How to connect to the data
 Or even simpler I could just export data for the engineers into XML or
 .csv files and expose them using a web server the client then just
 connects to the server and then downloads the job data , and uploads
 completed job information
 
 I've gone this route before, and this is why I say your .net solution
 looks like overkill. The phones that GSM providers *give away* have
 web browsers built into them, and it's been that way for years. No
 need for .net or Pocket PC or whatever on the mobile device - just get
 a web-enabled phone. This makes half the development trivial - you
 don't have to do *any* development on the mobile side of things.
cut
Somehow I immediately thought of the s60 platform, it even runs some 
form of python if you really need it to ;-)
http://www.s60.com/

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


Compressing folders in Windows using Python.

2006-01-01 Thread sri2097
Hi,
I'm trying to zip a particular fiolder and place the zipped folder into
a target folder using python. I have used the following command in
'ubuntu'.

zip_command = 'zip -qr %s %s' % (target, ' '.join(source))

I execute this using os.command(zip_command). It works fine...

But when I run this script in Windows XP, I get an error while
executing the above zip command. What command is there to zip files in
Windows? Or is there any other problem ?

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


Re: Line replace

2006-01-01 Thread Sam Pointon
Hello

  I need some help

  I have a text file which changes dynamically and has
  200-1800 lines. I need to replace a line , this line
  can be located via a text marker like :

  somelines
  # THIS IS MY MARKER
  This is the line to be replaced
  somemorelines

  My question is how to do this in place without
  a temporary file , so that the line after
  the marker is being replaced with mynewlinetext.

Thanks
Nx

You will either have to read the whole file into memory (at 1800 lines,
this shouldn't be too bad) or read piecementally from the input file,
write the processed output to a new file, delete the input file and
rename the new file to the original file (yes, that's using a temporary
file, but it'll be more memory friendly).

The first solution would look something like this:
#Untested
import sre
input_file = file('/your/path/here')
input_file_content = input_file.read()
input_file.close()
pat = sre.compile(r'^#THIS IS MY MARKER\n.*$')
mat = pat.search(input_file_content)
while mat:
input_file_content = pat.sub('New text goes here',
input_file_content)
mat = pat.search(input_file_content)
file('/your/path/here', 'w').write(input_file_content)

The second one might be cleaner to do using a shell script (assuming
you're on a *nix) - awk or sed are perfect for this type of job - but
the python solution will look like this:

#Untested
import os
input_file = file('/your/path/goes/here')
output_file = file('/tmp/temp_python_file', 'w')
marked = False
for line in input_file:
if line == '#THIS IS MY MARKER':
marked = True
elif marked:
output_file.write('New line goes here\n')
else:
output_file.write(line)
input_file.close()
os.system('rm /your/path/goes/here')
os.system('mv /tmp/temp_python_file /your/path/goes/here')

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


Re: Compressing folders in Windows using Python.

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 04:07:11 -0800, sri2097 wrote:

 Hi,
 I'm trying to zip a particular fiolder and place the zipped folder into
 a target folder using python. I have used the following command in
 'ubuntu'.
 
 zip_command = 'zip -qr %s %s' % (target, ' '.join(source))
 
 I execute this using os.command(zip_command). It works fine...
 
 But when I run this script in Windows XP, I get an error while
 executing the above zip command. 

Would you like to tell us what error you get?

No no, I'll just guess... your disk is full... am I close?

*wink*

 What command is there to zip files in Windows? Or is there any other problem ?

What happens if you call up a Windows command prompt and type zip at the
prompt?



-- 
Steven.

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


Re: Python article in Free Software Magazine

2006-01-01 Thread bonono

Steven D'Aprano wrote:
 I'm worried
 about people who pre-judging (as in prejudice) Python negatively on the
 basis of buzzwords they barely understand.
 
For those with prejudice, it doesn't matter anyway.

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


Re: Compressing folders in Windows using Python.

2006-01-01 Thread Heiko Wundram
Steven D'Aprano wrote:
 But when I run this script in Windows XP, I get an error while
 executing the above zip command.
 
 Would you like to tell us what error you get?

I presume the error he's seeing is something along the line of:

zip: Bad command or filename.

That's basically because there is no commandline builtin for zipping up
files on Windows, and I don't know of WinZIP or any of the InfoZIP derived
GUIs installing a command-line zipper.

What might help you though (and keep you platform-independent):

http://www.python.org/doc/2.4.2/lib/module-zipfile.html

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


Re: Compressing folders in Windows using Python.

2006-01-01 Thread Heiko Wundram
Heiko Wundram wrote:
 That's basically because there is no commandline builtin for zipping up
 files on Windows, and I don't know of WinZIP or any of the InfoZIP derived
 GUIs installing a command-line zipper.

btw. the zip command isn't builtin on Unix either. It's only available if
you installed the corresponding InfoZIP package(s). I know pretty much
every Linux-distribution comes preinstalled with it (because of stuff like
ark, a KDE-frontend for archivers, requiring it), but you shouldn't rely on
that either.

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


Re: Line replace

2006-01-01 Thread DarkBlue
Steven D'Aprano wrote:

 
 Let me see if I understand your problem... you need to edit a text file
 in place at the same time that another process is also changing the file
 in place? That's hard. You need some way to decide who gets precedence if
 both you and the other process both try to change the same line
 simultaneously.
 
 I think the only way this is even half-doable will be if:
 
 - the other process writing to the file only appends to the end of the
 file, and does not try to write to the middle;
 
 - the new line you are writing is the same length as the old line you are
 replacing;
 
 - and you are running an operating system that allows two processes to
 have simultaneous write access to a file.
 
 What problem are you trying to solve by having simultaneous writes to the
 same file? Perhaps there is another way.
 
 
Thanks for your reply.

I would have no problem to let other processes finish their
writing duty to the file and my script only gets access when
no other process is working with the file.
The file written to is the hosts.allow file which is 
changed often by the blockhosts.py script when
some ssh access is attempted. Now blockhosts.py works
great , but sometimes our mobile clients try to access
from ip addresses which are completely blocked to avoid the 
thousands of scripted attacks showing up in our logs.
Now our authorized clients register themselves automatically with
computername,id and ip address via a small python script which sends this
information to a firebird database on our server.
A serverside script scans the database ever so often and changes
the hosts.allow file to enable authorized clients to log on via ssh
if they have moved out of their original areas ( like traveling from 
china to india and logging in from a hotel room)

Most of the clients run Suse9.3 so does the server
some are wxp machines which get their ssh access via 
winscp or putty if needed.

Every client has a marker in the hosts.allow file
so if a change occurs one line shall be replaced 
by another line on the fly.

I hope this describes it.



Nx






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


f2py and common blocks /Carl

2006-01-01 Thread Carl
I have been experimenting with f2py and some fortran code that I want to
port to Python.

I have the following fortran file (TEST_00.f):

C FILE: TEST_00.f
  SUBROUTINE FOO(WORK)
  IMPLICIT REAL*8 (A-H, O-Z)
  COMMON /SIZES/ NINT
  DIMENSION WORK(NINT)
  DIMENSION USOL(NINT)
  DO 10 I=1,NINT
 WORK(I)=0.0
 PRINT *, In Fortran WORK(I)=, WORK(I)
 10   CONTINUE
  END
  DO 10 I=1,NINT
 USOL(I)=0.0
 PRINT *, In Fortran USOL(I)=, USOL(I)
 10   CONTINUE
  END
C END OF TEST_00.f

and the following signature file (generated by f2py TEST_00.f -m TEST_00 -h
TEST_00.pyf):

python module TEST_00 ! in
interface  ! in :TEST_00
subroutine foo(work) ! in :TEST_00:TEST_00.f
real*8 dimension(nint) :: work
integer optional,check(len(work)=nint),depend(work) ::
nint=len(work)
common /sizes/ nint
end subroutine foo
end interface
end python module TEST_00

When compiling (with f2py -c TEST_00.pyf TEST_00.f) I get the following
error message:

/tmp/tmpl75SQT/src/TEST_00module.c:149: error: `nint' undeclared (first use
in this function)

Question: How can one declare arrays passed as parameters via common block
variables?

Yours/ Carl




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


Re: Line replace

2006-01-01 Thread Paul Rubin
DarkBlue [EMAIL PROTECTED] writes:
 Now our authorized clients register themselves automatically with
 computername,id and ip address via a small python script which sends this
 information to a firebird database on our server...
 Every client has a marker in the hosts.allow file
 so if a change occurs one line shall be replaced 
 by another line on the fly.

Why don't you use the database to store those markers?  It should
support concurrent updates properly.  That's a database's job.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line replace

2006-01-01 Thread DarkBlue

 Why don't you use the database to store those markers?  It should
 support concurrent updates properly.  That's a database's job.
The markers are just there to have a static way to find the line
after the marker, which is the one which might have to be changed.

Nx

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


Re: Application architecture (long post - sorry)

2006-01-01 Thread limeydrink
In response to Mike's post...

I know exactly where you're coming from and you are right a web based
solution is the simplest and would be the fastest to develop and
rollout etc. but..

The cost is in the data, in the uk you get charged for the amount of
data you send/receive  by GPRS and this data you are paying for would
ideally be useful data and not the HTML to present it.

Engineers generally get the job information then fill in bits as they
go along, and also reveiew what has been done on the job at various
times throughout their work, this could mean alot of traffic moving
through data screens in a web based application.

The push capability of a full client could also be very useful.

The pocket PC hardware is very cheap, and this platform would provide a
good user experience with regards to screen size and means of inputting
the data.



In response to Ernst...

There hasn't been a full decision by management to spend lots of cash
on this as yet hence why I am making this sort of a pet project for my
self and spending mostly my own time, we will then hopefully trial it
with a few engineers and then see where it goes, you are right though,
the company ideally should invest in a full solution as in my opinion
there could be massive savings to the company both in money and time
and also improved service to customers, problem is management can take
a lot of convincing and they don't like spending money.

It would give me great satisfaction though to roll my own solution to
this and then at least prove the benefits to the company, even if just
to convince them to purchase a system from a vendor, and even if that
happens i will have learnt a lot in the process.

Thanks for your replies, they are much appreciated.

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


Re: Python article in Free Software Magazine

2006-01-01 Thread Ernst Noch
Steven D'Aprano wrote:
 On Sun, 01 Jan 2006 06:09:14 -0500, Dan Sommers wrote:
 
 
On Sun, 01 Jan 2006 18:06:10 +1100,
Steven D'Aprano [EMAIL PROTECTED] wrote:


I don't want to nit-pick all my way through the article, which is very
decent and is worth reading, but I will say one more thing: you
describe Python as an expressive, interpreted language ...

So does http://www.python.org/doc/Summary.html.
 
 
 Then it is time it stopped.
 
 In fairness, from a technical perspective, describing Python as
 interpreted is not wrong -- as I've pointed out, machine code is
 interpreted too -- but neither does it give the correct impression.
 Many people have argued that the terms interpreted and compiled are no
 longer meaningful in this day and age. I wouldn't go that far, but given
 the negative connotations of interpreted I think it is both better and
 more accurate to emphasis the fact that Python code is byte-code compiled
 and only use the I-word when discussing Python's interactive environment
 and eval/exec. If I could think of another word for interpreter, I would
 use it even then.
 
 People who are smart and care about correctness -- the reality-based
 community -- often don't realise just how many decisions are made on the
 basis of unfacts like everybody knows interpreted languages are slow and
 inefficient, that's what my professor told me when I did a semester of C
 in 1982, we better stick to Java or .Net.
 

Right on. Here's a tongue-in-cheek proposal for the python.org homepage 
to describe a combination of python, twisted and zope or something similar.
It yields a 10 on the buzzword meter, but is unfortunately blatantly stolen:


Today, more and more developers want to write distributed transactional 
applications for the enterprise and leverage the speed, security, and 
reliability of server-side technology. If you are already working in 
this area, you know that in today's fast-moving and demanding world of 
e-commerce and information technology, enterprise applications have to 
be designed, built, and produced for less money, faster, and with fewer 
resources than ever before.

To reduce costs and fast-track enterprise application design and 
development, the Python Platform Enterprise Edition technology provides 
a component-based approach to the design, development, assembly, and 
deployment of enterprise applications. The Python Enterprise platform 
gives you a multitiered distributed application model, the ability to 
reuse components, a unified security model, and flexible transaction 
control. Not only can you deliver innovative customer solutions to 
market faster than ever, but your platform-independent Python 
component-based solutions are not tied to the products and APIs of any 
one vendor.


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


Re: Line replace

2006-01-01 Thread Paul Rubin
DarkBlue [EMAIL PROTECTED] writes:
 The markers are just there to have a static way to find the line
 after the marker, which is the one which might have to be changed.

OK, why don't you store those changing lines in the database?

Can you arrange for those changeable lines to be fixed length, i.e.
by padding with spaces or something?  If you can, then you could just
overwrite them in place.  Use flock or fcntl (Un*x) or the comparable
Windows locking primitives to make sure other processes don't update
the file simultaneously.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging module example

2006-01-01 Thread Chris Smith
 One thing that made little sense to me when I was first working on
this is the following variation on the original script:

#--begin test script--
import logging

forest  = [root,trunk,branch,leaf]
lumber_jack = {forest[0] : logging.DEBUG
  ,forest[1] : logging.INFO
  ,forest[2] : logging.WARNING
  ,forest[3] : logging.ERROR  }
log_name= []
for log in forest:
mounty  = logging.FileHandler(%s%s.txt % (/home/smitty/mddl/,log))
log_name.append(log)
print Instantiating %s  % ..join(log_name)
timber  = logging.getLogger(..join(log_name))

#Comment out explit setting of level for logger
#timber.setLevel(lumber_jack[log])

#Commented out totally, called without argument, or called with
# logging.NOTSET all produce same output

#timber.setLevel(logging.NOTSET)
timber.addHandler(mounty)
if   lumber_jack[log] == logging.DEBUG:
timber.debug(  %s's a lumberjack, and he's OK. % log)
elif lumber_jack[log] == logging.INFO:
timber.info(   %s's a lumberjack, and he's OK. % log)
elif lumber_jack[log] == logging.WARNING:
timber.warning(%s's a lumberjack, and he's OK. % log)
elif lumber_jack[log] == logging.ERROR:
timber.error(  %s's a lumberjack, and he's OK. % log)
mounty.emit( logging.LogRecord( timber
  , 0
  , /mnt/dmz/proj/mddl4/mddl.py
  , 37
  , burp?
  , None
  , None   ))
#--end test script--

#---
#expected output
#---
$ cat root.txt
root's a lumberjack, and he's OK.
burp?
trunk's a lumberjack, and he's OK.
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
trunk's a lumberjack, and he's OK.
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?


#---
#actual output
#---
$ cat root.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?


#---
 At any rate, I see now that I want to use logging.setLevel() to lay
in my own, more descriptive, levels, and then the straight
logging.log() function to do that for me.
 Ah, the learning curve.
Best,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line replace

2006-01-01 Thread DarkBlue
 OK, why don't you store those changing lines in the database?
 
 Can you arrange for those changeable lines to be fixed length, i.e.
 by padding with spaces or something?  If you can, then you could just
 overwrite them in place.  Use flock or fcntl (Un*x) or the comparable
 Windows locking primitives to make sure other processes don't update
 the file simultaneously.

hmm , the line is actually being read from a database 
and now needs to be written into a file replacing
the line after the marker...
the line contains only an ip address

pseudocode is like this:

get newlinetext from database  # this is ok done with kinterbas
preferably check if file not in use by other process
open file and find desired marker
go to line after marker and replace that one with newlinetext
close the file

Should be easy, but I am suffering from New Year writer's block..

Nx

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


Re: python coding contest

2006-01-01 Thread Claudio Grondi
Claudio Grondi wrote:
 Please send me comments, suggestions and ideas.
 
 
 Now, after the contest is over I analysed the outcome of it and have 
 come to the conclusion, that there were two major factors which 
 contributed to squeezing of code:
 
   (1). usage of available variants for coding of the same thing
   (2). sqeezing the size of used numeric and string literals
 
 As (1) leads to less readable cryptic code it makes not much sense from 
 my point of view to dig deeper in that direction. As already mentioned 
 in this thread by Tim Peters ( pointing to 
 http://spoj.sphere.pl/problems/KAMIL/ ) it seems, that Pearl is here the 
 proper language of choice for such kind of problems anyway.
 
 Trying to improve on (2) belongs in my eyes much more into the area of 
 problems discussed in comp.compression than to problems belonging into 
 comp.lang.python .
 
 So what is my point? Ok, I will mention it at the end of this post.
 
 Before that I want to thank the originators of the contest and 
 especially the participants for providing insight into the techniques 
 they have used. I have learned from the contest what lambda expression 
 is good for and how it works  where I failed to grasp it from reading 
 tutorials only.
 
 I have detected, that it would be a nice thing to have in Python a 
 function able to convert values from binary string to an integer 
 representation as in my eyes both in case of long integer values are 
 more or less the same thing/object. The only difference is probably in 
 the header not in the representation of the actual value in memory - am 
 I right here? Will it make sense to have a string-integer object which 
 value can be used in both contexts as a binary string and a long integer 
 value?
 Is there in Python any simple way to do the same as the following two 
 following functions I have put together today:
 
 def longIntWithBitsOfBinaryString(stringToConvert):
   intWithBitsOfBinaryString = 0L
   for singleChar in stringToConvert:
 intWithBitsOfBinaryString = (intWithBitsOfBinaryString8) + 
 ord(singleChar)
   #:for
   return intWithBitsOfBinaryString
 #:def longIntWithBitsOfBinaryString(s)
 
 def binaryStringWithBitsOfLongInt(i):
   listOfCharsOfStringWithThePackedInt = []
   exponent = 1
   while i  256**exponent: exponent+=1
   for byteNo in range(0,exponent):
 noOfBitsToShift = byteNo*8
 
 listOfCharsOfStringWithThePackedInt.append(chr(inoOfBitsToShift0xFF))
   #:for
   # reverse (in place) in order to get the highest bits of the integer 
 as leftmost byte
   listOfCharsOfStringWithThePackedInt.reverse()
   stringWithThePackedInt = ''.join(listOfCharsOfStringWithThePackedInt)
   return stringWithThePackedInt
 #:def binaryStringWithBitsOfLongInt(i)
 
 print longIntWithBitsOfBinaryString('ABBA') = 
 %i%longIntWithBitsOfBinaryString('ABBA')
 print 
 binaryStringWithBitsOfLongInt(longIntWithBitsOfBinaryString('ABBA')) = 
 '%s'%binaryStringWithBitsOfLongInt(longIntWithBitsOfBinaryString('ABBA'))
 
 which gives:
 
 longIntWithBitsOfBinaryString('ABBA') = 1094861377
 binaryStringWithBitsOfLongInt(longIntWithBitsOfBinaryString('ABBA')) = 
 'ABBA'
 
 ?
 
 And now my point I have promised to write about:
 
 If squeezing code makes it bad code and compressing literals is more or 
 less compression technique and not Python programming, it is maybe a 
 good idea to try to explore what Python distribution provides as data 
 and modules and rewrite the  seven_seg  module, but with following 
 limitations:
 
 1. it is not allowed to use any literals in the provided code
 2. it is not allowed to misuse the names of the identifiers as a kind of 
 literals providing data
 3. it is not allowed to use modules or files which doesn't come with the 
 Python distribution.
 
 I have no slightest idea if it is possible to program a  seven_seg 
 module under such conditions. It could be a sign, that it would be a 
 very interesting challenge worth to get involved into or a sign I have 
 no slightest idea about Python and programming.
 
 What do you all think about it?
 
 Claudio
After some coding trials, it turned out to be quite easy (almost 
trivial) to overcome the problem of not beeing allowed to use any 
literals in the script code, but I suppose, that I am not alone with not 
seeing directly how to code it, so it is maybe a good exercise for a 
Python beginner (like me) to cope a bit with it.
Knowing this I am curious if it is also comparable easy in other 
programming languages, e.g. when using only a C/C++ compiler and linker 
executables along with the provided libraries and header files? I 
suppose, that each language comes with built-in literals which can be 
utilized in own code to get the full range of required literals into 
identifiers by using only what the language provides itself.
Am I right or not?

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


Re: Global Variables in OOP and Python

2006-01-01 Thread Kay Schluehr

Steven D'Aprano wrote:
 On Fri, 30 Dec 2005 20:00:51 -0500, Mike Meyer wrote:


  The other way I thought of is to create a separate class that consists
  of the variables and to use the
 
  from file name import *
 
  in all of the files (namespaces) where it is needed.
 
  Except for one detail, this is a Pythonesque method. The detail is
  that from module import * is generally considered a bad
  idea. There are two reasons for this:

 Agree about from module import * being bad, but it is still generally poor
 practice for the same reason using global variables is generally poor
 practice.

No, I don't think so. The general wisdom is that global variables are
bad not because they are global, but because they are variable.
Responsibility about state mutation is scattered across the code and
spaghetti is the likely consequence. This cannot be prevented by
changing the access protocoll ( getters / setters ) or using static
variables. Mutable OO-singletons are not less harmfull than good old
globals.

Namespace pollution or name clashes are another issue and we have to
make a tradeoff between easeness of following references and namespace
security on the one hand conciseness on the other. I'm not completely
unhappy using True instead of  __builtins__.True allthough the
latter would be more pure.

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


Re: python coding contest

2006-01-01 Thread Claudio Grondi
Steven D'Aprano wrote:
 On Sun, 01 Jan 2006 03:34:33 +0100, Claudio Grondi wrote:
 
 
Please send me comments, suggestions and ideas.

Now, after the contest is over I analysed the outcome of it and have 
come to the conclusion, that there were two major factors which 
contributed to squeezing of code:

   (1). usage of available variants for coding of the same thing
   (2). sqeezing the size of used numeric and string literals
 
 
 [snip]
 
 
Is there in Python any simple way to do the same as the following two 
following functions I have put together today:
 
 
 They are already pretty simple. You can make them even more simple by
 using less complicated names and getting rid of the explicit end block
 markers. It is sometimes useful to put in explicit end block markers when
 you have long blocks, but when the block is just a single line, well,
 I don't see the point.
 
 Here is another possibility.
 
 
import array
A = array.array('b')
n = 100
while n:
 
  A.append(n255); n = n  8
  
 
A.reverse()
A
 
 array('b', [15, 66, 64])
 
15*256**2 + 66*256 + 64
 
 100
 
A.tostring()
 
 '\x0fB@'
 
 The reverse transformation is just as easy:
 
 
A = array.array('b', \x0fB@)  # initialise from a byte string
n = 0L
for b in A:
 
  n = n  8 | b
 
 
n
 
 100L
 
 And of course these can be turned into functions.
 
 
 
What I have thought about as a simpler/better solution is a method 
allowing to avoid processing the content of the string or long integer 
object by looping over its content. I suppose, that knowing enough about 
Python internals it must be possible to change only the object type not 
beeing forced to process the content i.e. the value itself, what in case 
of big size of data to convert with methods like this above wastes CPU 
time.

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


Re: Compressing folders in Windows using Python.

2006-01-01 Thread bren[at]gillatt.org
Heiko Wundram wrote:
 Steven D'Aprano wrote:
 
But when I run this script in Windows XP, I get an error while
executing the above zip command.

Would you like to tell us what error you get?
 
 
 I presume the error he's seeing is something along the line of:
 
 zip: Bad command or filename.
 
 That's basically because there is no commandline builtin for zipping up
 files on Windows, and I don't know of WinZIP or any of the InfoZIP derived
 GUIs installing a command-line zipper.
 
 What might help you though (and keep you platform-independent):
 
 http://www.python.org/doc/2.4.2/lib/module-zipfile.html
 
 --- Heiko.

Go and get something like 7-ZIP and put a path environment variable in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Tech Geekers and their Style

2006-01-01 Thread John W. Kennedy
Xah Lee wrote:
 With all the whizbang of styles and features in CSS2, a basic,
 necessary, functional layout feature as multi-columns is not there yet.
 This is a indication of the fatuousness of the IT industry's
 technologies and its people.

No, this is an indication of what happens to an industry paralyzed by 
organized crime and a corrupt government.

Microsoft delendum est.

-- 
John W. Kennedy
But now is a new thing which is very old--
that the rich make themselves richer and not poorer,
which is the true Gospel, for the poor's sake.
   -- Charles Williams.  Judgement at Chelmsford
-- 
http://mail.python.org/mailman/listinfo/python-list


Help please with binary file read

2006-01-01 Thread Stewart Arnold
I'm trying to convert a Real Basic routine into Python and I can't read the 
long integer data from a file.

Here is the Real Basic code:

 b=f.OpenAsBinaryFile
 b.LittleEndian=True
 i=b.ReadByte
 titles=b.ReadLong
 shows=b.ReadLong
 i=b.ReadLong

And here is my code:

 db = open('otter.db', 'rb')
 null = db.read(1)  # read empty byte
 titles = db.read(4)
 shows = db.read(4)
 null = db.read(1)  # read empty byte

 print titles

When I print titles I get ascii pictures. How do I convert 'titles' to an 
integer I can loop through?
Is db.read(4) correct for ReadLong?

Thanks!

PS. here's the file I'm working with http://otterprojectonline.info/otter.db



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


how to show Chinese Characters in the value set of a dictionary

2006-01-01 Thread zxo102
Hi there,
  I have a dictionary with values of Chinses Characters. For
example,

 dict = {}
 dict['c1']=中国一
 dict['c2']=中国二
 dict.values()
['\xd6\xd0\xb9\xfa\xb6\xfe', '\xd6\xd0\xb9\xfa\xd2\xbb']

Since the result of dict.values will be inserted into web pages and
handled by javascript there, I want to show Chinese Characters
in the list directly like this,

['中国一','中国二']

Anybody knows how to do this?   Thank you very much for your help.

Ouyang

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

Re: Python article in Free Software Magazine

2006-01-01 Thread Kirk Strauser
On Sunday 01 January 2006 01:06 am, Steven D'Aprano wrote:

 I don't want to nit-pick all my way through the article,

There's nothing wrong with that, and if I hadn't been prepared for it, I
wouldn't have posted the link in here.

You have fair points.  Unfortunately, though, the word length of the article
just didn't provide enough space to go into the level of detail those
subjects would have required.  I tried to compromise by giving the answer
that most closely fit the situation without being exactly correct.

By the way, the author style guides say to write for an audience with
technical background.  That article was meant for you, not your boss.  :-)
-- 
Kirk Strauser

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


Re: python coding contest

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 15:49:58 +0100, Claudio Grondi wrote:


 What I have thought about as a simpler/better solution is a method 
 allowing to avoid processing the content of the string or long integer 
 object by looping over its content. 

How can you avoid looping over its content? Whether you do it yourself
using for byte in array or similar, or Python does it for you
(using array.tostring perhaps), *something* has to walk through the bytes.

If you don't like walking the string, write a function to do it once, and
then use the function.

 I suppose, that knowing enough about 
 Python internals it must be possible to change only the object type not 
 beeing forced to process the content i.e. the value itself, what in case 
 of big size of data to convert with methods like this above wastes CPU 
 time.

I'm reminded of a time I was going for a drive in the country when I drove
past an apple orchid. Standing in the orchid was a farmer with a pig. He
lifted the pig into the air, and the pig then bit an apple and slowly
chewed it. The farmer then carried him over to another branch, and the pig
ate another apple.

I was so surprised I stopped my car and wandered over to ask the farmer
what he was doing.

I'm feeding apples to my pig, he replied.

Wouldn't it save time to just pick some apples and feed them to the pig?

The farmer looked at me like I was an idiot. What's time to a pig?


The moral of the story is, before spending time working on some scheme to
save CPU time, you better be absolutely sure that firstly, you are going
to save CPU time, secondly, that it is enough CPU time to be worth saving,
and thirdly, that you aren't wasting more of your own time to do it.



-- 
Steven.

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


Re: Help please with binary file read

2006-01-01 Thread Grant Edwards
On 2006-01-01, Stewart Arnold [EMAIL PROTECTED] wrote:

 I'm trying to convert a Real Basic routine into Python and I
 can't read the long integer data from a file.

http://docs.python.org/lib/module-struct.html

-- 
Grant Edwards   grante Yow!  Here I am in 53
  at   B.C. and all I want is a
   visi.comdill pickle!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global Variables in OOP and Python

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 06:48:48 -0800, Kay Schluehr wrote:

 Agree about from module import * being bad, but it is still generally poor
 practice for the same reason using global variables is generally poor
 practice.
 
 No, I don't think so. The general wisdom is that global variables are
 bad not because they are global, but because they are variable.
 Responsibility about state mutation is scattered across the code and
 spaghetti is the likely consequence. This cannot be prevented by
 changing the access protocoll ( getters / setters ) or using static
 variables. Mutable OO-singletons are not less harmfull than good old
 globals.

Now that you mention it, how obvious it is. That is good thinking,
thanks.



-- 
Steven.

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


Re: how to show Chinese Characters in the value set of a dictionary

2006-01-01 Thread Nikos Kouremenos
On Sun, 01 Jan 2006 07:35:31 -0800, zxo102 wrote:

 
 Hi there,
   I have a dictionary with values of Chinses Characters. For
 example,
 
 dict = {}
 dict['c1']=中国一
 dict['c2']=中国二
 dict.values()
 ['\xd6\xd0\xb9\xfa\xb6\xfe', '\xd6\xd0\xb9\xfa\xd2\xbb']
 
 Since the result of dict.values will be inserted into web pages and
 handled by javascript there, I want to show Chinese Characters
 in the list directly like this,
 
 ['中国一','中国二']
 
 Anybody knows how to do this?   Thank you very much for your help.
 
 Ouyang

 print [', dict.values()[0], '], [', dict.values()[1], ']
[' 中国二 '] [' 中国一 ']

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

Re: Line replace

2006-01-01 Thread Mike Meyer
DarkBlue [EMAIL PROTECTED] writes:
 pseudocode is like this:

 get newlinetext from database  # this is ok done with kinterbas
 preferably check if file not in use by other process
 open file and find desired marker
 go to line after marker and replace that one with newlinetext
 close the file

 Should be easy, but I am suffering from New Year writer's block..

This is only easy if the old and new data are exactly the same
size. In line oriented files, that's not normally the case.

The standard solution is to overwrite the entire file. Your code goes
like so:

 get lock on file.
 read in file.
 produce new version of file.
 write out file.
 release lock on file.

Of course, this has the problem that if someothing goes wrong during
the write you're going to be up the creek without a paddle - or much
in the way of a canoe. This is why experienced people always use a
temp file, and do things like so:

 get lock on file
 read in file
 produce new version of file in temp file
 rename temp file to real file
 release lock on file

I can't think of a good reason to skip using the temp file once you
have to write out the entire file.

If you can't deal with writing out the entire file, convert the file
from lines of text to something that can be update in place. It's not
clear how much else is going to have to change to deal with this,
though.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to show Chinese Characters in the value set of a dictionary

2006-01-01 Thread Diez B. Roggisch
zxo102 schrieb:
 Hi there,
   I have a dictionary with values of Chinses Characters. For
 example,
 
 
dict = {}
dict['c1']=中国一
dict['c2']=中国二
dict.values()
 
 ['\xd6\xd0\xb9\xfa\xb6\xfe', '\xd6\xd0\xb9\xfa\xd2\xbb']
 
 Since the result of dict.values will be inserted into web pages and
 handled by javascript there, I want to show Chinese Characters
 in the list directly like this,
 
 ['中国一','中国二']
 
 Anybody knows how to do this?   Thank you very much for your help.

I can see these chines characters very well - so I don't see why it 
won't work putting them into a HTML page. Just nake sure you use the 
proper encoding, most probably utf-8.

What put you off probably is the fact that in the interpreter, strings 
are printed using their __repr__-method, that puts out those funny 
hex-characters. But no need to worry there.

Additionally, you should use unicode-objecvts instead of byte-strings

do

# -*- coding: utf-8 -*-
d = dict(c1=u中国一)

Notice the u in front of the string-literal.

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

Try Python update

2006-01-01 Thread Mike Meyer
After spending time I should have been sleeping working on it, the try
python site is much more functional. It now allows statements,
including multi-line statements and expressions. You can't create code
objects yet, so it's still more a programmable calculator than
anything real.

I've got some of the tutorial text (literally) up as well. I hope to
make it easier to read the tutorial and interact with python at the
same time in the near future.

The url is http://www.mired.org/home/mwm/try_python/. Reports of
problems would appreciated.

If you want to try an online P{ython tool that lets you save code, try
Devan L's at http://www.datamech.com/devan/trypython/trypython.py.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


LocaWapp: localhost web applications (v.03 - 2005 Dec 31)

2006-01-01 Thread LocaWapp
http://cheeseshop.python.org/packages/source/L/LocaWapp/locawapp-03.tar.gz


LocaWapp: localhost web applications (v.03 - 2005 Dec 31)

Copyright (c) 2005 RDJ
This code is distributed for your utility but WITHOUT ANY WARRANTY.

http://LocaWapp.blogspot.com



- Run:

python run.py

- and browse:

http://localhost:8080/locawapp/main.py

- You can change the port:

python run.py 8081

- You can develope with this framework:

HTML(CSS,JS) + Python = LocaWapp



- Put your application folder in root directory:

[your_application]
[locawapp]
__init__.py
common.py
main.py
[static]
logo.gif
main.css
main.js
README.txt
run.py

- Your application must have init and main files (for convention):

[your_application]
__init__.py
main.py
other web applications (ex. main2.py)
your files or folders (ex. your [static])

- main.py is a web application, then it has locawapp_main function:

def locawapp_main(request):
[...]
html = [...String...]
return lwa.makeResponse(html)

- See locawapp.main.py and locawapp.common.py

- You can find me in comp.lang.python newsgroup
-


- New applications:

lwaUtils - LocaWapp Utilities
lwaUtils.files.py - files manager (under costruction)
lwaUtils.editor.py - source editor (under costruction)

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


Re: python coding contest

2006-01-01 Thread Claudio Grondi
Steven D'Aprano wrote:
 On Sun, 01 Jan 2006 15:49:58 +0100, Claudio Grondi wrote:
 
 
 
What I have thought about as a simpler/better solution is a method 
allowing to avoid processing the content of the string or long integer 
object by looping over its content. 
 
 
 How can you avoid looping over its content? Whether you do it yourself
 using for byte in array or similar, or Python does it for you
 (using array.tostring perhaps), *something* has to walk through the bytes.
 
 If you don't like walking the string, write a function to do it once, and
 then use the function.
 
 
I suppose, that knowing enough about 
Python internals it must be possible to change only the object type not 
beeing forced to process the content i.e. the value itself, what in case 
of big size of data to convert with methods like this above wastes CPU 
time.
 
 
 I'm reminded of a time I was going for a drive in the country when I drove
 past an apple orchid. Standing in the orchid was a farmer with a pig. He
 lifted the pig into the air, and the pig then bit an apple and slowly
 chewed it. The farmer then carried him over to another branch, and the pig
 ate another apple.
 
 I was so surprised I stopped my car and wandered over to ask the farmer
 what he was doing.
 
 I'm feeding apples to my pig, he replied.
 
 Wouldn't it save time to just pick some apples and feed them to the pig?
 
 The farmer looked at me like I was an idiot. What's time to a pig?
 
 
 The moral of the story is, before spending time working on some scheme to
 save CPU time, you better be absolutely sure that firstly, you are going
 to save CPU time, secondly, that it is enough CPU time to be worth saving,
 and thirdly, that you aren't wasting more of your own time to do it.
 
 
 
It's a funny story :-))

, but in my eyes not appropriate in given context, because my prior goal 
is to understand some more about Python internals, i.e. what is and if 
it is at all a differerence between the internal representation of a 
string and a long integer.

I know, I should probably look into the C source of Python, but I 
suppose it could be too hard for me to find the appropriate piece of 
code, so I welcome any hints.

If I knew the internal representation of string and long integer objects 
and were able to read/write to memory and point an identifier at a given 
memory address, a conversion between long integer and string types were 
probably nothing else as changing some bytes and repointing an 
identifier (assuming that string and long integer values are in memory 
the same data if they represent the same value). That it would save CPU 
time is secondary here, but with increasing costs of energy making the 
number on my electrical power bill higher each year due to higher power 
consumption with increasing number of programs I run (it makes a 
difference of 50 Watt between an algorithm keeping the CPU 100% busy and 
an algorithm using only 1% of it) it is not necessarily paranoia driving 
one to consider potential savings of CPU time.
In this context the example of the bigdec class comes to my mind, where 
usage of another algorithm made it possible to cut down power 
consumption and time of printing a decimal form of the largest known 
prime number from 7 hours of a 100% busy CPU down to 7 seconds!

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


Re: how-to POST form data to ASP pages?

2006-01-01 Thread livin
Mike,
I'm not a coder really at all (I dabble with vbscript  jscript) but an 
asking for help to get this working.

I have tried this...

  params = urllib.urlencode({'action': 'hs.ExecX10ByName Kitchen 
Espresso Machine, On, 100'})
  urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

Can you suggest the correct code to get this working?

I appreciate the help!

Aaron






Mike Meyer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 livin livin@@cox.net writes:
 I need to post form data to an ASP page that looks like this on the page
 itself...
 form method='POST'input src=\icons\devices\coffee-on.gif type='image'
 align='absmiddle' width=16 height=16 title='Off'input type='hidden'
 value='Image' name='Action'input type='hidden' value='hs.ExecX10ByName
 Kitchen Espresso Machine, Off, 100'/form
 I've been trying this but I get a syntax error...
   params = urllib.urlencode({'hidden': 'hs.ExecX10ByName Kitchen
 Espresso Machine, On, 100'})
   urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

 urlencode doesn't care about the type of the input element (or that
 the page is ASP), just the name/value pairs. You want:

   params = urllib.urlencode({'Action': 'Image', ...})

 The provided HTML doesn't say what the name of the second hidden input
 field is. It's not at all clear what should be passed to the server in
 this case.

 It looks like you tried to break a string across a line boundary, but
 that may be your posting  software. If you did, then that's what's
 generating a syntax error, and a good indication that you should try
 reading the tutorial.

mike
 -- 
 Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/
 Independent WWW/Perforce/FreeBSD/Unix consultant, email for more 
 information. 


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


Re: python coding contest

2006-01-01 Thread bonono

Steven D'Aprano wrote:
 I'm reminded of a time I was going for a drive in the country when I drove
 past an apple orchid. Standing in the orchid was a farmer with a pig. He
 lifted the pig into the air, and the pig then bit an apple and slowly
 chewed it. The farmer then carried him over to another branch, and the pig
 ate another apple.

 I was so surprised I stopped my car and wandered over to ask the farmer
 what he was doing.

 I'm feeding apples to my pig, he replied.

 Wouldn't it save time to just pick some apples and feed them to the pig?

 The farmer looked at me like I was an idiot. What's time to a pig?

Has anyone studied if farmers like him are in general healthier ?

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


Re: how-to POST form data to ASP pages?

2006-01-01 Thread Alan Kennedy
[livin]
 I'm not a coder really at all (I dabble with vbscript  jscript) but an 
 asking for help to get this working.
 
 I have tried this...
 
   params = urllib.urlencode({'action': 'hs.ExecX10ByName Kitchen 
 Espresso Machine, On, 100'})
   urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

You should try to phrase your question so that it is easier for us to 
understand what is going wrong, and thus help you to correct it.

As Mike already suggested, you have a string that may be spread over two 
lines, which would be illegal python syntax, and which would give a 
SyntaxError if run. You should be sure that this is not the cause of 
your problem before going further.

The following code should do the same as the above, but not suffer from 
the line breaks problem.

name_value_pairs = {
   'action': 'hs.ExecX10ByName Kitchen Espresso Machine, On, 100'
}
params = urllib.urlencode(name_value_pairs)
urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

BTW, it looks to me like you may be opening up a security hole in your 
application. The following string looks very like a VB function 
invocation: 'hs.ExecX10ByName Kitchen Espresso Machine, On, 100'

Are you executing the contents of form input fields as program code? 
That's highly inadvisable from a security point of view.

Happy New Year.

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with Tkinter

2006-01-01 Thread Steffen Mutter
Hi all and a happy new year!

My first try fiddling around with GUIs ended disappointing, instead of
showing the window title as expected 'Demofenster' ist still shows 'tk'
instead. 
What did I do wrong?


#!/usr/bin/env python

from Tkinter import *
fenster = Tk()
fenster.title = 'Demofenster'
fenster.mainloop()



I actually tried this running python2.4 on an Ubuntu's breezy badger
machine and Win2kPro running Python2.3 gives the same result.

Any hints highly apprechiated.

Regards,
Steffen

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


Re: Help please with binary file read

2006-01-01 Thread Stewart Arnold
Grant

Perfect!

Thanks :)
Stewart

Grant Edwards [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 On 2006-01-01, Stewart Arnold [EMAIL PROTECTED] wrote:

 I'm trying to convert a Real Basic routine into Python and I
 can't read the long integer data from a file.

 http://docs.python.org/lib/module-struct.html


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


Re: bsddb3 locking questions

2006-01-01 Thread Eric S. Johansson
man, I'm in really bad form replying to myself twice but I'me solved the 
problem at least in a simple form.

Eric S. Johansson wrote:
 Eric S. Johansson wrote:
 are there any simple examples of how to do record locking with bsddb3?

#!/usr/bin/python

from bsddb import db   # the Berkeley db data base
import sys, os, time

# some helpers fcns

def countdown(id, count):
 limit = 0
 while limit  count:
 print id, limit,
 limit = limit+1

# fork into 2 instances and collide
pid = os.fork()

# Part 1: Create database and insert 4 elements
#
filename = 'fruit'

# Get an instance of BerkeleyDB
db_env = db.DBEnv()
db_env.set_lk_detect(db.DB_LOCK_YOUNGEST)
db_env.open(/tmp/bsddb3,db.DB_INIT_LOCK|db.DB_CREATE| db.DB_INIT_MPOOL)

# force a collision
time.sleep(2)

an_id = db_env.lock_id()

print pid, an_id

fruitDB = db.DB(db_env)
# Create a database in file fruit with a Hash access method
#   There are also, B+tree and Recno access methods
fruitDB.open(filename, None, db.DB_HASH, db.DB_CREATE)

# Print version information
print '\t', pid, db.DB_VERSION_STRING

while(1):
 try:
 lock = db_env.lock_get(an_id, anytid, db.DB_LOCK_WRITE, 
db.DB_LOCK_NOWAIT)
 break
 except Exception,error:
 #print error
 pass

print pid, here

# force another one
time.sleep(2)

# Insert new elements in database
fruitDB.put(apple,red)
fruitDB.put(orange,orange)
fruitDB.put(banana,yellow)
fruitDB.put(tomato,red)

db_env.lock_put(lock)
print pid, there

# Close database
fruitDB.close()

# Part 2: Open database and write its contents out
#
fruitDB = db.DB(db_env)
# Open database
#   Access method: Hash
#   set isolation level to dirty read (read uncommited)
fruitDB.open(filename, None, db.DB_HASH, db.DB_DIRTY_READ)

# get database cursor and print out database content
cursor = fruitDB.cursor()
rec = cursor.first()
while rec:
 print rec
 rec = cursor.next()
fruitDB.close()

--

still unanswered, under what conditions do you change the second 
argument of lock_get?  Is that a simple lock identifier within the 
context of the lock ID so that you can lock different records?  Anyway, 
this locking is close enough for what I need to do.

---eric

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


Re: Problems with Tkinter

2006-01-01 Thread Kevin
Try:

fenster.title(Demofenster)

title a class method, not a variable.

Kevin.


Steffen Mutter [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Hi all and a happy new year!

 My first try fiddling around with GUIs ended disappointing, instead of
 showing the window title as expected 'Demofenster' ist still shows 'tk'
 instead.
 What did I do wrong?


 #!/usr/bin/env python

 from Tkinter import *
 fenster = Tk()
 fenster.title = 'Demofenster'
 fenster.mainloop()



 I actually tried this running python2.4 on an Ubuntu's breezy badger
 machine and Win2kPro running Python2.3 gives the same result.

 Any hints highly apprechiated.

 Regards,
 Steffen



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


Re: python coding contest

2006-01-01 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
 Steven D'Aprano wrote:
 
I'm reminded of a time I was going for a drive in the country when I drove
past an apple orchid. Standing in the orchid was a farmer with a pig. He
lifted the pig into the air, and the pig then bit an apple and slowly
chewed it. The farmer then carried him over to another branch, and the pig
ate another apple.

I was so surprised I stopped my car and wandered over to ask the farmer
what he was doing.

I'm feeding apples to my pig, he replied.

Wouldn't it save time to just pick some apples and feed them to the pig?

The farmer looked at me like I was an idiot. What's time to a pig?
 
 
 Has anyone studied if farmers like him are in general healthier ?

Yes, they have stronger arms, but some greater incidence of back 
problems as well.  Other than that they're basically just as healthy as 
the rest of us who feed our pigs the normal way.

-Peter

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


Re: Problems with Tkinter

2006-01-01 Thread Cousin Stanley

 My first try fiddling around with GUIs ended disappointing, 
 instead of showing the window title as expected 'Demofenster' 
 ist still shows 'tk' instead. 

 What did I do wrong?


 #!/usr/bin/env python

 from Tkinter import *
 fenster = Tk()
 fenster.title = 'Demofenster'
 fenster.mainloop()

Steffen  

  To set the Tk window title
  try 

  fenster.title( 'Demofenster' )
  

-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Tkinter

2006-01-01 Thread Steffen Mutter
Am Sun, 01 Jan 2006 18:36:56 +0100 schrieb Kevin:

 Try:
 
 fenster.title(Demofenster)

Exactly. I had a look in Michael Lauer's 'Python  GUI-Toolkits'
meanwhile, so I found the clue.

 title a class method, not a variable.

Yep. Thank you:

 Kevin.

Steffen

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


Re: Problems with Tkinter

2006-01-01 Thread Mario Wehbrink
Steffen Mutter schrieb in comp.lang.python:

 fenster.title = 'Demofenster'

Try:

fenster.title(Demofenster)

instead

Mario

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


Re: Compressing folders in Windows using Python.

2006-01-01 Thread Christian Tismer
sri2097 wrote:
 Hi,
 I'm trying to zip a particular fiolder and place the zipped folder into
 a target folder using python. I have used the following command in
 'ubuntu'.
 
 zip_command = 'zip -qr %s %s' % (target, ' '.join(source))
 
 I execute this using os.command(zip_command). It works fine...
 
 But when I run this script in Windows XP, I get an error while
 executing the above zip command. What command is there to zip files in
 Windows? Or is there any other problem ?

zip is not a built-in command for windows.
You might use winzip or something else, there is
a bunch of different compression tools available.

ciao - chris

-- 
Christian Tismer :^)   mailto:[EMAIL PROTECTED]
tismerysoft GmbH : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A :*Starship* http://starship.python.net/
14109 Berlin : PGP key - http://wwwkeys.pgp.net/
work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
PGP 0x57F3BF04   9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
  whom do you want to sponsor today?   http://www.stackless.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compressing folders in Windows using Python.

2006-01-01 Thread Tim N. van der Leeuw

Christian Tismer wrote:
 sri2097 wrote:
  Hi,
  I'm trying to zip a particular fiolder and place the zipped folder into
  a target folder using python. I have used the following command in
  'ubuntu'.
 
  zip_command = 'zip -qr %s %s' % (target, ' '.join(source))
 
  I execute this using os.command(zip_command). It works fine...
 
  But when I run this script in Windows XP, I get an error while
  executing the above zip command. What command is there to zip files in
  Windows? Or is there any other problem ?

 zip is not a built-in command for windows.
 You might use winzip or something else, there is
 a bunch of different compression tools available.

 ciao - chris


Something else to watch for -- Spaces in filenames. Uncommon on
unix/linux, but very common on windows. Put some double-quotes around
the filenames in your zip_command:

zip_command = 'zip -qr %s %s' % (target, ' '.join(source))


AFAIK there are built-in zip modules available in Python? They might be
a better alternative to calling an external zip command?

(Winzip btw, has a seperate download for a command-line capable version
of the compressor)

cheers,

--Tim


 --
 Christian Tismer :^)   mailto:[EMAIL PROTECTED]
 tismerysoft GmbH : Have a break! Take a ride on Python's
 Johannes-Niemeyer-Weg 9A :*Starship* http://starship.python.net/
 14109 Berlin : PGP key - http://wwwkeys.pgp.net/
 work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
 PGP 0x57F3BF04   9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
   whom do you want to sponsor today?   http://www.stackless.com/

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


Re: Filling out forms with python

2006-01-01 Thread Christoph Haas
On Friday 30 December 2005 06:30, Steve Young wrote:
 Hi, I was wondering if there's a way to fill out forms online using
 python. Say for example if you wanted to make a search on some search
 engine without having to actually open a browser or something like that.

Try twill:
http://www.idyll.org/~t/www-tools/twill/

 Christoph
-- 
Never trust a system administrator who wears a tie and suit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Try Python update

2006-01-01 Thread UrsusMaximus
Cool. I think its really a good thing. Could come in handy when one is
on a strange Windows machine with no Python installed, or when using a
PDA that doesn't have Python etc. 

And its just a neat feat. ;-)))

Ron

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


Re: how-to POST form data to ASP pages?

2006-01-01 Thread livin
Hi Alan,

I have tried the code you suggested and a more simple set of post parameters 
(below).

import urllib
name_value_pairs = {'control_device': 'Kitchen Lights=off'}
params = urllib.urlencode(name_value_pairs)
urllib.urlopen(http://192.168.1.11:80;, params)


Either way I get this error log...

File Q:\python\python23.zlib\urllib.py, line 78, in urlopen
File Q:\python\python23.zlib\urllib.py, line 183, in open
File Q:\python\python23.zlib\urllib.py, line 297, in open_http
File Q:\python\python23.zlib\httplib.py, line 712, in endheaders
File Q:\python\python23.zlib\httplib.py, line 597, in _send_output
File Q:\python\python23.zlib\httplib.py, line 576, in send
File string, line 1, in sendall
IOError
:
[Errno socket error] (10057, 'Socket is not connected')





Alan Kennedy [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 [livin]
 I'm not a coder really at all (I dabble with vbscript  jscript) but an 
 asking for help to get this working.

 I have tried this...

   params = urllib.urlencode({'action': 'hs.ExecX10ByName Kitchen 
 Espresso Machine, On, 100'})
   urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

 You should try to phrase your question so that it is easier for us to 
 understand what is going wrong, and thus help you to correct it.

 As Mike already suggested, you have a string that may be spread over two 
 lines, which would be illegal python syntax, and which would give a 
 SyntaxError if run. You should be sure that this is not the cause of your 
 problem before going further.

 The following code should do the same as the above, but not suffer from 
 the line breaks problem.

 name_value_pairs = {
   'action': 'hs.ExecX10ByName Kitchen Espresso Machine, On, 100'
 }
 params = urllib.urlencode(name_value_pairs)
 urllib.urlopen(http://192.168.1.11:80/hact/kitchen.asp;, params)

 BTW, it looks to me like you may be opening up a security hole in your 
 application. The following string looks very like a VB function 
 invocation: 'hs.ExecX10ByName Kitchen Espresso Machine, On, 100'

 Are you executing the contents of form input fields as program code? 
 That's highly inadvisable from a security point of view.

 Happy New Year.

 -- 
 alan kennedy
 --
 email alan:  http://xhaus.com/contact/alan 


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


Re: python coding contest

2006-01-01 Thread Claudio Grondi
Claudio Grondi wrote:
 Steven D'Aprano wrote:
 
 On Sun, 01 Jan 2006 15:49:58 +0100, Claudio Grondi wrote:



 What I have thought about as a simpler/better solution is a method 
 allowing to avoid processing the content of the string or long 
 integer object by looping over its content. 



 How can you avoid looping over its content? Whether you do it yourself
 using for byte in array or similar, or Python does it for you
 (using array.tostring perhaps), *something* has to walk through the 
 bytes.

 If you don't like walking the string, write a function to do it once, and
 then use the function.


 I suppose, that knowing enough about Python internals it must be 
 possible to change only the object type not beeing forced to process 
 the content i.e. the value itself, what in case of big size of data 
 to convert with methods like this above wastes CPU time.



 I'm reminded of a time I was going for a drive in the country when I 
 drove
 past an apple orchid. Standing in the orchid was a farmer with a pig. He
 lifted the pig into the air, and the pig then bit an apple and slowly
 chewed it. The farmer then carried him over to another branch, and the 
 pig
 ate another apple.

 I was so surprised I stopped my car and wandered over to ask the farmer
 what he was doing.

 I'm feeding apples to my pig, he replied.

 Wouldn't it save time to just pick some apples and feed them to the 
 pig?

 The farmer looked at me like I was an idiot. What's time to a pig?


 The moral of the story is, before spending time working on some scheme to
 save CPU time, you better be absolutely sure that firstly, you are going
 to save CPU time, secondly, that it is enough CPU time to be worth 
 saving,
 and thirdly, that you aren't wasting more of your own time to do it.



 It's a funny story :-))
 
 , but in my eyes not appropriate in given context, because my prior goal 
 is to understand some more about Python internals, i.e. what is and if 
 it is at all a differerence between the internal representation of a 
 string and a long integer.
 
 I know, I should probably look into the C source of Python, but I 
 suppose it could be too hard for me to find the appropriate piece of 
 code, so I welcome any hints.
 
 If I knew the internal representation of string and long integer objects 
 and were able to read/write to memory and point an identifier at a given 
 memory address, a conversion between long integer and string types were 
 probably nothing else as changing some bytes and repointing an 
 identifier (assuming that string and long integer values are in memory 
 the same data if they represent the same value). That it would save CPU 
 time is secondary here, but with increasing costs of energy making the 
 number on my electrical power bill higher each year due to higher power 
 consumption with increasing number of programs I run (it makes a 
 difference of 50 Watt between an algorithm keeping the CPU 100% busy and 
 an algorithm using only 1% of it) it is not necessarily paranoia driving 
 one to consider potential savings of CPU time.
 In this context the example of the bigdec class comes to my mind, where 
 usage of another algorithm made it possible to cut down power 
 consumption and time of printing a decimal form of the largest known 
 prime number from 7 hours of a 100% busy CPU down to 7 seconds!
 
 Claudio

 From stringobject.h :
typedef struct {
 PyObject_VAR_HEAD
 long ob_shash;
 int ob_sstate;
 char ob_sval[1];
 /* Invariants:
  * ob_sval contains space for 'ob_size+1' elements.
  * ob_sval[ob_size] == 0.
  * ob_shash is the hash of the string or -1 if not computed yet.
  * ob_sstate != 0 iff the string object is in stringobject.c's
  *   'interned' dictionary; in this case the two references
  *   from 'interned' to this object are *not counted* in ob_refcnt.
  */
} PyStringObject;

 From longobject.h :
typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */
 From longintrepr.h :
typedef unsigned short digit;
struct _longobject {
  PyObject_VAR_HEAD
  digit ob_digit[1];
};

 From this I mean to see, that the string data header is longer 
containing an additional long and an int compared to long integer data 
header. The long integer seem to be an array of unsigned short values 
and the string an array of characters. My MSDN help tells me, that:
Type short int (or simply short) is an integral type that is larger 
than or equal to the size of type char, and shorter than or equal to the 
size of type int. In Microsoft Visual C++ short is 2 bytes long, and 
because I am on an Intel processor the sequence of bytes will differ 
from what I will get when creating a binary string out of a long integer 
due to swapping of byte order. Am I right here?

My conclusion is, that beeing on e.g. Motorola 68000 based processors 
the actual data behind the string and the long integer types will be the 
same, but beeing on an Intel 386 

Python or Java or maybe PHP?

2006-01-01 Thread liorm
Hi everyone,

I need to write a web app, that will support millions of user accounts,
template-based user pages and files upload. The client is going to be
written in Flash. I wondered if I coudl get your opinions - what do you
think is the best language to use for the server? Python or Java? And
I'm talking scalability, object oriented, development tools etc.

Thansk for any idea! I'd love to hear it
Happy New 2006,
Lior

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


Re: python coding contest

2006-01-01 Thread Jacob Hallen
In article [EMAIL PROTECTED],
Simon Hengel  [EMAIL PROTECTED] wrote:
Hello,

 After all, I'd really love to set up another contest with
 different measures and criteria.

for future events i will take a close look at other possibilities for
doing a ranking. At the moment the 22c3 and the contest is eating up all
my time. Pleas appreciate that i may not keep up with all mails. Sorry
for that.

For whatever it is worth, I enjoyed myself thoroughly thinking about the 
problem,
discussing it and listening to others discuss it. It was FUN!

It is built into all requirements for shortest or fastest that the winning 
solution
will be using obscure features and combinations in order to make the absolutely
optimal solution. This doesn't really matter unless your goals are to 
demonstrate
the elegance of the programming language. If you want to provide an alternative
to solving crossword puzzles or mega-hard Sudoku's for the Christmas holiday, 
I'd
say this is spot on.

Jacob Hallén


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

Preventing control characters from entering an XML file

2006-01-01 Thread Frank Niessink
Hi list,

First of all, I wish you all a happy 2006. I have a small question that 
googling didn't turn up an answer for. So hopefully you'll be kind 
enough to send me in the right direction.

I'm developing a desktop application, called Task Coach, that saves its 
domain objects (tasks, mostly :-) in an XML file. Users have reported 
that sometimes their Task Coach file would become unreadable by Task
Coach after copying information from some other application into e.g. a 
task description. Looking at the 'corrupted' file showed that control 
characters ended up in the XML file (Control-K for example). Task Coach 
uses xml.dom to create an XML document and save it, like this:

class XMLWriter:
   ...

   def write(self, taskList):
 domImplementation = xml.dom.getDOMImplementation()
 self.document = domImplementation.createDocument(None, 'tasks',
  None)
 ...
 for task in taskList.rootTasks():
   self.document.documentElement.appendChild(self.taskNode(task))
 self.document.writexml(self.__fd) # __fd is a file open for writing

   ...

Apparently, the writexml method of xml.dom (which comes from 
xml.dom.minidom if pyxml is not installed I think) does not feel that 
writing control characters in an XML file is wrong, but the parser does:

Traceback (most recent call last):
...
   File c:\Program Files\Python24\lib\xml\dom\expatbuilder.py, line 
207, in parseFile
 parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 77, 
column 147

Rightfully so, because ^K is not valid XML 1.0, according to 
http://www.w3.org/TR/REC-xml/:

Legal characters are tab, carriage return, line feed, and the legal 
characters of Unicode and ISO/IEC 10646. [...] Consequently, XML 
processors MUST accept any character in the range specified for Char.

Character Range
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | 
[#x1-#x10]

So, all this leads me to the following questions:
- Why does the writexml method of the document created by the object 
returned by domImplementation() allow control characters? Isn't that a bug?
- What is the easiest/most pythonic (preferably build-in) way of 
checking a unicode string for control characters and weeding those 
characters out?

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


Re: how-to POST form data to ASP pages?

2006-01-01 Thread Alan Kennedy
[livin]
 I have tried the code you suggested and .. 
 .. Either way I get this error log...
 
 File Q:\python\python23.zlib\urllib.py, line 78, in urlopen
 File Q:\python\python23.zlib\urllib.py, line 183, in open
 File Q:\python\python23.zlib\urllib.py, line 297, in open_http
 File Q:\python\python23.zlib\httplib.py, line 712, in endheaders
 File Q:\python\python23.zlib\httplib.py, line 597, in _send_output
 File Q:\python\python23.zlib\httplib.py, line 576, in send
 File string, line 1, in sendall
 IOError
 :
 [Errno socket error] (10057, 'Socket is not connected')

OK, now we're getting somewhere.

As you can probably guess from the error message, the socket through 
which urllib is making the request is not connected to the server. We 
have to figure out why.

That library path is unusual: Q:\python\python23.zlib\httplib.py

Python supports reading library modules from a zip file, but the 
standard installations generally don't use it, except for Python CE, 
i.e. Python for Microsoft Windows PocketPC/CE/WTF. Is this the platform 
that you're using? If I remember rightly, Python for Pocket Windows 
doesn't support sockets, meaning that urllib wouldn't work on that platform.

Another thing to establish is whether the URL is working correctly, from 
a client you know works independently from your script above, e.g. an 
ordinary browser. When you submit to your form handling script from an 
ordinary browser, does it work?

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how-to POST form data to ASP pages?

2006-01-01 Thread livin
The library is the PC version of 2.3  --- I have done some more testing.

I simplified my .py to only 2 lines...

import urllib
urllib.urlopen('http://192.168.1.11', urllib.urlencode({'control_device': 
'Kitchen Lights=off'}))

I get this error...

File Q:\python\python23.zlib\urllib.py, line 78, in urlopen
File Q:\python\python23.zlib\urllib.py, line 183, in open
File Q:\python\python23.zlib\urllib.py, line 297, in open_http
File Q:\python\python23.zlib\httplib.py, line 712, in endheaders
File Q:\python\python23.zlib\httplib.py, line 597, in _send_output
File Q:\python\python23.zlib\httplib.py, line 564, in send
File Q:\python\python23.zlib\httplib.py, line 548, in connect
IOError
:
[Errno socket error] (10060, 'Operation timed out')

I've taken the commands I'm using from working HTTP  ASP pages.

Here's actual code from an HTML page I'm using for the same device I'm 
trying in my .PY...

form method=post
td nowrap class=tableroweven
a name=bm83274/a
input type=hidden name=bookmark value=83274
input type=hidden name=ref_page value=stat
input type=hidden name=control_device value=Kitchen Lights
input class=formbutton type=submit name=action_on value=On
input class=formbutton type=submit name=action_off value=Off
select class=formdropdown name=selectdim SIZE=1 
onchange=SubmitForm(this)
option selected value=00%/option
option value=1010%/option
option value=2020%/option
option value=3030%/option
option value=4040%/option
option value=5050%/option
option value=6060%/option
option value=7070%/option
option value=8080%/option
option value=9090%/option
option value=100100%/option
/select
/td/form




Alan Kennedy [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 [livin]
 I have tried the code you suggested and .. .. Either way I get this error 
 log...

 File Q:\python\python23.zlib\urllib.py, line 78, in urlopen
 File Q:\python\python23.zlib\urllib.py, line 183, in open
 File Q:\python\python23.zlib\urllib.py, line 297, in open_http
 File Q:\python\python23.zlib\httplib.py, line 712, in endheaders
 File Q:\python\python23.zlib\httplib.py, line 597, in _send_output
 File Q:\python\python23.zlib\httplib.py, line 576, in send
 File string, line 1, in sendall
 IOError
 :
 [Errno socket error] (10057, 'Socket is not connected')

 OK, now we're getting somewhere.

 As you can probably guess from the error message, the socket through which 
 urllib is making the request is not connected to the server. We have to 
 figure out why.

 That library path is unusual: Q:\python\python23.zlib\httplib.py

 Python supports reading library modules from a zip file, but the standard 
 installations generally don't use it, except for Python CE, i.e. Python 
 for Microsoft Windows PocketPC/CE/WTF. Is this the platform that you're 
 using? If I remember rightly, Python for Pocket Windows doesn't support 
 sockets, meaning that urllib wouldn't work on that platform.

 Another thing to establish is whether the URL is working correctly, from a 
 client you know works independently from your script above, e.g. an 
 ordinary browser. When you submit to your form handling script from an 
 ordinary browser, does it work?

 -- 
 alan kennedy
 --
 email alan:  http://xhaus.com/contact/alan 


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


Re: Python article in Free Software Magazine

2006-01-01 Thread Ed Jensen
Steven D'Aprano [EMAIL PROTECTED] wrote:
 I don't want to nit-pick all my way through the article, which
 is very decent and is worth reading, but I will say one more thing: you
 describe Python as an expressive, interpreted language. Python is no
 more interpreted than Java. Like Java, it is compiled into byte-code which
 is then executed by a virtual machine. It has a separate compilation and
 execution step.

http://www.python.org/doc/faq/general.html

Python is an *interpreted*, interactive, object-oriented programming
language.

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


Re: Python article in Free Software Magazine

2006-01-01 Thread Ed Jensen
Steven D'Aprano [EMAIL PROTECTED] wrote:
 I don't want to nit-pick all my way through the article, which
 is very decent and is worth reading, but I will say one more thing: you
 describe Python as an expressive, interpreted language. Python is no
 more interpreted than Java. Like Java, it is compiled into byte-code which
 is then executed by a virtual machine. It has a separate compilation and
 execution step.

The most-used desktop/server JVM, the Sun JVM, takes things one step
further and compiles often-executed bytecode into native code.  It can
then execute native code.  AFAIK, the most-used desktop/server Python
VM doesn't do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


loops breaks and returns

2006-01-01 Thread rbt
Is it more appropriate to do this:

while 1:
 if x:
 return x

Or this:

while 1:
 if x:
 break
return x

Or, does it matter?
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem overriding sys.excepthook

2006-01-01 Thread Lunchtimemama
Yo all, I'm getting into Python for the first time and I'm really
having a blast. I've hit a bit of a snag and was wondering if someone
could lend some insight. Here be the code:

import sys
def myexcepthook(type, value, tb):
  import traceback
  rawreport = traceback.format_exception(type, value, tb)
  report = '\n'.join(rawreport)
  errorlog = open('error.log','a')
  errorlog.write(('%s\n' + '-'*30 + '\n\n') % report)
  errorlog.close()
sys.excepthook = myexcepthook

Now here's the trouble: if I enter that line-by-line into the
interpreter in interactive mode, the custom exception hook will handle
all exceptions, but if I put that in a script that I run from the
shell, it only catches some exceptions. For example, it would catch an
undefined name, like if I just put:

spam

into the program above, the override would work. But if I made a
syntactical error, like:

1 = spam

then it would fall to the standard sys.excepthook. Is there some lazy
evaluation that I don't know about? I'm on Windows, if that makes a
difference. Thank for the help.

-LTM

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


Re: Memoization and encapsulation

2006-01-01 Thread Tom Anderson
On Sat, 31 Dec 2005 [EMAIL PROTECTED] wrote:

just I actually prefer such a global variable to the default arg
just trick. The idiom I generally use is:

just _cache = {}
just def func(x):
just result = _cache.get(x)
just if result is None:
just result = x + 1  # or a time consuming calculation...
just _cache[x] = result
just return result

 None of the responses I've seen mention the use of decorators such as the
 one shown here:

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

 While wrapping one function in another is obviously a bit slower, you can
 memoize any function without tweaking its source.

I'd definitely say this is the way to go.

def memoised(fn):
cache = {}
def memoised_fn(*args):
if args in cache:
return cache[args]
else:
rtn = fn(*args)
cache[args] = rtn
return rtn
return memoised_fn

@memoised
def func(x):
return x + 1 # or a time-consuming calculation

tom

-- 
Exceptions say, there was a problem. Someone must deal with it. If you
won't deal with it, I'll find someone who will.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'

2006-01-01 Thread Max M
Carsten Haese wrote:
 On Fri, 2005-12-30 at 09:52, tim wrote:
 
Trying to convert midi to text using MidiToText.py.
I get the following:

midi_port: 0
Traceback (most recent call last):
  File MidiToText.py, line 176, in ?
midiIn.read()
  File C:\Python24\Lib\site-packages\midi\MidiInFile.py, line 24, in read
p.parseMTrkChunks()
  File C:\Python24\Lib\site-packages\midi\MidiFileParser.py, line 167, 
in parseMTrkChunks
self.parseMTrkChunk() # this is where it's at!
  File C:\Python24\Lib\site-packages\midi\MidiFileParser.py, line 129, 
in parseMTrkChunk
dispatch.sysex_events(sysex_data)
AttributeError: EventDispatcher instance has no attribute 'sysex_events'
 
 
 Try changing def sysex_event(self, data): in
 ...\midi\EventDispatcher.py to def sysex_events(self, data):

Or just do a search and replace on the whole package::

search: sysex_events(
replace: sysex_event(

Apparently I have been inconsistent in my naming.

New version at:

http://www.mxm.dk/products/public/pythonmidi/download


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loops breaks and returns

2006-01-01 Thread Peter Hansen
rbt wrote:
 Is it more appropriate to do this:
 
 while 1:
  if x:
  return x
 
 Or this:
 
 while 1:
  if x:
  break
 return x

The former would be considered bad style by some people.  Others would 
consider it perfectly acceptable in a small function (say, no more than 
10-20 lines of code?) where it would be clear what's going on.  Others 
would consider it fine in any case.

If I really had a while 1 loop with only the one exit condition, and 
an immediate return, I would definitely go with the former approach.  If 
I had any other place where I was going to return, I'd consider the 
second approach more carefully.

-Peter

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


Re: Hypergeometric distribution

2006-01-01 Thread Raven
Thanks Steven for your very interesting post.

This was a critical instance from my problem:

from scipy import comb
 comb(14354,174)
inf

The scipy.stats.distributions.hypergeom function uses the scipy.comb
function, so it returned nan since it tries to divide an infinite. I
did not tried to write a self-made function using standard python as I
supposed that the scipy functions reached python's limits but I was
wrong, what a fool :-)

If you are calculating hundreds of hypergeometric probabilities, 30
seconds each could be quite painful, but it certainly shows that Python is
capable of doing it without resorting to logarithms which may lose some
significant digits. Although, in fairness, the log function doesn't seem
to lose much accuracy for arguments in the range you are dealing with.

Yes I am calculating hundreds of hypergeometric probabilities so I need
fast calculations

Ale

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


Re: Python as a Server vs Running Under Apache

2006-01-01 Thread mojosam
I guess I'm a little confused, and this certainly comes from not yet
having tried to do anything with Python on a web server.

I remarked once to a Python programmer that it appeared to me that if I
had a web page that called a Python program, that the server would:
1. Load Python
2. Run the program
3. Unload Python

Then the next time it has to serve up that page, it would have to
repeat the process.  This seems inefficient, and it would slow the site
down.  The programmer confirmed this.  He said that's why I should use
mod_python.  It stays resident.

Is this advice accurate?  Are there other things to consider?  Isn't
there just some way (short of running something like Zope) that would
keep Python resident in the server's RAM?  This is a shared server, so
the web host probably doesn't like stuff sitting around in RAM.

Right now, I only need small programs to run.  E.g., I'm thinking of
embedding a Live Journal blog in my web page.  Live Journal gives you
several ways of doing this, one of which is three lines of Python code.

Ron Britton

(This email address will be deleted in a couple of days, once it starts
receiving spam from this posting.  Please reply to the group!)

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


Re: Try Python update

2006-01-01 Thread Devan L

Mike Meyer wrote:
 After spending time I should have been sleeping working on it, the try
 python site is much more functional. It now allows statements,
 including multi-line statements and expressions. You can't create code
 objects yet, so it's still more a programmable calculator than
 anything real.

 I've got some of the tutorial text (literally) up as well. I hope to
 make it easier to read the tutorial and interact with python at the
 same time in the near future.

 The url is http://www.mired.org/home/mwm/try_python/. Reports of
 problems would appreciated.

 If you want to try an online P{ython tool that lets you save code, try
 Devan L's at http://www.datamech.com/devan/trypython/trypython.py.

My code uses one of the recipes from the Python Cookbook, 7.6 Pickling
Code Objects. It's limited to closures though, just like in the recipe.
So uh, you can't write closures in mine.

On a side note, my brother has tinkered with the C internals and now
__subclasses__ is restricted and many, many os and posix commands are
restricted (not that you can get them anyways, since importing is
broken!)

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


Re: Problem overriding sys.excepthook

2006-01-01 Thread Patrick Maupin

Lunchtimemama wrote:
 Yo all, I'm getting into Python for the first time and I'm really
 having a blast. I've hit a bit of a snag and was wondering if someone
 could lend some insight. Here be the code:

 import sys
 def myexcepthook(type, value, tb):
   import traceback
   rawreport = traceback.format_exception(type, value, tb)
   report = '\n'.join(rawreport)
   errorlog = open('error.log','a')
   errorlog.write(('%s\n' + '-'*30 + '\n\n') % report)
   errorlog.close()
 sys.excepthook = myexcepthook

 Now here's the trouble: if I enter that line-by-line into the
 interpreter in interactive mode, the custom exception hook will handle
 all exceptions, but if I put that in a script that I run from the
 shell, it only catches some exceptions. For example, it would catch an
 undefined name, like if I just put:

 spam

 into the program above, the override would work. But if I made a
 syntactical error, like:

 1 = spam

 then it would fall to the standard sys.excepthook. Is there some lazy
 evaluation that I don't know about? I'm on Windows, if that makes a
 difference. Thank for the help.


Python first compiles, then executes.  However, since an import is
considered to be an execution, you can retrieve this sort of
compile-time error, but only on modules which are imported _after_ you
hook the exception handler.

HTH,
Pat

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


Re: loops breaks and returns

2006-01-01 Thread Sam Pointon
rbt wrote:
 Is it more appropriate to do this:

 while 1:
  if x:
  return x

 Or this:

 while 1:
  if x:
  break
 return x

 Or, does it matter?

I would pick the first form if that's the only place where x would be
returned from the function. However, if there would be redundant
'return x'-es in the function because of this, then the second form
becomes preferable. It's not set in stone, though - if you have a
compelling reason to break the rule-of-thumb, do so.

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


Tkinter app hanging on windows

2006-01-01 Thread msoulier
Hello,

I have a very simple Tkinter application that I'm using to dispatch a
mechanize crawl of a web form, when a button is clicked. Most of the
time it will be idle, until the user decides to unminimize it and click
that button.

Unfortunately, I'm finding that after several hours of being up, when I
go to the app, either by unminimizing it or simply bringing it into
focus, the app is no longer dispatching events. It refuses to redraw
itself, showing whatever was over it at the time. The app is apparently
hung, and I do not believe that this is through any fault of my own, as
the app is just too simple.

Any ideas as to how I could find out why it is hanging? I'm using
Python.org's win32 build of Python 2.4. I don't recall the exact
version, but I can get it. 

Mike

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


Re: Python as a Server vs Running Under Apache

2006-01-01 Thread Jean-Paul Calderone
On 1 Jan 2006 14:44:07 -0800, mojosam [EMAIL PROTECTED] wrote:
I guess I'm a little confused, and this certainly comes from not yet
having tried to do anything with Python on a web server.

I remarked once to a Python programmer that it appeared to me that if I
had a web page that called a Python program, that the server would:
1. Load Python
2. Run the program
3. Unload Python

This is true of any CGI.  It is part of the definition of CGI.


Then the next time it has to serve up that page, it would have to
repeat the process.  This seems inefficient, and it would slow the site
down.  The programmer confirmed this.  He said that's why I should use
mod_python.  It stays resident.

There are lots of ways to write web applications aside from CGIs.  mod_python 
is one.


Is this advice accurate?  Are there other things to consider?  Isn't
there just some way (short of running something like Zope) that would
keep Python resident in the server's RAM?  This is a shared server, so
the web host probably doesn't like stuff sitting around in RAM.

Using Twisted, FastCGI, SCGI, or even BaseHTTPServer in the standard library 
will address /this/ particular issue (there are lots of other solutions, too, 
not just these four).  Some of them may address other issues better or worse 
than others.

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


The New Extension IDE - EXTEIDE

2006-01-01 Thread EXTEIDE (sent by Nabble.com)

EXTEIDE is freeware. Anyone can download now.

Please visit http://www.exteide.com

Thanks.


Sent from the Python - python-list forum at Nabble.com:
The New Extension IDE - EXTEIDE
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Hypergeometric distribution

2006-01-01 Thread Paul Rubin
Raven [EMAIL PROTECTED] writes:
 Yes I am calculating hundreds of hypergeometric probabilities so I need
 fast calculations

Can you use Stirling's approximation to get the logs of the factorials?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing control characters from entering an XML file

2006-01-01 Thread Scott David Daniels
Frank Niessink wrote:
 ...
 Character Range
 Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | 
 [#x1-#x10]
 
 - What is the easiest/most pythonic (preferably build-in) way of 
 checking a unicode string for control characters and weeding those 
 characters out?

 drop_controls = [None] * 0x20
 for c in '\t\r\n':
 drop_controls[c] = unichr(c)
 ...
 some_unicode_string = some_unicode_string.translate(drop_controls)

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


Getting terse tracebacks?

2006-01-01 Thread Roy Smith
Is there any way to make the traceback printer built into the
interpreter elide all the directories in pathnames (like strip_dirs()
does for the profiler)?

I'm working in a deep directory tree, and the full pathnames to my
python source files are pushing 150 characters.  I either need a
laptop with a wider screen, or younger eyes so I can read a smaller
font :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem overriding sys.excepthook

2006-01-01 Thread Lunchtimemama
Forgive my ignorance, but I'm not quite sure what you mean. I tried
importing the traceback module at the beginning of the script, but that
didn't make a difference. Could you provide example code to illustrate
your comment? Thanks.

-LTM

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


Re: Try Python update

2006-01-01 Thread Mike Meyer
Devan L [EMAIL PROTECTED] writes:
 If you want to try an online P{ython tool that lets you save code, try
 Devan L's at http://www.datamech.com/devan/trypython/trypython.py.
 My code uses one of the recipes from the Python Cookbook, 7.6 Pickling
 Code Objects. It's limited to closures though, just like in the recipe.
 So uh, you can't write closures in mine.

I don't have the dead trees version, and the online version doesn't
have chapter numbers. Is that URL:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212565?

 On a side note, my brother has tinkered with the C internals and now
 __subclasses__ is restricted and many, many os and posix commands are
 restricted (not that you can get them anyways, since importing is
 broken!)

I got import to work by pickling pairs of names - the variable name
that references the module, and the name of the module. When it
unpickles the list, it reimports them and points the appropriate
variable at them. This had unwanted effects if you did an import
this. It also doesn't work for objects that contain references to
modules.

I tried for a bit to restrict things, then gave up and did it
externally. There's no access to any files but those required to run
the script that deals with thing, and some other python modules that I
decided would be nice to have. Normally, nothing in the tree is
writable, either. Once I'm happy with it, I'll save a copy of the tree
somewhere and set up a cron job to refresh it at regular intervals.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


how to scrape url out of href

2006-01-01 Thread homepricemaps
i need to scrape a url out of an href.  it seems that people recommend
that i use beautiful soup but had some problems.

does anyone have sample code for scraping the actual url out of an href
like this one

a href=http://www.cnn.com; target=_blank

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


Re: Numeric RandomArray seed problem

2006-01-01 Thread Sean Richards

[EMAIL PROTECTED] [EMAIL PROTECTED] writes:

 Hello,

 I tried calling RandomArray.seed()
 by calling RandomArray.get_seed() I get the seed number (x,y).
 My problem is that x is always 113611 any advice?


In [1]: from RandomArray import *

In [2]: seed?
Type:   function
Base Class: type 'function'
String Form:function seed at 0x407a1534
Namespace:  Interactive
File:   /usr/lib/python2.3/site-packages/Numeric/RandomArray.py
Definition: seed(x=0, y=0)
Docstring:
seed(x, y), set the seed using the integers x, y; 
Set a random one from clock if  y == 0


In [3]: seed(123,456)

In [4]: get_seed()
Out[4]: (123, 456)

Cheers, Sean

-- 
Hver sin smak, sa vintapperen, han drakk mens de andre sloss.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to scrape url out of href

2006-01-01 Thread Paul Rubin
[EMAIL PROTECTED] writes:
 does anyone have sample code for scraping the actual url out of an href
 like this one
 
 a href=http://www.cnn.com; target=_blank

If you've got the tag by itself like that, just use a regexp to get
the href out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python coding contest

2006-01-01 Thread Michael Spencer
Claudio Grondi wrote:
 ...I analysed the outcome of it and have
 come to the conclusion, that there were two major factors which 
 contributed to squeezing of code:
 
(1). usage of available variants for coding of the same thing
(2). sqeezing the size of used numeric and string literals
 
...not only squeezing the size of the literals, but the combined size of the 
compressed data and the code to expand it.  In this respect it turned out to be 
a surprisingly rewarding challenge, and a nice reinforcement of the Pythonic 
mantra of seeking performance gains by optimizing algorithms.

Michael



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


Re: Python as a Server vs Running Under Apache

2006-01-01 Thread Mike Meyer
mojosam [EMAIL PROTECTED] writes:
 Is this advice accurate?  Are there other things to consider?  Isn't
 there just some way (short of running something like Zope) that would
 keep Python resident in the server's RAM?  This is a shared server, so
 the web host probably doesn't like stuff sitting around in RAM.

Jean-Paul Calderone has already answered most of these, so I'll get
the last one.

Stuff sitting around in RAM unusued on a busy server leaves RAM
pretty quickly on a modern system. The executable pages will just be
tossed, and reloaded from the executable file when they are needed
again. Data pages will be written out to disk in the swap area, and
read back in when they are needed. Unless your program's behavior is
very strange, this will generally be quicker than recreating the
program state from scratch. The end result is that your program loads
faster, and the real RAM used to support this is negligible.

 Right now, I only need small programs to run.  E.g., I'm thinking of
 embedding a Live Journal blog in my web page.  Live Journal gives you
 several ways of doing this, one of which is three lines of Python code.

Trying to make your dynamic HTML content fast before you need to is
a premature optimization. Yes, CGI is slow compared to some of the
alternatives. But forks on Unix are still cheap, and you can handle
quite a bit of traffic with it on a modern system before you run into
a wall. Do it with CGI first, and fix it later if you need to.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Build Python using Mars compiler?

2006-01-01 Thread rzed
Has anyone tried to compile Python (on Windows) using the Digital 
Mars compiler? If so, can you give some hints how you did it? 

Or ... can anyone suggest an approach to compiling from the ground up 
using a compiler that isn't mentioned in the thicket of #ifdefs? 
Where to start? What to look out for?
-- 
rzed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to scrape url out of href

2006-01-01 Thread homepricemaps
sorry paul-i'm an extremely beginner programmer, if that! ;-) can you
give me an example?

thanks in advance

Paul Rubin wrote:
 [EMAIL PROTECTED] writes:
  does anyone have sample code for scraping the actual url out of an href
  like this one
 
  a href=http://www.cnn.com; target=_blank

 If you've got the tag by itself like that, just use a regexp to get
 the href out.

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


Re: python coding contest

2006-01-01 Thread Alex Martelli
Christian Tismer [EMAIL PROTECTED] wrote:

 Hans Nowak wrote:
 
 ...  for u in(3,14,10))
  
  can be written as:
  
 ...  for u in 3,14,10)
  
  which would shave off a character.  Tuples don't always need parentheses...
 
 This would work with a list comprehension.
 Doesn't work with a generator expression
 (thought of it, too, and the list comprehension eats one char)

Right.  I asked Guido about that, as he put together the 120-chars
submission of Team Google (including some input from me and others),
and he says it's to avoid (human) ambiguity, much like the reason the
parentheses are mandatory in [(a,b) for ...].


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


Re: how-to POST form data to ASP pages?

2006-01-01 Thread livin
The library is the PC version of 2.3  --- I have done some more testing.

I simplified my .py to only 2 lines...

import urllib
urllib.urlopen('http://192.168.1.11', urllib.urlencode({'control_device':
'Kitchen Lights=off'}))

I get this error...

File Q:\python\python23.zlib\urllib.py, line 78, in urlopen
File Q:\python\python23.zlib\urllib.py, line 183, in open
File Q:\python\python23.zlib\urllib.py, line 297, in open_http
File Q:\python\python23.zlib\httplib.py, line 712, in endheaders
File Q:\python\python23.zlib\httplib.py, line 597, in _send_output
File Q:\python\python23.zlib\httplib.py, line 564, in send
File Q:\python\python23.zlib\httplib.py, line 548, in connect
IOError
:
[Errno socket error] (10060, 'Operation timed out')

I've taken the commands I'm using from working HTTP  ASP pages.

Here's actual code from an HTML page I'm using for the same device I'm
trying in my .PY...

form method=post
td nowrap class=tableroweven
a name=bm83274/a
input type=hidden name=bookmark value=83274
input type=hidden name=ref_page value=stat
input type=hidden name=control_device value=Kitchen Lights
input class=formbutton type=submit name=action_on value=On
input class=formbutton type=submit name=action_off value=Off
select class=formdropdown name=selectdim SIZE=1
onchange=SubmitForm(this)
option selected value=00%/option
option value=1010%/option
option value=2020%/option
option value=3030%/option
option value=4040%/option
option value=5050%/option
option value=6060%/option
option value=7070%/option
option value=8080%/option
option value=9090%/option
option value=100100%/option
/select
/td/form



Dennis Lee Bieber [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 On Sun, 1 Jan 2006 12:35:06 -0700, livin livin@@cox.net declaimed
 the following in comp.lang.python:

 IOError
 :
 [Errno socket error] (10057, 'Socket is not connected')


 That doesn't look like anything to do, directly, with parameter
 encodings... Rather, it looks like your server is closing the connection
 unexpectedly.

 You've got the Python source for everything down to the call to
 sendall, examine it -- it might help figure out where things are
 failing. (sendall looks to be in a compiled module)


 -- 
  == 
[EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG 
   [EMAIL PROTECTED] |   Bestiaria Support Staff   
  == 
Home Page: http://www.dm.net/~wulfraed/
 Overflow Page: http://wlfraed.home.netcom.com/ 


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


Re: Try Python update

2006-01-01 Thread Devan L
Mike Meyer wrote:
 Devan L [EMAIL PROTECTED] writes:
  If you want to try an online P{ython tool that lets you save code, try
  Devan L's at http://www.datamech.com/devan/trypython/trypython.py.
  My code uses one of the recipes from the Python Cookbook, 7.6 Pickling
  Code Objects. It's limited to closures though, just like in the recipe.
  So uh, you can't write closures in mine.

 I don't have the dead trees version, and the online version doesn't
 have chapter numbers. Is that URL:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/212565?

It was one of the recipes of the day, actually. They don't keep them up
for more than a week, though, I think. But more or less it has all of
the attributes used for creating an object from types.CodeType in
correct order.

  On a side note, my brother has tinkered with the C internals and now
  __subclasses__ is restricted and many, many os and posix commands are
  restricted (not that you can get them anyways, since importing is
  broken!)

 I got import to work by pickling pairs of names - the variable name
 that references the module, and the name of the module. When it
 unpickles the list, it reimports them and points the appropriate
 variable at them. This had unwanted effects if you did an import
 this. It also doesn't work for objects that contain references to
 modules.

My general method of storing is to store everything possible. See a
function? Store the function object itself. See a class? Store the
class object. Unfortunately, I can't store builtin methods or
functions, so this breaks on most modules. Don't try to reference the
__builtins__, by the way, otherwise it won't be removed and modjelly
will break.


 I tried for a bit to restrict things, then gave up and did it
 externally. There's no access to any files but those required to run
 the script that deals with thing, and some other python modules that I
 decided would be nice to have. Normally, nothing in the tree is
 writable, either. Once I'm happy with it, I'll save a copy of the tree
 somewhere and set up a cron job to refresh it at regular intervals.

I don't have enough control on the server to effectively restrict it
externally (no running as an unprivelleged user!), so I have to lock it
down as tightly as possible internally.

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


Re: Python or Java or maybe PHP?

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

 Hi everyone,
 
 I need to write a web app, that will support millions of user accounts,
 template-based user pages and files upload. The client is going to be
 written in Flash. I wondered if I coudl get your opinions - what do you
 think is the best language to use for the server? Python or Java? And
 I'm talking scalability, object oriented, development tools etc.

I would personally not consider PHP, in terms of human scalability (if
the server needs to grow to substantially rich logic etc).  However,
Ruby (with Rails, of course, as the server-side framework), Python (many
options server-side, from Twisted to Django), and Java (even more
options server-side), are, I believe, all worthy candidates.  They're
all object oriented enough that the fine distinctions among them don't
really matter; choice of developer tools is probably widest for Java and
least wide for Ruby (and the same for server-side web frameworks), but
this cuts both ways (once you've decided on Java as the language you
still have many weeks of evaluation to pick tools and frameworks -- if
you decide on Ruby, tools and framework are more or less fixed -- Python
is in between in both fields).

The etc. is where the fun is;-).  Java is statically typed, Ruby and
Python are dynamically typed: you will perhaps find more flamewars on
the web about this one aspect of programming languages than about all
others combined.  On the basis of extensive personal experience, I'm
firmly in the dynamical-typing camp -- firmly convinced that Ruby or
Python make developers and teams more productive, or, in other words,
that Ruby and Python are higher-level than Java, requiring much less
code to implement a given amount of functionality, and developers'
productivity is tied mostly to the amount of code they need to
develop, debug, maintain (functional specs and user documentation OTOH
depend on functionality, not on code needed to implement the
functionality, and so don't depend on the choice of implementation
language[s]).

You'll also find lots of flamewars on each side about side issue such as
community, or the quality of programmers that you can easily get for
language A vs language B (for just about any choice of A and B;-).  I'm
not sure how much weight you should give to these considerations, or
other soft and fuzzy ones such as the issue of philosophy reflected
by each language's design and community.

All things considered, I would tentatively suggest Python, but if you
examined both languages a little and then picked Ruby (or, given a
suitable number of CS PhD's in your development team, Common Lisp, or
Haskell, but that's another issue) I'd have no basis for predicting that
your choice would be wrong; if you picked Java, I would strongly suspect
you made the wrong choice; if you picked PHP, I would personally feel
_certain_ that you made the wrong choice;-).

And just to give the devil its due, if it's an acceptable trade-off for
your server to be shackled to Microsoft systems forevermore, you might
even want to consider ASP.NET -- I have no experience with it
whatsoever, but some people whose technical judgment I respect do claim
it's a good choice.  Personally, I would consider the 'strategic' cost
(the above-mentioned MS shackes) too high in any case, but only you can
make such decisions for your own circumstances.  Similarly, Apple's
WebObjects have also been widely praised, but they would shackle you to
Apple systems (language choice directly supported by Apple for
WebObjects is Objective C, Java, and WebScript, a proprietary
very-high-level language; but I believe that thanks to PyObjC you could
use Python instead or side by side with ObjC, just as, of course, you
always have the option of Jython, instead or side by side with Java,
whenever you choose a Java-based platform).


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


Re: Line replace

2006-01-01 Thread DarkBlue
Thank you for all the suggestions

It appears the safest solution still is using a temp file
as was so apt suggested further up here without it I maybe
white water rafting without a canoe.
I also will test the feasibility to regenerate
the whole file from the database.

Nx



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


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-01 Thread Alex Martelli
Anton Vredegoor [EMAIL PROTECTED] wrote:
   ...
 Google's not a nice company (yeah, I know I'm posting from a google
 account). If you look at their job requirements it's clear they will
 only hire people with long backstabbing histories.

Such as...? Guido van Rossum?  Greg Stein?  Vint Cerf?  Ben Goodger?
Please DO share your insider-information about the long backstabbing
histories of each and every one of these people, I'm sure it will be
most fascinating (as well as useful for self-protection to future
potential victims), and, after all, they ARE all rather public
figures... TIA!


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


Re: Hypergeometric distribution

2006-01-01 Thread Steven D'Aprano
On Sun, 01 Jan 2006 14:24:39 -0800, Raven wrote:

 Thanks Steven for your very interesting post.
 
 This was a critical instance from my problem:
 
from scipy import comb
 comb(14354,174)
 inf

Curious. It wouldn't surprise me if scipy was using floats, because 'inf'
is usually a floating point value, not an integer.

Using my test code from yesterday, I got:

 bincoeff(14354,174)
11172777193562324917353367958024437473336018053487854593870
07090637489405604489192488346144684402362344409632515556732
33563523161308145825208276395238764441857829454464446478336
90173777095041891067637551783324071233625370619908633625448
31076677382448616246125346667737896891548166898009878730510
57476139515840542769956414204130692733629723305869285300247
645972456505830620188961902165086857407612722931651840L

Took about three seconds on my system.



 Yes I am calculating hundreds of hypergeometric probabilities so I
 need fast calculations

Another possibility, if you want exact integer maths rather than floating
point with logarithms, is to memoise the binomial coefficients. Something
like this:

# untested
def bincoeff(n,r, \
 cache={}):
try:
return cache((n,r))
except KeyError:
x = 1
for i in range(r+1, n+1):
x *= i
for i in range(1, n-r+1):
x /= i
cache((n,r)) = x
return x


-- 
Steven.

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


  1   2   >