Re: python and JMS

2006-07-30 Thread Ravi Teja
> I am looking to use python to talk to JMS. Can some please point me to
> such resources if this is possible.

JPype
http://jpype.sourceforge.net/

Jython
http://www.jython.org/

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


Re: write()

2006-07-30 Thread Andy Salnikov

"manuhack" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I copied the lines
>
> f=open('/tmp/workfile', 'w')
> print f
> f.close()
>
> from Python 2.4 Documentation 7.2.  But it said IOerror No such file or
> directory" '/tmp/workfile'
>
> Is it something about the os?  I'm using Python 2.4 under WinXP.
> Thanks.  Without / I can open it.
>

  In addition to what others said, if you need to open a temporary file,
it's better to use os.tmpfile() to get a file descriptor and not to
rely on magic file names like '/tmp/workfile'. So instead of open()
you should do:

import os

f = os.tmpfile()

This should work fine of both Windows and UNIX systems.

  Andy.


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


Re: How to force a thread to stop

2006-07-30 Thread H J van Rooyen
"Damjan" <[EMAIL PROTECTED]> wrote:


| > | A common recovery mechanism in embedded systems is a watchdog timer,
| > | which is a hardware device that must be poked by the software every
| > | so often (e.g. by writing to some register).  If too long an interval
| > | goes by without a poke, the WDT hard-resets the cpu.  Normally the
| > | software would poke the WDT from its normal periodic timing routine.
| > | A loop like you describe would stop the timing routine from running,
| > | eventually resulting in a reset.
| >
| > *grin* - Yes of course - if the WDT was enabled - its something that I
| > have not seen on PC's yet...
|
| The intel 810 chipset (and all after that) has a builtin watchdog timer -
| unfortunetally on some motherboards it's disabled (I guess in the BIOS).
|
| How do I know that?
| Once I got Linux installed on a new machine and although the install
| went without a problem, after the first boot the machine would reboot on
| exactly 2 minutes.
| After a bit of poking around I found that hotplug detected the WDT support
| and loaded the driver for it (i8xx_tco), and it seems the WDT chip was set
| to start ticking right away after the driver poked it.

Yikes! "some poking around" - with two minutes to do it in - must have scarred
you for life!

- Hendrik


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


Re: Looking for a regular expression for this...

2006-07-30 Thread Anthra Norell

- Original Message - 
From: <[EMAIL PROTECTED]>
To: 
Sent: Friday, July 28, 2006 10:30 PM
Subject: Looking for a regular expression for this...


> Hi,
> My string is a multi line string that contains "filename
> \n" and "host \n" entries among other things.
> 
> For example: s = """ filename X
> host hostname1
> blah...
> host hostname2
> blah...
> filename Y
> host hostname3
> """
> Given a host name, I would like to get its filename (The closest
> filename reading backwards from the host line). I could read each line
> until I hit the host name, but I am looking for an RE that will do job.
> The answer should be "Y" for host hostname3 and "X" for either host
> hostname1 or hostname2.
> 
> Thanks in advance.
> 
> --Malahal.
> -- 
> http://mail.python.org/mailman/listinfo/python-list


Malahal, may I make this suggestion:

##

>>> import SE  # Cheese Shop

>>> Names_Filter = SE.SE ('  "~filename .*~=(10)=: " "~host .*~==, " ')
>>> print Names_Filter (s)

filename X: host hostname1, host hostname2, 
filename Y: host hostname3, 


Or: Without redundant words:

>>> Names_Filter = SE.SE ('  "~filename .*~=(10)=: " "~host .*~==, "  |  
>>> "filename ="  "host =" ", (10)=(10)"  "~, $~=(10)" ')
>>> print Names_Filter (s)

X: hostname1, hostname2
Y: hostname3


##

Regards

Frederic


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


Re: install python on cdrom

2006-07-30 Thread Martin v. Löwis
Fabian Braennstroem schrieb:
> I look for an easy way to use the newest scipy, pyvtk, matplotlib,
> f2py, numpy, paraview/vtk,... on a entreprise redhat machine
> without administration rights.
> My first thought was to install the whole new python system
> on a cdrom/dvd and mounting it, when I need it. Would that
> be the easiest way? I would be glad to read some
> hints about the way doing it... 

If you have a home directory with sufficient disk space, the
easiest way would be to install Python into your home directory,
assuming administrative policy allows such usage of the
home directory.

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


Re: Newbie..Needs Help

2006-07-30 Thread Anthra Norell
Graham,

Would it help to use another web site? Not as long as the program works on this 
site. If it doesn't it may help to change sites, but
a new reader would have to be crafted. Towards this my code may look 
intimidating. It isn't really a good example for a demo,
because it looks scary. As I said, I experimentally stretched the envelope.
  The trick is to develop incrementally, one step at a time, look at the 
result of each stage, recognize what needs to be done
next and add missing definitions or add a subsequent translation step. In this 
manner a complex system can be built. SE is
particualry accommodating in this respect. You can test an Editor object in 
seconds on the IDLE command line, e.g.:

  >>> s = 'Total: $1,234.55  (-6.7)'

  >>> print SE.SE ('"$=USD " ,=\' .=, ":=   "  )=%)') (s)
  TotalUSD 1'234,55  (-6,7%)

It also helps to read  SE-DOC.HTM which explains a host of basic techniques.

Glad to help

Frederic

- Original Message -
From: "Graham Feeley" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Sunday, July 30, 2006 5:55 AM
Subject: Re: Newbie..Needs Help


> Well Well Well, Anthra you are a clever person, Are
> nt you
> I nearly fell over when i read your post.
> Would it help if we used another web site to gather data
> As you stated the tables are not all that well structured.
> well I will give thisone  a go first and if there is anything I can do for
> you just ask and I will try my best.
> I really appreciate what you have done.
> Of course I will try to follow your code to see if any will fall on
> meLOL
> Regards
> Graham
>
> "Anthra Norell" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >
> > - Original Message -
> > From: "Graham Feeley" <[EMAIL PROTECTED]>
> > Newsgroups: comp.lang.python
> > To: 
> > Sent: Friday, July 28, 2006 5:11 PM
> > Subject: Re: Newbie..Needs Help
> >
> >
> >> Thanks Nick for the reply
> >> Of course my first post was a general posting to see if someone would be
> >> able to help
> >> here is the website which holds the data I require
> >> http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006&meetings=bdgo
> >>
> >> The fields required are as follows
> >>  NSW Tab
> >> #  Win  Place
> >>  2$4.60   $2.40
> >>  5$2.70
> >>  1$1.30
> >>  Quin$23.00
> >>  Tri  $120.70
> >> Field names are
> >> Date   ( not important )
> >> Track= Bendigo
> >> RaceNoon web page
> >> Res1st...2
> >> Res2nd..5
> >> Res3rd..1
> >> Div1..$4.60
> >> DivPlc...$2.40
> >> Div2..$2.70
> >> Div3..$1.30
> >> DivQuin.$23.00
> >> DivTrif...$120.70
> >> As you can see there are a total of 6 meetings involved and I would need
> >> to
> >> put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks
> >>
> >> Hope this more enlightening
> >> Regards
> >> graham
> >>
> >
> > Graham,
> >
> > Only a few days ago I gave someone a push who had a very similar problem.
> > I handed him code ready to run. I am doing it again for
> > you.
> >  The site you use is much harder to interpret than the other one was
> > and so I took the opportunity to experimentally stretch
> > the envelope of a new brain child of mine: a stream editor called SE. It
> > is new and so I also take the opportunity to demo it.
> >  One correspondent in the previous exchange was Paul McGuire, the
> > author of 'pyparse'. He made a good case for using 'pyparse'
> > in situations like yours. Unlike a stream editor, a parser reads structure
> > in addition to data and can relate the data to its
> > context.
> >  Anlayzing the tables I noticed that they are poorly structured: The
> > first column contains both data and ids. Some records are
> > shorter than others, so column ids have to be guessed and hard coded.
> > Missing data sometimes is a dash, sometimes nothing. The
> > inconsistencies seem to be consistent, though, down the eight tables of
> > the page. So they can be formalized with some confidence
> > that they are systematic. If Paul could spend some time on this, I'd be
> > much interested to see how he would handle the relative
> > disorder.
> >  Another thought: The time one invests in developing a program should
> > not exceed the time it can save overall (not talking
> > about recreational programming). Web pages justify an extra measure of
> > caution, because they may change any time and when they do
> > they impose an unscheduled priority every time the reader stops working
> > and requires a revision.
> >
> > So, here is your program. I write it so you can copy the whole thing to a
> > file. Next copy SE from the Cheese Shop. Unzip it and put
> > both SE.PY and SEL.PY where your Python progams are. Then 'execfile' the
> > code in an IDLE window, call 'display_horse_race_data
> > 

Re: python and JMS

2006-07-30 Thread Alan Kennedy
[tksri2000]
> I am looking to use python to talk to JMS. Can some please point me to
> such resources if this is possible.

PyHJB is the python-to-JMS gateway. ... via HJB, the HTTP JMS bridge.
http://hjb.python-hosting.com/

HJB (HTTP JMS Bridge)
http://hjb.berlios.de/

HTH,

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

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


Re: class variables

2006-07-30 Thread Colin J. Williams
Andre Meyer wrote:
> Hi all
> 
> I am trying to understand the magic of Python's class variables and 
> tried the following code (see below).
> 
> Just out of curiosity, I tried to define a property that provides access 
> to a seemingly instancae variable which is in fact a class variable. All 
> seems to work fine (case 4), but when a custom object is assigned, an 
> instance variable is created instead of using theproerty (case 5).
> 
> What goes wrong here? What is the difference between cases 4 and 5? How 
> can case 5 be fixed?
> 
> thanks a lot for your help
> Andre
> 
> Code Listing
> =
> 
> print; print "*** Case 1 ***"; print
> 
> class C1(object):
>
> v = None
>
> def __init__(self, value):
> print '-', self.v
> self.v = value
>
> def value(self):
> return self.v
>
> a1 = C1(1)
> b1 = C1(2)
> print a1.value()
> 
> print; print "*** Case 2 ***"; print
> 
> class C2(object):
>
> v = None
>
> def __init__(self, value):
> print '-', self.v
> self.__class__.v = value
>
> def value(self):
> return self.__class__.v
>
> a2 = C2(1)
> b2 = C2(2)
> print a2.value()
> 
> print; print "*** Case 3 ***"; print
> 
> class C3(object):
>
> v = 5
>
> def __init__(self, value):
> print '-', self.v
> self.v = self.v + value
>
> def value(self):
> return self.v
>
> a3 = C3(1)
> b3 = C3(2)
> print a3.value()
> print a3.v
> print a3.__class__.v
> 
> print; print "*** Case 4 ***"; print
> 
> class V4(list):
> def work(self):
> return 'done'
>
> class C4(object):
>
> def __set_v(self, v): self.__class__.__v = v   
> def __get_v(self): return self.__class__.__v
> def __del_v(self): del self.__class__.__v
> v = property(__get_v, __set_v, __del_v, 'make class variable')
> v = V4()
>
> def __init__(self, value):
> 
> print '-', self.v
> self.v.append(value)
> print '+', self.v
>
> @classmethod
> def value(self):
> print self.v.work()
> return self.v
>
> 
> a4 = C4(1)
> b4 = C4(2)
> print a4.value()
> print a4.v
> print a4.__class__.v
> print a4.v.work()
> 
> 
> print; print "*** Case 5 ***"; print
> 
> class V5(object):
> def __init__(self, i):
> self.i = i
>
> def work(self):
> return 'done', self.i
>
> class C5(object):
>
> def __set_v(self, v): self.__class__.__v = v   
> def __get_v(self): return self.__class__.__v
> def __del_v(self): del self.__class__.__v
> v = property(__get_v, __set_v, __del_v, 'make class variable')
> v = None
>
> def __init__(self, value):
> 
> print '-', self.v
> self.v = V5(value)
> print '+', self.v
> #print self.__class__.__dict__
> #print self.__dict__
>
> @classmethod
> def value(self):
> print self.v.work()
> return self.v
>
> 
> a5 = C5(1)
> b5 = C5(2)
> print a5.value()
> print a5.v
> print a5.__class__.v
> print a5.v.work()
> 
> 
> Output
> =
> 
> 
> *** Case 1 ***
> 
> - None
> - None
> 1
> 
> *** Case 2 ***
> 
> - None
> - 1
> 2
> 
> *** Case 3 ***
> 
> - 5
> - 5
> 6
> 6
> 5
> 
> *** Case 4 ***
> 
> - []
> + [1]
> - [1]
> + [1, 2]
> done
> [1, 2]
> [1, 2]
> [1, 2]
> done
> 
> *** Case 5 ***
> 
> - None
> + <__main__.V5 object at 0x00AFE0D0>
> - None
> + <__main__.V5 object at 0x00AFE110>
> Traceback (most recent call last):
>   File "classvariables.py", line 121, in ?
> print a5.value ()
>   File "classvariables.py", line 115, in value
> print self.v.work()
> AttributeError: 'NoneType' object has no attribute 'work'
> 
André,

I would have expected a5.v to be equal to b5.v, otherwise what is the 
value of a class variable?

I get:
[Dbg]>>> a5.v == b5.v
False

I hope that one of the wizards will respond.

Colin W.

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

Re: Nested function scope problem

2006-07-30 Thread Antoon Pardon
On 2006-07-29, Gerhard Fiedler <[EMAIL PROTECTED]> wrote:
> On 2006-07-29 13:47:37, Antoon Pardon wrote:
>
>> I think the important thing to remember is that the assignment in Python
>> is a alias maker and not a copy maker. In languages like C, Fortran,
>> pascal, the assignment makes a copy from what is on the righthand and
>> stores that in the variable on the lefthand. In languages like Lisp,
>> Smalltalk and Python, the assignment essentially makes the lefthand
>> an alias for the righthand.
>
> Yes, I think I got it now :) 
>
> It seems that, in essence, Bruno is right in that Python doesn't really
> have variables. Everything that seems variable doesn't really change; what
> changes is that an element of what seems to change gets rebound.

Aren't you looking too much at implementation details now?

The difference between an alias assignment and a storage assigment
is for instance totaly irrelevant for immutable objects/values like numbers.

On a language level you can't distinghuish between immutable types
where the implementation uses storage assignment or alias assignment
and a number of language implementation do use different implementation
for different types because of optimisation considerations.

AFAIU, one can also build a C++ class hierarchy that with some small
limitations in used operators, would have semantics very similar to
Python. Would you argue that those using such a C++ class hierarchy would
no longer be using variables in C++?

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


Html character entity conversion

2006-07-30 Thread [EMAIL PROTECTED]
Here is my script:

from mechanize import *
from BeautifulSoup import *
import StringIO
b = Browser()
f = b.open("http://www.translate.ru/text.asp?lang=ru";)
b.select_form(nr=0)
b["source"] = "hello python"
html = b.submit().get_data()
soup = BeautifulSoup(html)
print  soup.find("span", id = "r_text").string

OUTPUT:
привет
питон
--
In russian it looks like:
"привет питон"

How can I translate this using standard Python libraries??

--
Pak Andrei, http://paxoblog.blogspot.com, icq://97449800

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

Re: Nested function scope problem

2006-07-30 Thread Gerhard Fiedler
On 2006-07-30 09:54:14, Antoon Pardon wrote:

> Aren't you looking too much at implementation details now?

Possibly, but at this point I'm still trying to understand how Python does
these things, and what the useful abstraction level is for me. I also still
have very little experience how I'll put the things we've been discussing
here into (Python) practice. While not new to programming, I'm new to
Python.

> AFAIU, one can also build a C++ class hierarchy that with some small
> limitations in used operators, would have semantics very similar to
> Python. Would you argue that those using such a C++ class hierarchy would
> no longer be using variables in C++?

Probably not. But for me it's mostly about useful terminology, not
necessarily "correct" terminology. In order to talk about correct
terminology, we'd have to use a common definition of "variable". This is a
term so widely used that I'm not sure there is a useful single definition
of it; do you know one?

In any case, the following doesn't seem to be implementation detail (and
rather a part of the language), but it's not really understandable with a
C++ concept of "variable":

>>> a=3
>>> id(a)
3368152
>>> b=a
>>> id(b)
3368152
>>> b=4
>>> id(b)
3368140

You don't expect the "identity" of the variable b to change with a simple
assignment from a C/C++ point of view. You also don't expect the "identity"
of a and b to be the same after assigning one to the other. You can create
C++ classes that behave like that (you can implement Python in C++ :), but
that doesn't mean that you expect C++ language constructs to behave like
that.

Gerhard

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


how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread zxo102
Hi everyone,
I am using a python socket server to collect data from a socket
client and then control a image location ( wxpython) with the data,
i.e. moving the image around in the wxpython frame.
   But  the "app.MainLoop()" in wxpython looks like conflicting with
the "while 1:" in socket server. After I commented the
"app.MainLoop()", everything is working except two things:
 1. if I click anywhere on the screen with the mouse, the image is
gong and only the empty frame( or panel) is left.
 2. if I don't  touch anything, the image is being moved around but
the previous images are left behind in the panel.
I guess that may be caused by "app.MainLoop()" commented.
   Anybody knows how to make the two things work together? I really
appreciate your help.
   My sample code is modified based on the wxpython demo: image.py.
socket client is also attached for your reference.

Ouyang

 socket server with wxpython ##

from Main import opj
import wx,string
class MMCS(wx.Frame):
def __init__(self):
self.bmp = wx.Image(opj('bitmaps/image.bmp'),
wx.BITMAP_TYPE_BMP)
self.bmp.SetMask(True)
wx.Frame.__init__(self, parent=None, title='monitoring system',
size=(500,600))
self.panel = wx.Panel(self,-1)

def monitor(self,x,y,angle):
bmp = self.bmp.Rotate(angle, (x,y), True,None)
bmp = bmp.ConvertToBitmap()

wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
bmp.GetHeight()))
del bmp

app = wx.PySimpleApp()
frame = MMCS()
frame.Show()
frame.monitor(50,10,0.0)
#app.MainLoop()

# Server program
from socket import *
# Set the socket parameters
host = "192.168.0.2"
port = 21567
buf = 1024
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"
 d = string.split(data, '-')

frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
if data == 'END':
print "end of moving the ship"

# Close socket
UDPSock.close()

# socket client ##>
rom socket import *
import time

# Set the socket parameters
host = "192.168.0.2"
port = 21567
buf = 1024
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg

# Send messages
while (1):
  for i in range(100):
   time.sleep(1)
   data = "50-100-%s"%(0.1*i)
   if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'."
# Close socket
UDPSock.close()

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread Philippe Martin
zxo102 wrote:

> Hi everyone,
> I am using a python socket server to collect data from a socket
> client and then control a image location ( wxpython) with the data,
> i.e. moving the image around in the wxpython frame.
>But  the "app.MainLoop()" in wxpython looks like conflicting with
> the "while 1:" in socket server. After I commented the
> "app.MainLoop()", everything is working except two things:
>  1. if I click anywhere on the screen with the mouse, the image is
> gong and only the empty frame( or panel) is left.
>  2. if I don't  touch anything, the image is being moved around but
> the previous images are left behind in the panel.
> I guess that may be caused by "app.MainLoop()" commented.
>Anybody knows how to make the two things work together? I really
> appreciate your help.
>My sample code is modified based on the wxpython demo: image.py.
> socket client is also attached for your reference.
> 
> Ouyang
> 
>  socket server with wxpython ##
> 
> from Main import opj
> import wx,string
> class MMCS(wx.Frame):
> def __init__(self):
> self.bmp = wx.Image(opj('bitmaps/image.bmp'),
> wx.BITMAP_TYPE_BMP)
> self.bmp.SetMask(True)
> wx.Frame.__init__(self, parent=None, title='monitoring system',
> size=(500,600))
> self.panel = wx.Panel(self,-1)
> 
> def monitor(self,x,y,angle):
> bmp = self.bmp.Rotate(angle, (x,y), True,None)
> bmp = bmp.ConvertToBitmap()
> 
> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
> bmp.GetHeight()))
> del bmp
> 
> app = wx.PySimpleApp()
> frame = MMCS()
> frame.Show()
> frame.monitor(50,10,0.0)
> #app.MainLoop()
> 
> # Server program
> from socket import *
> # Set the socket parameters
> host = "192.168.0.2"
> port = 21567
> buf = 1024
> addr = (host,port)
> 
> # Create socket and bind to address
> UDPSock = socket(AF_INET,SOCK_DGRAM)
> UDPSock.bind(addr)
> 
> # Receive messages
> while 1:
> data,addr = UDPSock.recvfrom(buf)
> if not data:
> print "Client has exited!"
> break
> else:
> print "\nReceived message '", data,"'"
>  d = string.split(data, '-')
> 
> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
> if data == 'END':
> print "end of moving the ship"
> 
> # Close socket
> UDPSock.close()
> 
> # socket client ##>
> rom socket import *
> import time
> 
> # Set the socket parameters
> host = "192.168.0.2"
> port = 21567
> buf = 1024
> addr = (host,port)
> 
> # Create socket
> UDPSock = socket(AF_INET,SOCK_DGRAM)
> def_msg = "===Enter message to send to server===";
> print "\n",def_msg
> 
> # Send messages
> while (1):
>   for i in range(100):
>time.sleep(1)
> data = "50-100-%s"%(0.1*i)
> if(UDPSock.sendto(data,addr)):
> print "Sending message '",data,"'."
> # Close socket
> UDPSock.close()


If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
You need to have you server in a separate thread.

Philippe


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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread Philippe Martin
Philippe Martin wrote:

> zxo102 wrote:
> 
>> Hi everyone,
>> I am using a python socket server to collect data from a socket
>> client and then control a image location ( wxpython) with the data,
>> i.e. moving the image around in the wxpython frame.
>>But  the "app.MainLoop()" in wxpython looks like conflicting with
>> the "while 1:" in socket server. After I commented the
>> "app.MainLoop()", everything is working except two things:
>>  1. if I click anywhere on the screen with the mouse, the image is
>> gong and only the empty frame( or panel) is left.
>>  2. if I don't  touch anything, the image is being moved around but
>> the previous images are left behind in the panel.
>> I guess that may be caused by "app.MainLoop()" commented.
>>Anybody knows how to make the two things work together? I really
>> appreciate your help.
>>My sample code is modified based on the wxpython demo: image.py.
>> socket client is also attached for your reference.
>> 
>> Ouyang
>> 
>>  socket server with wxpython ##
>> 
>> from Main import opj
>> import wx,string
>> class MMCS(wx.Frame):
>> def __init__(self):
>> self.bmp = wx.Image(opj('bitmaps/image.bmp'),
>> wx.BITMAP_TYPE_BMP)
>> self.bmp.SetMask(True)
>> wx.Frame.__init__(self, parent=None, title='monitoring system',
>> size=(500,600))
>> self.panel = wx.Panel(self,-1)
>> 
>> def monitor(self,x,y,angle):
>> bmp = self.bmp.Rotate(angle, (x,y), True,None)
>> bmp = bmp.ConvertToBitmap()
>> 
>> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
>> bmp.GetHeight()))
>> del bmp
>> 
>> app = wx.PySimpleApp()
>> frame = MMCS()
>> frame.Show()
>> frame.monitor(50,10,0.0)
>> #app.MainLoop()
>> 
>> # Server program
>> from socket import *
>> # Set the socket parameters
>> host = "192.168.0.2"
>> port = 21567
>> buf = 1024
>> addr = (host,port)
>> 
>> # Create socket and bind to address
>> UDPSock = socket(AF_INET,SOCK_DGRAM)
>> UDPSock.bind(addr)
>> 
>> # Receive messages
>> while 1:
>> data,addr = UDPSock.recvfrom(buf)
>> if not data:
>> print "Client has exited!"
>> break
>> else:
>> print "\nReceived message '", data,"'"
>>  d = string.split(data, '-')
>> 
>> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
>> if data == 'END':
>> print "end of moving the ship"
>> 
>> # Close socket
>> UDPSock.close()
>> 
>> # socket client ##>
>> rom socket import *
>> import time
>> 
>> # Set the socket parameters
>> host = "192.168.0.2"
>> port = 21567
>> buf = 1024
>> addr = (host,port)
>> 
>> # Create socket
>> UDPSock = socket(AF_INET,SOCK_DGRAM)
>> def_msg = "===Enter message to send to server===";
>> print "\n",def_msg
>> 
>> # Send messages
>> while (1):
>>   for i in range(100):
>>time.sleep(1)
>> data = "50-100-%s"%(0.1*i)
>> if(UDPSock.sendto(data,addr)):
>> print "Sending message '",data,"'."
>> # Close socket
>> UDPSock.close()
> 
> 
> If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
> You need to have you server in a separate thread.
> 
> Philippe
PS:

http://wiki.wxpython.org/index.cgi/LongRunningTasks

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


Re: metaclass : parse all class once before doing anything else ?

2006-07-30 Thread gene tani

Paddy wrote:
> Laurent Rahuel wrote:
> >
> > Laurent.
>
> I, like Diez am unsure of why you would need what you have asked for,
> but maybe this will help.
>
> You can keep  track of all instances of a class by this kind of thing:
>
> >>> class C1(object):
> ...   inst = []
> ...   def __init__(self):
> ...   self.inst.append(self)
> ...

or list all subclasses with

print LaurentsPutativeMetaClass.__subclasses__()

me 3 for: not clear what you're getting at

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread Grant Edwards
On 2006-07-30, Philippe Martin <[EMAIL PROTECTED]> wrote:

> If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
> You need to have you server in a separate thread.

Isn't there any way to use wxWidgets socket callbacks in wxPython?

-- 
Grant Edwards   grante Yow!  I'm wearing PAMPERS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread zxo102
Philippe,

Thanks a lot. I got the idea. Let me try it.

Ouyang

Philippe Martin 写道:

> Philippe Martin wrote:
>
> > zxo102 wrote:
> >
> >> Hi everyone,
> >> I am using a python socket server to collect data from a socket
> >> client and then control a image location ( wxpython) with the data,
> >> i.e. moving the image around in the wxpython frame.
> >>But  the "app.MainLoop()" in wxpython looks like conflicting with
> >> the "while 1:" in socket server. After I commented the
> >> "app.MainLoop()", everything is working except two things:
> >>  1. if I click anywhere on the screen with the mouse, the image is
> >> gong and only the empty frame( or panel) is left.
> >>  2. if I don't  touch anything, the image is being moved around but
> >> the previous images are left behind in the panel.
> >> I guess that may be caused by "app.MainLoop()" commented.
> >>Anybody knows how to make the two things work together? I really
> >> appreciate your help.
> >>My sample code is modified based on the wxpython demo: image.py.
> >> socket client is also attached for your reference.
> >>
> >> Ouyang
> >>
> >>  socket server with wxpython ##
> >>
> >> from Main import opj
> >> import wx,string
> >> class MMCS(wx.Frame):
> >> def __init__(self):
> >> self.bmp = wx.Image(opj('bitmaps/image.bmp'),
> >> wx.BITMAP_TYPE_BMP)
> >> self.bmp.SetMask(True)
> >> wx.Frame.__init__(self, parent=None, title='monitoring system',
> >> size=(500,600))
> >> self.panel = wx.Panel(self,-1)
> >>
> >> def monitor(self,x,y,angle):
> >> bmp = self.bmp.Rotate(angle, (x,y), True,None)
> >> bmp = bmp.ConvertToBitmap()
> >>
> >> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
> >> bmp.GetHeight()))
> >> del bmp
> >>
> >> app = wx.PySimpleApp()
> >> frame = MMCS()
> >> frame.Show()
> >> frame.monitor(50,10,0.0)
> >> #app.MainLoop()
> >>
> >> # Server program
> >> from socket import *
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket and bind to address
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> UDPSock.bind(addr)
> >>
> >> # Receive messages
> >> while 1:
> >> data,addr = UDPSock.recvfrom(buf)
> >> if not data:
> >> print "Client has exited!"
> >> break
> >> else:
> >> print "\nReceived message '", data,"'"
> >>  d = string.split(data, '-')
> >>
> >> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
> >> if data == 'END':
> >> print "end of moving the ship"
> >>
> >> # Close socket
> >> UDPSock.close()
> >>
> >> # socket client ##>
> >> rom socket import *
> >> import time
> >>
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> def_msg = "===Enter message to send to server===";
> >> print "\n",def_msg
> >>
> >> # Send messages
> >> while (1):
> >>   for i in range(100):
> >>time.sleep(1)
> >> data = "50-100-%s"%(0.1*i)
> >> if(UDPSock.sendto(data,addr)):
> >> print "Sending message '",data,"'."
> >> # Close socket
> >> UDPSock.close()
> >
> >
> > If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
> > You need to have you server in a separate thread.
> >
> > Philippe
> PS:
> 
> http://wiki.wxpython.org/index.cgi/LongRunningTasks

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

Re: Html character entity conversion

2006-07-30 Thread Claudio Grondi
[EMAIL PROTECTED] wrote:
> Here is my script:
> 
> from mechanize import *
> from BeautifulSoup import *
> import StringIO
> b = Browser()
> f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> b.select_form(nr=0)
> b["source"] = "hello python"
> html = b.submit().get_data()
> soup = BeautifulSoup(html)
> print  soup.find("span", id = "r_text").string
> 
> OUTPUT:
> привет
> питон
> --
> In russian it looks like:
> "привет питон"
> 
> How can I translate this using standard Python libraries??
> 
> --
> Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
> 
Translate to what and with what purpose?

Assuming your intention is to get a Python Unicode string, what about:

strHTML = 'привет 
питон'
strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
strUnicode = eval("u'%s'"%strUnicodeHexCode)

?

I am sure, there is a more elegant and direct solution, but just wanted 
to provide here some quick response.

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

Re: Html character entity conversion

2006-07-30 Thread danielx
[EMAIL PROTECTED] wrote:
> Here is my script:
>
> from mechanize import *
> from BeautifulSoup import *
> import StringIO
> b = Browser()
> f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> b.select_form(nr=0)
> b["source"] = "hello python"
> html = b.submit().get_data()
> soup = BeautifulSoup(html)
> print  soup.find("span", id = "r_text").string
>
> OUTPUT:
> привет
> питон
> --
> In russian it looks like:
> "привет питон"
>
> How can I translate this using standard Python libraries??
>
> --
> Pak Andrei, http://paxoblog.blogspot.com, icq://97449800

I'm having trouble understanding how your script works (what would a
"BeautifulSoup" function do?), but assuming your intent is to find
character reference objects in an html document, you might try using
the HTMLParser class in the HTMLParser module. This class delegates
several methods. One of them is handle_charref. It will be called with
one argument, the name of the reference, which includes only the number
part. HTMLParser is alot more powerful than that though. There may be
something more light-weight out there that will accomplish what you
want. Then again, you might be able to find a use for all that power :P.

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

Re: Nested function scope problem

2006-07-30 Thread Antoon Pardon
On 2006-07-30, Gerhard Fiedler <[EMAIL PROTECTED]> wrote:
> On 2006-07-30 09:54:14, Antoon Pardon wrote:
>
>> Aren't you looking too much at implementation details now?
>
> Possibly, but at this point I'm still trying to understand how Python does
> these things, and what the useful abstraction level is for me. I also still
> have very little experience how I'll put the things we've been discussing
> here into (Python) practice. While not new to programming, I'm new to
> Python.
>
>> AFAIU, one can also build a C++ class hierarchy that with some small
>> limitations in used operators, would have semantics very similar to
>> Python. Would you argue that those using such a C++ class hierarchy would
>> no longer be using variables in C++?
>
> Probably not. But for me it's mostly about useful terminology, not
> necessarily "correct" terminology. In order to talk about correct
> terminology, we'd have to use a common definition of "variable". This is a
> term so widely used that I'm not sure there is a useful single definition
> of it; do you know one?

A name in a scope to which is attached some value/object. Now whether
this attachment is in the form of storage or binding is IMO not
that important.

> In any case, the following doesn't seem to be implementation detail (and
> rather a part of the language), but it's not really understandable with a
> C++ concept of "variable":
>
 a=3
 id(a)
> 3368152
 b=a
 id(b)
> 3368152
 b=4
 id(b)
> 3368140
>
> You don't expect the "identity" of the variable b to change with a simple
> assignment from a C/C++ point of view.

That depends on what you call the identity. If I had to translate this
into C++ it would be something like:

  int *a, *b;

  a = MakeInt(3);
  b = a;
  b = MakeInt(4);

AFAIU, you can wrap these int pointers into some kind of class, so that
they behave as you would expect integers to behave. The id(a) would just
return a, the address of where the integer is stored.

Now whether this is helpfull or not for you in understanding the python
behaviour, I don't know. So if you think this is mixing to many things
I'll drop it.

> You also don't expect the "identity"
> of a and b to be the same after assigning one to the other. You can create
> C++ classes that behave like that (you can implement Python in C++ :),

I'm sorry but IMO you there is no connection between those two.
C doesn't have classes, yet you can still implement Python in C.

> but
> that doesn't mean that you expect C++ language constructs to behave like
> that.

If you have implemented it with that purpose, you do.

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


Re: class variables

2006-07-30 Thread faulkner
python != java.
when you say "self.v = ...", you mask the class attribute with an
instance attribute.
say "C1.v = ...".

Colin J. Williams wrote:
> Andre Meyer wrote:
> > Hi all
> >
> > I am trying to understand the magic of Python's class variables and
> > tried the following code (see below).
> >
> > Just out of curiosity, I tried to define a property that provides access
> > to a seemingly instancae variable which is in fact a class variable. All
> > seems to work fine (case 4), but when a custom object is assigned, an
> > instance variable is created instead of using theproerty (case 5).
> >
> > What goes wrong here? What is the difference between cases 4 and 5? How
> > can case 5 be fixed?
> >
> > thanks a lot for your help
> > Andre
> >
> > Code Listing
> > =
> >
> > print; print "*** Case 1 ***"; print
> >
> > class C1(object):
> >
> > v = None
> >
> > def __init__(self, value):
> > print '-', self.v
> > self.v = value
> >
> > def value(self):
> > return self.v
> >
> > a1 = C1(1)
> > b1 = C1(2)
> > print a1.value()
> >
> > print; print "*** Case 2 ***"; print
> >
> > class C2(object):
> >
> > v = None
> >
> > def __init__(self, value):
> > print '-', self.v
> > self.__class__.v = value
> >
> > def value(self):
> > return self.__class__.v
> >
> > a2 = C2(1)
> > b2 = C2(2)
> > print a2.value()
> >
> > print; print "*** Case 3 ***"; print
> >
> > class C3(object):
> >
> > v = 5
> >
> > def __init__(self, value):
> > print '-', self.v
> > self.v = self.v + value
> >
> > def value(self):
> > return self.v
> >
> > a3 = C3(1)
> > b3 = C3(2)
> > print a3.value()
> > print a3.v
> > print a3.__class__.v
> >
> > print; print "*** Case 4 ***"; print
> >
> > class V4(list):
> > def work(self):
> > return 'done'
> >
> > class C4(object):
> >
> > def __set_v(self, v): self.__class__.__v = v
> > def __get_v(self): return self.__class__.__v
> > def __del_v(self): del self.__class__.__v
> > v = property(__get_v, __set_v, __del_v, 'make class variable')
> > v = V4()
> >
> > def __init__(self, value):
> >
> > print '-', self.v
> > self.v.append(value)
> > print '+', self.v
> >
> > @classmethod
> > def value(self):
> > print self.v.work()
> > return self.v
> >
> >
> > a4 = C4(1)
> > b4 = C4(2)
> > print a4.value()
> > print a4.v
> > print a4.__class__.v
> > print a4.v.work()
> >
> >
> > print; print "*** Case 5 ***"; print
> >
> > class V5(object):
> > def __init__(self, i):
> > self.i = i
> >
> > def work(self):
> > return 'done', self.i
> >
> > class C5(object):
> >
> > def __set_v(self, v): self.__class__.__v = v
> > def __get_v(self): return self.__class__.__v
> > def __del_v(self): del self.__class__.__v
> > v = property(__get_v, __set_v, __del_v, 'make class variable')
> > v = None
> >
> > def __init__(self, value):
> >
> > print '-', self.v
> > self.v = V5(value)
> > print '+', self.v
> > #print self.__class__.__dict__
> > #print self.__dict__
> >
> > @classmethod
> > def value(self):
> > print self.v.work()
> > return self.v
> >
> >
> > a5 = C5(1)
> > b5 = C5(2)
> > print a5.value()
> > print a5.v
> > print a5.__class__.v
> > print a5.v.work()
> >
> >
> > Output
> > =
> >
> >
> > *** Case 1 ***
> >
> > - None
> > - None
> > 1
> >
> > *** Case 2 ***
> >
> > - None
> > - 1
> > 2
> >
> > *** Case 3 ***
> >
> > - 5
> > - 5
> > 6
> > 6
> > 5
> >
> > *** Case 4 ***
> >
> > - []
> > + [1]
> > - [1]
> > + [1, 2]
> > done
> > [1, 2]
> > [1, 2]
> > [1, 2]
> > done
> >
> > *** Case 5 ***
> >
> > - None
> > + <__main__.V5 object at 0x00AFE0D0>
> > - None
> > + <__main__.V5 object at 0x00AFE110>
> > Traceback (most recent call last):
> >   File "classvariables.py", line 121, in ?
> > print a5.value ()
> >   File "classvariables.py", line 115, in value
> > print self.v.work()
> > AttributeError: 'NoneType' object has no attribute 'work'
> >
> André,
>
> I would have expected a5.v to be equal to b5.v, otherwise what is the
> value of a class variable?
>
> I get:
> [Dbg]>>> a5.v == b5.v
> False
> 
> I hope that one of the wizards will respond.
> 
> Colin W.

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread bryanjugglercryptographer

Philippe Martin wrote:
> Philippe Martin wrote:
> > You need to have you server in a separate thread.
> PS:
>
> http://wiki.wxpython.org/index.cgi/LongRunningTasks


And here's an important bit from the wxWindows doc:

  For communication between secondary threads and the main thread,
  you may use wxEvtHandler::AddPendingEvent or its short version
  wxPostEvent. These functions have thread safe implementation
  [...]
  

Calling various wxWindows functions from threads other than the
one that runs the GUI, can cause a crash. Use only those that the
authoritative documentation states to be thread-safe, such as
wxPostEvent. The Wiki page that Pilippe cited says that
wxCallAfter uses wxPostEvent internally, so it should also be
thread-safe. I still wouldn't use it; internals are subject to
change.


-- 
--Bryan

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


Re: How do you implement this Python idiom in C++

2006-07-30 Thread alainpoint

Pierre Barbier de Reuille wrote:
> [EMAIL PROTECTED] wrote:
> > Rob Williscroft wrote:
> >
> >> If this is more than idle curiosity I strongly suggest you post
> >> a version of the python code you need to translate to C++.
> >
> > For the moment this is just healthy curiosity but i will still post the
> > code i would like to see translated:
> >
> > class Parent:
> > count=0
> > def __init__(self):
> > self.__class__.count +=1
> > @classmethod
> > def getcount(cls):
> > return cls.count
> >
> > class Child(Parent):
> > count=0 # replace this line by a 'pass'  statement if you don't want
> > to reinitialise the count
> >
> > a=Parent()
> > b=Parent()
> > print Parent.getcount()  # you get 2
> > c=Child()
> > d=Child()
> > e=Child()
> > print Child.getcount() # you get 3 (you could get 5 if you don't
> > reinitialise the count)
> >
> > This is as simple as it can get. I just derive from Parent and i get my
> > proper count (added to my parent's if i wish so).
> > I wish i could achieve such a code purity in C++.
>
> Well, I hope you understand that this code "purity" is possible only
> because of the *dynamic* lookup of the variable name ... Thus, the same
> function, once compiled, will be able to determine, at runtime, where
> the current variable lies ... At the same time, tries, in Python, to
> achieve the count of *all* the instances of a class, meaning that you want :
>
> a = Parent()
> b = Child()
> c = Parent()
> d = Child()
> print Child.getcount() # 2
> print Parent.getcount() # 4
>
> That time, the automatic name lookup will come in the way as you cannot
> have two "count" variables accessible from the same class.
> For C++ the problem is inverse, you have a way to obtain the second
> thing (using templates or macro), but the first is harder.
>
> Pierre
>
> PS: here is my solution in C++
>
>
> #include 
> using namespace std;
>
> template 
> struct Counted
> {
>   Counted() { ++count; }
>   Counted( Counted const& ) { ++count; }
>   virtual ~Counted() { --count; }
>   static size_t getCount() { return count; }
> protected:
>   static size_t count;
> };
>
> template 
> size_t Counted::count = 0;
>
> struct cA : public Counted
> {
>   int a;
> };
>
> struct cB : public Counted, public cA
> {
>   // Needed to be sure of which getCount is called in cB
>   using Counted::getCount;
> };
>
> int main()
> {
>   cA a,b,c;
>   cB d,e,f;
>   a.a = 1;
>   b.a = 1;
>   c.a = 1;
>   d.a = 1;
>   e.a = 1;
>   f.a = 1;
> {
> cA g;
> g.a = 1;
> cout << "#cA = " << cA::getCount() << endl; // 7
> cout << "#cB = " << cB::getCount() << endl; // 3
> }
>   cout << "#cA = " << cA::getCount() << endl; // 6
>   cout << "#cB = " << cB::getCount() << endl; // 3
>   return 0;
> }

I thank you for your response. The equivalent of your solution is
posted hereunder:
class cA(object):
count=0
def __init__(self):
self.__class__.count +=1
@classmethod
def getcount(cls):
return cls.count
def __del__(self):
self.__class__.count -=1
class cB(cA):
count=0
def __init__(self):
super(cB,self).__init__()
for klass in self.__class__.__bases__:
klass.count +=1

a=cA() ; b=cA(); c= cA()
d=cB() ; e=cB(); f= cB()
a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
g=cA()
g.a=1
print  '#cA=',cA.getcount()  # 7
print '#cB=',cB.getcount() #  3
del g
print  '#cA=',cA.getcount()  # 6
print '#cB=',cB.getcount() #  3

There is nothing impossible in Python ;-)

Alain

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


Re: Fastest Way To Loop Through Every Pixel

2006-07-30 Thread Chaos

Paul McGuire wrote:
> "Paul McGuire" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > "Chaos" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> > >
> > >
> > > myCol = (0.3 * image.GetRed(thisX, thisY)) + (0.59 *
> > > image.GetGreen(thisX, thisY)) + (0.11 * image.GetBlue(thisX, thisY))
> > > if myCol < darkestCol:
> > >darkestCol = myCol
> > >possX = thisX
> > >possY = thisY
> > >
> >
> > Psyco may be of some help to you, especially if you extract out your myCol
> > expression into its own function, something like:
> >
> > def darkness(img,x,y):
> > return  (0.3 * img.GetRed(x,y)) + (0.59 * img.GetGreen(x,y)) + (0.11 *
> > img.GetBlue(x,y))
> >
> 
>
> Even better than my other suggestions might be to write this function, and
> then wrap it in a memoizing decorator
> (http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622
> 201abfac735ea47ffade5) - surely there must be some repeated colors in your
> image.
>
> -- Paul

Its not only finding the darkest color, but also finding the X position
and Y Position of the darkest color.

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


Re: Html character entity conversion

2006-07-30 Thread [EMAIL PROTECTED]

Claudio Grondi wrote:
> [EMAIL PROTECTED] wrote:
> > Here is my script:
> >
> > from mechanize import *
> > from BeautifulSoup import *
> > import StringIO
> > b = Browser()
> > f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> > b.select_form(nr=0)
> > b["source"] = "hello python"
> > html = b.submit().get_data()
> > soup = BeautifulSoup(html)
> > print  soup.find("span", id = "r_text").string
> >
> > OUTPUT:
> > привет
> > питон
> > --
> > In russian it looks like:
> > "привет питон"
> >
> > How can I translate this using standard Python libraries??
> >
> > --
> > Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
> >
> Translate to what and with what purpose?
>
> Assuming your intention is to get a Python Unicode string, what about:
>
> strHTML = 'привет
> питон'
> strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
> strUnicode = eval("u'%s'"%strUnicodeHexCode)
>
> ?
>
> I am sure, there is a more elegant and direct solution, but just wanted
> to provide here some quick response.
>
> Claudio Grondi

Thank you, Claudio.
Really interest solution, but it doesn't work...

In [19]: strHTML = 'привет
питон'

In [20]: strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')

In [21]: strUnicode = eval("u'%s'"%strUnicodeHexCode)

In [22]: print strUnicode
---
exceptions.UnicodeEncodeErrorTraceback (most
recent call last)

C:\Documents and Settings\dron\

C:\usr\lib\encodings\cp866.py in encode(self, input, errors)
 16 def encode(self,input,errors='strict'):
 17
---> 18 return codecs.charmap_encode(input,errors,encoding_map)
 19
 20 def decode(self,input,errors='strict'):

UnicodeEncodeError: 'charmap' codec can't encode characters in position
0-5: character maps to 

In [23]: print strUnicode.encode("utf-8")
сВЗсВИсВАсБ┤сБ╖сВР сВЗсВАсВРсВЖсВЕ
<-- it's not my string "привет питон"

In [24]: strUnicode.encode("utf-8")
Out[24]:
'\xe1\x82\x87\xe1\x82\x88\xe1\x82\x80\xe1\x81\xb4\xe1\x81\xb7\xe1\x82\x90
\xe1\x82\x87\xe1\x82\x80\xe1\x82\x90\xe1\x82\x86\xe1\x82\
x85' <-- and too many chars

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

Re: Html character entity conversion

2006-07-30 Thread [EMAIL PROTECTED]
danielx wrote:
> [EMAIL PROTECTED] wrote:
> > Here is my script:
> >
> > from mechanize import *
> > from BeautifulSoup import *
> > import StringIO
> > b = Browser()
> > f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> > b.select_form(nr=0)
> > b["source"] = "hello python"
> > html = b.submit().get_data()
> > soup = BeautifulSoup(html)
> > print  soup.find("span", id = "r_text").string
> >
> > OUTPUT:
> > привет
> > питон
> > --
> > In russian it looks like:
> > "привет питон"
> >
> > How can I translate this using standard Python libraries??
> >
> > --
> > Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
>
> I'm having trouble understanding how your script works (what would a
> "BeautifulSoup" function do?), but assuming your intent is to find
> character reference objects in an html document, you might try using
> the HTMLParser class in the HTMLParser module. This class delegates
> several methods. One of them is handle_charref. It will be called with
> one argument, the name of the reference, which includes only the number
> part. HTMLParser is alot more powerful than that though. There may be
> something more light-weight out there that will accomplish what you
> want. Then again, you might be able to find a use for all that power :P.

Thank you for response.
It doesn't matter what is 'BeautifulSoup'...
General question is:

How can I convert encoded string

sEncodedHtmlText = 'привет
питон'

into human readable:

sDecodedHtmlText  == 'привет питон'

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

Re: How do you implement this Python idiom in C++

2006-07-30 Thread Pierre Barbier de Reuille
[EMAIL PROTECTED] wrote:
> Pierre Barbier de Reuille wrote:
[...]
> 
> I thank you for your response. The equivalent of your solution is
> posted hereunder:
> class cA(object):
> count=0
> def __init__(self):
> self.__class__.count +=1
> @classmethod
> def getcount(cls):
> return cls.count
>   def __del__(self):
>   self.__class__.count -=1
> class cB(cA):
> count=0
> def __init__(self):
>   super(cB,self).__init__()
>   for klass in self.__class__.__bases__:
>   klass.count +=1
> 
> a=cA() ; b=cA(); c= cA()
> d=cB() ; e=cB(); f= cB()
> a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
> g=cA()
> g.a=1
> print  '#cA=',cA.getcount()  # 7
> print '#cB=',cB.getcount() #  3
> del g
> print  '#cA=',cA.getcount()  # 6
> print '#cB=',cB.getcount() #  3
> 
> There is nothing impossible in Python ;-)
> 
> Alain
> 

Well, nothing is impossible, but it is now much much more complex ! As a
proof of that, your version does not work completely :P (try deleting d
for example).

I add a working version, but you will also notice that I have to
*explicitly* walk over all the classes of the hierarchy, testing for the
one who have a "count" attribute, hoping that this attribute is indeed
for counting the number of objects and not anything else ... so the
solution is quite fragile and very slow.

class cA(object):
count=0
def __init__(self):
self.__class__.count +=1
for klass in self.__class__.__bases__:
if hasattr( klass, "count" ):
klass.count += 1

@classmethod
def getcount(cls):
return cls.count
def __del__(self):
self.__class__.count -=1
for klass in self.__class__.__bases__:
if hasattr( klass, "count" ):
klass.count -= 1
class cB(cA):
count=0

a=cA() ; b=cA(); c= cA()
d=cB() ; e=cB(); f= cB()
a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
g=cA()
g.a=1
print  '#cA=',cA.getcount()  # 7
print '#cB=',cB.getcount() #  3
del g
del d
print  '#cA=',cA.getcount()  # 5
print '#cB=',cB.getcount() #  2

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


Re: Nested function scope problem

2006-07-30 Thread Gerhard Fiedler
On 2006-07-30 12:45:50, Antoon Pardon wrote:

>> [...] we'd have to use a common definition of "variable". This is a term
>> so widely used that I'm not sure there is a useful single definition of
>> it; do you know one?
> 
> A name in a scope to which is attached some value/object. Now whether
> this attachment is in the form of storage or binding is IMO not
> that important.

IMO this is not a useful definition of "variable", as it also includes what
some languages would call a "constant". This definition even includes
preprocessor macros. Once you try to come up with a definition that does
not include these, it probably gets trickier.


>> In any case, the following doesn't seem to be implementation detail (and
>> rather a part of the language), but it's not really understandable with a
>> C++ concept of "variable":
>>
> a=3
> id(a)
>> 3368152
> b=a
> id(b)
>> 3368152
> b=4
> id(b)
>> 3368140
>>
>> You don't expect the "identity" of the variable b to change with a simple
>> assignment from a C/C++ point of view.
> 
> That depends on what you call the identity. If I had to translate this
> into C++ it would be something like:
> 
>   int *a, *b;
> 
>   a = MakeInt(3);
>   b = a;
>   b = MakeInt(4);

Yup. But in C/C++ speak, it's more common to call a and b "pointers" rather
than "variables". Of course they are also sometimes called "pointer
variables", but not usually "variables". It's of course not technically
wrong to call the variables, but it's probably rare. And for a reason. 


>> but that doesn't mean that you expect C++ language constructs to behave
>> like that.
> 
> If you have implemented it with that purpose, you do.

I'm not sure an implementation of C++ that behaves like Python when
handling ints is still C++. 


I'm not sure where you're trying to go. I think that most people (and even
Bruno, who argued this issue most strongly) call Python variables
"variables" every now and then, or maybe even usually. But it was helpful
for me to see the difference between Python variables and, say, C
variables. I think this has been a useful discussion in this respect. There
is a difference, and it is important (IMO). 

Whether Python variables are in fact "variables" probably depends mostly on
your definition of "variable", and that's IMO a tough one -- a definition
of "variable" that includes all those language elements that various
languages call "variables", and nothing else (that's the tough part).
Whether that definition exists, and whether it includes Python "variables",
remains to be seen :)

Gerhard

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


Re: Smaple of recursive directory walker

2006-07-30 Thread Ant

Traveler wrote:
> yes this is great i will work from that but how can i use say a list
> to pass 10 words?
>
> mylist = ['word1','word2','word3','word4']
...
> >for root, dirs, files in os.walk('~/mydir'):
> >for file in [f for f in files if f.endswith(".txt")]:
> >fh = open(file)
> >for line in fh:
> ># Search for words.
> >fh.close()

The following will allow you to search a line of text for one of a list
of words.

import re

line = "line of text"
mylist = ["bogus", "text", "here"]

p = re.compile(r"\b(%s)\b" % '|'.join(mylist))
m = p.search(line)
if m: print "Found %s" % m.group(1)

Alternatively, the following will give a list of all words in a string
that appear in the list:

words_found = [word for word in re.split(r"\W+", line) if word in
mylist]

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


Mouse LED Control in Python

2006-07-30 Thread semagraw
I found this link that describes the byte arrays to control the
IM/Email Leds on my Logitech MX610 mouse:

http://www.kdedevelopers.org/node/2029

The link to the tarball is dead so I can't look at that.  Is there
anyway to do what the link says in Python? If you follow the link
above, it talks about 'sending the byte array to 0x10 (16)'.  I'm not
sure if that is possible in python.  Can anyone help or point me in the
right direction?  I'd also be willing to have this be done in another
language and just call different programs from a python program when I
need something specific done (IM light on, for example).



Text from the link if you can't be bothered to follow it:

"I've figured out the IM led now. As before, you send 6 bytes to report
ID 0x10
(16), followed by the "confirm" message.

The magic values are:
unsigned char confirm[6] = { 0x01, 0x80, 0x52, 0x00, 0x00, 0x00 };
unsigned char email_off[6] = { 0x01, 0x80, 0x52, 0x06, 0x00, 0x00 };
unsigned char email_on[6] = { 0x01, 0x80, 0x52, 0x05, 0x00, 0x00 };
unsigned char email_pulse[6] = { 0x01, 0x80, 0x52, 0x04, 0x00, 0x00 };
unsigned char email_flash[6] = { 0x01, 0x80, 0x52, 0x03, 0x00, 0x00 };
unsigned char email_instanton[6] = { 0x01, 0x80, 0x52, 0x02, 0x00, 0x00
};
unsigned char email_instantoff[6] = { 0x01, 0x80, 0x52, 0x01, 0x00,
0x00 };

unsigned char im_off[6] = { 0x01, 0x80, 0x52, 0x00, 0x06, 0x00 };
unsigned char im_on[6] = { 0x01, 0x80, 0x52, 0x00, 0x05, 0x00 };
unsigned char im_pulse[6] = { 0x01, 0x80, 0x52, 0x00, 0x04, 0x00 };
unsigned char im_flash[6] = { 0x01, 0x80, 0x52, 0x00, 0x03, 0x00 };
unsigned char im_instantoff[6] = { 0x01, 0x80, 0x52, 0x00, 0x01, 0x00
};
unsigned char im_instanton[6] = { 0x01, 0x80, 0x52, 0x00, 0x02, 0x00
};"


Thanks,

Jeff

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


BCD List to HEX List

2006-07-30 Thread Philippe Martin
Hi,

I'm looking for an algo that would convert a list such as:

I'm using python to prototype the algo: this will move to C in an embedded
system where an int has 16 bits - I do not wish to use any python library.

l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
l2 = func (l1)
# l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687


Regards,

Philippe

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread Philippe Martin
Grant Edwards wrote:

> On 2006-07-30, Philippe Martin <[EMAIL PROTECTED]> wrote:
> 
>> If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
>> You need to have you server in a separate thread.
> 
> Isn't there any way to use wxWidgets socket callbacks in wxPython?
> 
> --
> Grant Edwards   grante Yow!  I'm wearing
> PAMPERS!!
>   at
>visi.com

If I understand correctly, I guess you can send an event to the main thread
to tell it there was data received.

Regards,

Philippe

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


Re: Html character entity conversion

2006-07-30 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> Here is my script:
> 
> from mechanize import *
> from BeautifulSoup import *
> import StringIO
> b = Browser()
> f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> b.select_form(nr=0)
> b["source"] = "hello python"
> html = b.submit().get_data()
> soup = BeautifulSoup(html)
> print  soup.find("span", id = "r_text").string
> 
> OUTPUT:
> привет
> питон
> --
> In russian it looks like:
> "привет питон"
> 
> How can I translate this using standard Python libraries??

Have you tried a more recent version of BeautifulSoup?  IIRC current
versions always decode text to unicode objects before returning them.

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

Re: BCD List to HEX List

2006-07-30 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Philippe Martin wrote:

> I'm looking for an algo that would convert a list such as:
> 
> I'm using python to prototype the algo: this will move to C in an embedded
> system where an int has 16 bits - I do not wish to use any python library.
> 
> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> l2 = func (l1)
> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687

def func(x):
result = list(x)
result[2:4] = [0xd]
result[-1], result[-2] = result[-2], result[-1]
return result

l1 = [1, 2, 3, 4, 6, 7, 8]
l2 = func(l1)
print l2

And now please describe you problem a little better.  ;-)

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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Marc 'BlackJack' Rintsch wrote:

> In <[EMAIL PROTECTED]>, Philippe Martin wrote:
> 
>> I'm looking for an algo that would convert a list such as:
>> 
>> I'm using python to prototype the algo: this will move to C in an
>> embedded system where an int has 16 bits - I do not wish to use any
>> python library.
>> 
>> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
>> l2 = func (l1)
>> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> 
> def func(x):
> result = list(x)
> result[2:4] = [0xd]
> result[-1], result[-2] = result[-2], result[-1]
> return result
> 
> l1 = [1, 2, 3, 4, 6, 7, 8]
> l2 = func(l1)
> print l2
> 
> And now please describe you problem a little better.  ;-)
> 
> Ciao,
> Marc 'BlackJack' Rintsch

I'll try.

first of all python is not going to be used for my purpose (sigh)

I have device A which holds a binary coded decimal array [N1,N2,Nn]
where the array represents a decimal number.

In C: unsigned char dec[] = {1,2,3,4,5,6,7,8};

I need that array converted for device B into an array where each element
represents the actual byte value.

In C: the result would be unsigned char hex[] = {0x1,0x2,0xD,0x6,0x8,0x7};

I guess any pocket calculator goes through that process for dec/hex
conversion.

Hope that's clearer.

Regards,

Philippe



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


Re: Smaple of recursive directory walker

2006-07-30 Thread Traveler
Thank you very much that is what i was looking for.


On 30 Jul 2006 13:18:51 -0700, "Ant" <[EMAIL PROTECTED]> wrote:

>
>Traveler wrote:
>> yes this is great i will work from that but how can i use say a list
>> to pass 10 words?
>>
>> mylist = ['word1','word2','word3','word4']
>...
>> >for root, dirs, files in os.walk('~/mydir'):
>> >for file in [f for f in files if f.endswith(".txt")]:
>> >fh = open(file)
>> >for line in fh:
>> ># Search for words.
>> >fh.close()
>
>The following will allow you to search a line of text for one of a list
>of words.
>
>import re
>
>line = "line of text"
>mylist = ["bogus", "text", "here"]
>
>p = re.compile(r"\b(%s)\b" % '|'.join(mylist))
>m = p.search(line)
>if m: print "Found %s" % m.group(1)
>
>Alternatively, the following will give a list of all words in a string
>that appear in the list:
>
>words_found = [word for word in re.split(r"\W+", line) if word in
>mylist]

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


Re: BCD List to HEX List

2006-07-30 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Philippe Martin wrote:

> Marc 'BlackJack' Rintsch wrote:
> 
>> And now please describe you problem a little better.  ;-)
> 
> I'll try.
> 
> first of all python is not going to be used for my purpose (sigh)
> 
> I have device A which holds a binary coded decimal array [N1,N2,Nn]
> where the array represents a decimal number.
> 
> In C: unsigned char dec[] = {1,2,3,4,5,6,7,8};
> 
> I need that array converted for device B into an array where each element
> represents the actual byte value.
> 
> In C: the result would be unsigned char hex[] = {0x1,0x2,0xD,0x6,0x8,0x7};
> 
> I guess any pocket calculator goes through that process for dec/hex
> conversion.
> 
> Hope that's clearer.

Not really.  Maybe I'm missing something obvious but I don't see the link
between your `dec` and `hex` values.  12345678 converted to hex is
bc614e.  Do you need such a conversion?  And should the result really be
one nibble (4 bit)/hex digit per array entry!?

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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Marc 'BlackJack' Rintsch wrote:

> In <[EMAIL PROTECTED]>, Philippe Martin wrote:
> 
>> Marc 'BlackJack' Rintsch wrote:
>> 
>>> And now please describe you problem a little better.  ;-)
>> 
>> I'll try.
>> 
>> first of all python is not going to be used for my purpose (sigh)
>> 
>> I have device A which holds a binary coded decimal array [N1,N2,Nn]
>> where the array represents a decimal number.
>> 
>> In C: unsigned char dec[] = {1,2,3,4,5,6,7,8};
>> 
>> I need that array converted for device B into an array where each element
>> represents the actual byte value.
>> 
>> In C: the result would be unsigned char hex[] =
>> {0x1,0x2,0xD,0x6,0x8,0x7};
>> 
>> I guess any pocket calculator goes through that process for dec/hex
>> conversion.
>> 
>> Hope that's clearer.
> 
> Not really.  Maybe I'm missing something obvious but I don't see the link
> between your `dec` and `hex` values.  12345678 converted to hex is
> bc614e.  Do you need such a conversion?  And should the result really be
> one nibble (4 bit)/hex digit per array entry!?
> 
> Ciao,
> Marc 'BlackJack' Rintsch

My apologies, I clearly made a mistake with my calculator, yes the resulting
array I would need is [0xb,0xc,0x6,0x1,0x4,0xe]

Regards,

Philippe



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


Re: BCD List to HEX List

2006-07-30 Thread John Machin
Philippe Martin wrote:
> Hi,
>
> I'm looking for an algo that would convert a list such as:

Such as what?

>
> I'm using python to prototype the algo: this will move to C in an embedded
> system where an int has 16 bits - I do not wish to use any python library.
>
> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678

Does it??? How do you represent the decimal number 12349678, then?

> l2 = func (l1)
> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>

I'm sorry, but very little of that makes any sense to me:

1. I thought BCD meant something very much like this:
http://en.wikipedia.org/wiki/Binary-coded_decimal

2. >>> [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
[1, 2, 13, 6, 8, 7]

So [1], [2], [6] are unchanged, [3, 4] -> [13] (or maybe [3, 4, 5] ->
13),  and [7, 8] -> [8,7].

I doubt very much that there's an algorithm to do that. What is the
relationship between 1234(maybe 5)678 and 0x12D687??? I would expect
something like this::

0x12345678 (stored in 4 bytes 0x12, ..., 0x78)  -- or 0x21436587
or
0x012345678s (where s is a "sign" nibble; stored in 5 bytes 0x01,
..., 0x8s)

IOW something regular and explicable ...

3. Perhaps it might be a good idea if you told us what the *real*
problem is, including *exact* quotes from the manual for the embedded
system. You evidently need/want to convert from one representation of
signed? unsigned? integers to another. Once we all understand *what*
those representations are, *then* we can undoubtedly help you with
pseudocode in the form of Python code manipulating lists or whatever.

Cheers,
John

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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> Philippe Martin wrote:
>> Hi,
>>
>> I'm looking for an algo that would convert a list such as:
> 
> Such as what?
> 
>>
>> I'm using python to prototype the algo: this will move to C in an
>> embedded system where an int has 16 bits - I do not wish to use any
>> python library.
>>
>> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> 
> Does it??? How do you represent the decimal number 12349678, then?
> 
>> l2 = func (l1)
>> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>>
> 
> I'm sorry, but very little of that makes any sense to me:
> 
> 1. I thought BCD meant something very much like this:
> http://en.wikipedia.org/wiki/Binary-coded_decimal
> 
> 2. >>> [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> [1, 2, 13, 6, 8, 7]
> 
> So [1], [2], [6] are unchanged, [3, 4] -> [13] (or maybe [3, 4, 5] ->
> 13),  and [7, 8] -> [8,7].
> 
> I doubt very much that there's an algorithm to do that. What is the
> relationship between 1234(maybe 5)678 and 0x12D687??? I would expect
> something like this::
> 
> 0x12345678 (stored in 4 bytes 0x12, ..., 0x78)  -- or 0x21436587
> or
> 0x012345678s (where s is a "sign" nibble; stored in 5 bytes 0x01,
> ..., 0x8s)
> 
> IOW something regular and explicable ...
> 
> 3. Perhaps it might be a good idea if you told us what the *real*
> problem is, including *exact* quotes from the manual for the embedded
> system. You evidently need/want to convert from one representation of
> signed? unsigned? integers to another. Once we all understand *what*
> those representations are, *then* we can undoubtedly help you with
> pseudocode in the form of Python code manipulating lists or whatever.
> 
> Cheers,
> John


Hi,

>From my answer to Marc:

>My apologies, I clearly made a mistake with my calculator, yes the
>resulting
>array I would need is [0xb,0xc,0x6,0x1,0x4,0xe]



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


Execution timeout

2006-07-30 Thread lorenzo . viscanti
X-No-Archive: yes

Hi,
I'm using feedparser to parse some xml feeds.
As others reported
(http://sourceforge.net/tracker/index.php?func=detail&aid=1519461&group_id=112328&atid=661937
) the library halts while parsing some feeds.

To overcome this issue I was thinking about creating some kind of
wrapper for feedparser that encapsulates a timeout.
So after launching the parse method wait a few seconds and if the
control does not return mark the feed as bad.
I haven't much experience with Python so I'm not able to code it, any
hint?

Is there a better method to avoid this kind of problem?

Thanks,
Lorenzo

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


Re: BCD List to HEX List

2006-07-30 Thread Paul Rubin
Philippe Martin <[EMAIL PROTECTED]> writes:
> I'm using python to prototype the algo: this will move to C in an embedded
> system where an int has 16 bits - I do not wish to use any python library.
> 
> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678

This is untested, but should give you the idea:

First, convert that list to a decimal digit string:

   s = ''.join(map(str, l1))

Then convert the string to an integer:

   n = int(s)# base 10 is the default

Then convert the integer to a hex digit string:

   h = '%X' % n

Finally, convert the hex digit string to a list of integer values of the
individual digits:

   vlist = [int(d, 16) for d in h]

This is the list you want.

If you prefer, You can do it all in one line:

   vlist = [int(d, 16) for d in ('%X' % int(''.join(map(str, l1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Paul Rubin wrote:

> Philippe Martin <[EMAIL PROTECTED]> writes:
>> I'm using python to prototype the algo: this will move to C in an
>> embedded system where an int has 16 bits - I do not wish to use any
>> python library.
>> 
>> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> 
> This is untested, but should give you the idea:
> 
> First, convert that list to a decimal digit string:
> 
>s = ''.join(map(str, l1))
> 
> Then convert the string to an integer:
> 
>n = int(s)# base 10 is the default
> 
> Then convert the integer to a hex digit string:
> 
>h = '%X' % n
> 
> Finally, convert the hex digit string to a list of integer values of the
> individual digits:
> 
>vlist = [int(d, 16) for d in h]
> 
> This is the list you want.
> 
> If you prefer, You can do it all in one line:
> 
>vlist = [int(d, 16) for d in ('%X' % int(''.join(map(str, l1]

Thanks Paul,

I'm just using Python to prototype, so I cannot use any of these great
features of the language.

Regards,

Philippe

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


ftplib errors/exceptions

2006-07-30 Thread Matthew Little
I'm new to Python and I am writing a simple FTP client.  I am having trouble handling errors like connection refused, invalid username or password, and the like.  I can use a try exception block like thistry:  ftp=FTP('some_server')
  ftp.login()  # more linesexcept:  print "An error has occured.\n"This works fine to supress the errors, but I would like to be able to narrow the errors down so that I can print 'invalid username or password' or 'connection refused' rather than simply 'An error has occured'.  How would I go about narrowing down which errors occur? 
Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list

Small problem with print and comma

2006-07-30 Thread [EMAIL PROTECTED]
Hi,

I have a small problem with my function: printList. I use print with a
',' . Somehow the last digit of the last number isn't printed. I wonder
why.

import random

def createRandomList(param):
length = param

a = []
 creating random list"""
for i in range(0,length):
a.append(random.randrange(100))
return a

def printList(param):
#doesn't work
#2 sample outputs
# 30 70 68 6 48 60 29 48 30 38
#sorted list
#6 29 30 30 38 48 48 60 68 7  <--- last character missing

#93 8 10 28 94 4 26 41 72 6
#sorted list
#4 6 8 10 26 28 41 72 93 9 <-- dito


for i in range(0,len(param)):
print a[i],
   #works
   #for i in range(0,len(param)-1):
   #print a[i],
   #print a[len(param)-1]


if __name__ == "__main__":
length = 10
a = createRandomList(length)
printList(a)

for j in range(1,len(a)):
key = a[j]
i = j-1
while i > -1 and a[i]>key:
a[i+1] = a[i]
i = i-1
a[i+1] = key

print "\n sorted list"
printList(a)

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin
Philippe Martin wrote:
> John Machin wrote:
>
> > Philippe Martin wrote:
> >> Hi,
> >>
> >> I'm looking for an algo that would convert a list such as:
> >
> > Such as what?
> >
> >>
> >> I'm using python to prototype the algo: this will move to C in an
> >> embedded system where an int has 16 bits - I do not wish to use any
> >> python library.
> >>
> >> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> >
> > Does it??? How do you represent the decimal number 12349678, then?
> >
> >> l2 = func (l1)
> >> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> >>
> >
> > I'm sorry, but very little of that makes any sense to me:
> >
> > 1. I thought BCD meant something very much like this:
> > http://en.wikipedia.org/wiki/Binary-coded_decimal
> >
> > 2. >>> [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> > [1, 2, 13, 6, 8, 7]
> >
> > So [1], [2], [6] are unchanged, [3, 4] -> [13] (or maybe [3, 4, 5] ->
> > 13),  and [7, 8] -> [8,7].
> >
> > I doubt very much that there's an algorithm to do that. What is the
> > relationship between 1234(maybe 5)678 and 0x12D687??? I would expect
> > something like this::
> >
> > 0x12345678 (stored in 4 bytes 0x12, ..., 0x78)  -- or 0x21436587
> > or
> > 0x012345678s (where s is a "sign" nibble; stored in 5 bytes 0x01,
> > ..., 0x8s)
> >
> > IOW something regular and explicable ...
> >
> > 3. Perhaps it might be a good idea if you told us what the *real*
> > problem is, including *exact* quotes from the manual for the embedded
> > system. You evidently need/want to convert from one representation of
> > signed? unsigned? integers to another. Once we all understand *what*
> > those representations are, *then* we can undoubtedly help you with
> > pseudocode in the form of Python code manipulating lists or whatever.
> >
> > Cheers,
> > John
>
>
> Hi,
>
> From my answer to Marc:
>
> >My apologies, I clearly made a mistake with my calculator, yes the
> >resulting
> >array I would need is [0xb,0xc,0x6,0x1,0x4,0xe]
>

"Clearly"? I don't think that word means what you think it means :-)

All you need is something like the following. You will need to use
"long" if the C "int" is only 16 bits.

C:\junk>type bcd.py
def reconstitute_int(alist):
reg = 0 # reg needs to be 32-bits (or more)
for digit in alist:
assert 0 <= digit <= 9
reg = reg * 10 + digit
return reg

def make_hex(anint):
# anint needs to be 32-bits (or more)
result = []
while anint:
result.append(anint & 0xF)
anint >>= 4
return result

def reverse_list(alist):
n = len(alist)
for i in xrange(n >> 1):
reg1 = alist[n - 1 - i]
reg2 = alist[i]
alist[i] = reg1
alist[n - 1 - i] = reg2

C:\junk>
C:\junk>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import bcd
>>> num = bcd.reconstitute_int([1,2,3,4,5,6,7,8])
>>> num
12345678
>>> result = bcd.make_hex(num)
>>> result
[14, 4, 1, 6, 12, 11]
>>> bcd.reverse_list(result)
>>> result
[11, 12, 6, 1, 4, 14]
>>> ['0x%x' % digit for digit in result]
['0xb', '0xc', '0x6', '0x1', '0x4', '0xe']
>>> ^Z

HTH,
John

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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> Philippe Martin wrote:
>> John Machin wrote:
>>
>> > Philippe Martin wrote:
>> >> Hi,
>> >>
>> >> I'm looking for an algo that would convert a list such as:
>> >
>> > Such as what?
>> >
>> >>
>> >> I'm using python to prototype the algo: this will move to C in an
>> >> embedded system where an int has 16 bits - I do not wish to use any
>> >> python library.
>> >>
>> >> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
>> >
>> > Does it??? How do you represent the decimal number 12349678, then?
>> >
>> >> l2 = func (l1)
>> >> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>> >>
>> >
>> > I'm sorry, but very little of that makes any sense to me:
>> >
>> > 1. I thought BCD meant something very much like this:
>> > http://en.wikipedia.org/wiki/Binary-coded_decimal
>> >
>> > 2. >>> [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>> > [1, 2, 13, 6, 8, 7]
>> >
>> > So [1], [2], [6] are unchanged, [3, 4] -> [13] (or maybe [3, 4, 5] ->
>> > 13),  and [7, 8] -> [8,7].
>> >
>> > I doubt very much that there's an algorithm to do that. What is the
>> > relationship between 1234(maybe 5)678 and 0x12D687??? I would expect
>> > something like this::
>> >
>> > 0x12345678 (stored in 4 bytes 0x12, ..., 0x78)  -- or 0x21436587
>> > or
>> > 0x012345678s (where s is a "sign" nibble; stored in 5 bytes 0x01,
>> > ..., 0x8s)
>> >
>> > IOW something regular and explicable ...
>> >
>> > 3. Perhaps it might be a good idea if you told us what the *real*
>> > problem is, including *exact* quotes from the manual for the embedded
>> > system. You evidently need/want to convert from one representation of
>> > signed? unsigned? integers to another. Once we all understand *what*
>> > those representations are, *then* we can undoubtedly help you with
>> > pseudocode in the form of Python code manipulating lists or whatever.
>> >
>> > Cheers,
>> > John
>>
>>
>> Hi,
>>
>> From my answer to Marc:
>>
>> >My apologies, I clearly made a mistake with my calculator, yes the
>> >resulting
>> >array I would need is [0xb,0xc,0x6,0x1,0x4,0xe]
>>
> 
> "Clearly"? I don't think that word means what you think it means :-)
> 
> All you need is something like the following. You will need to use
> "long" if the C "int" is only 16 bits.
> 
> C:\junk>type bcd.py
> def reconstitute_int(alist):
> reg = 0 # reg needs to be 32-bits (or more)
> for digit in alist:
> assert 0 <= digit <= 9
> reg = reg * 10 + digit
> return reg
> 
> def make_hex(anint):
> # anint needs to be 32-bits (or more)
> result = []
> while anint:
> result.append(anint & 0xF)
> anint >>= 4
> return result
> 
> def reverse_list(alist):
> n = len(alist)
> for i in xrange(n >> 1):
> reg1 = alist[n - 1 - i]
> reg2 = alist[i]
> alist[i] = reg1
> alist[n - 1 - i] = reg2
> 
> C:\junk>
> C:\junk>python
> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
 import bcd
 num = bcd.reconstitute_int([1,2,3,4,5,6,7,8])
 num
> 12345678
 result = bcd.make_hex(num)
 result
> [14, 4, 1, 6, 12, 11]
 bcd.reverse_list(result)
 result
> [11, 12, 6, 1, 4, 14]
 ['0x%x' % digit for digit in result]
> ['0xb', '0xc', '0x6', '0x1', '0x4', '0xe']
 ^Z
> 
> HTH,
> John

Thanks John, I do not have a long available on the device: stuck with 16
bits.

Regards,

Philippe



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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Dennis Lee Bieber wrote:

> On Sun, 30 Jul 2006 16:39:47 -0500, Philippe Martin
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
>> 
>> My apologies, I clearly made a mistake with my calculator, yes the
>> resulting array I would need is [0xb,0xc,0x6,0x1,0x4,0xe]
>>
> Take note that this is NOT a BCD form for "12345678". BCD (typically
> packed) uses four bits per decimal digit. That would make "12345678" =>
> 0x12, 0x34, 0x56, 0x78 (ignoring matters of big/little end).
> 
> The binary representation of 12345678, in bytes, is 0xBC, 0x61, 0x4E
> 
> 0xb, 0xc... is really 0x0B, 0x0C... 8-bits per byte, with MSB set to
> .
> 
> Compare:
> BCD   00010010 00110100 01010110 0000
> binary1000 0111 01001110
> your  1011 1100 0110 0001 0100 1110
> --
> Wulfraed  Dennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff: [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/
Yes I realized that after writing it.

Regards,

Philippe

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


Re: BCD List to HEX List

2006-07-30 Thread Paul Rubin
Philippe Martin <[EMAIL PROTECTED]> writes:
> I'm just using Python to prototype, so I cannot use any of these great
> features of the language.

I think when writing a prototype, you should use whatever features you
want, except maybe at the upper levels of program organization.  The
idea of prototyping is to get something done quickly, that you can use
for integration and user testing earlier in the development cycle.  So
you should use whatever Python features are available to make
prototyping faster.  You shouldn't expect the prototype code to
closely match the final C code, if that slows you down.  If you want
code that closely resembles C code, you might as well write in C
directly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Paul Rubin wrote:

> Philippe Martin <[EMAIL PROTECTED]> writes:
>> I'm just using Python to prototype, so I cannot use any of these great
>> features of the language.
> 
> I think when writing a prototype, you should use whatever features you
> want, except maybe at the upper levels of program organization.  The
> idea of prototyping is to get something done quickly, that you can use
> for integration and user testing earlier in the development cycle.  So
> you should use whatever Python features are available to make
> prototyping faster.  You shouldn't expect the prototype code to
> closely match the final C code, if that slows you down.  If you want
> code that closely resembles C code, you might as well write in C
> directly.


Some truth in that.

Thanks,

Philippe

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin
Philippe Martin wrote:

>
> Thanks John, I do not have a long available on the device: stuck with 16
> bits.
>

What does "available on the device" mean? Having a "long" is a property
of a C complier, not a device. What is the CPU in the device? What is
the C compiler you are using? N.B. Last time I looked, gcc would
generate code for just about any CPU since Babbage's. I would expect
*any* C compiler that is targetting a 16-bit CPU to provide a 32-bit
long and generate reasonably efficient code for most simple operations.
Is there no library of utility routines for *elementary* base
conversions such as you need? Is there no 32-bit-arithmetic-simulation
package?

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


Re: Small problem with print and comma

2006-07-30 Thread faulkner
why don't you iterate over the list instead of indices?
for elem in L: print elem,

you don't need the 0 when you call range: range(0, n) == range(n)
the last element of a range is n-1: range(n)[-1] == n-1
you don't need while to iterate backwards. the third argument to range
is step.
range(n-1, -1, -1) == [n-1, n-2, n-3, ..., 1, 0]

[EMAIL PROTECTED] wrote:
> Hi,
>
> I have a small problem with my function: printList. I use print with a
> ',' . Somehow the last digit of the last number isn't printed. I wonder
> why.
>
> import random
>
> def createRandomList(param):
> length = param
>
> a = []
>  creating random list"""
> for i in range(0,length):
>   a.append(random.randrange(100))
> return a
>
> def printList(param):
> #doesn't work
> #2 sample outputs
> # 30 70 68 6 48 60 29 48 30 38
> #sorted list
> #6 29 30 30 38 48 48 60 68 7  <--- last character missing
>
> #93 8 10 28 94 4 26 41 72 6
> #sorted list
> #4 6 8 10 26 28 41 72 93 9 <-- dito
>
>
> for i in range(0,len(param)):
>   print a[i],
>#works
>#for i in range(0,len(param)-1):
>#  print a[i],
>#print a[len(param)-1]
>
>
> if __name__ == "__main__":
>   length = 10
>   a = createRandomList(length)
>   printList(a)
>
>   for j in range(1,len(a)):
>   key = a[j]
>   i = j-1
>   while i > -1 and a[i]>key:
>   a[i+1] = a[i]
>   i = i-1
>   a[i+1] = key
>   
>   print "\n sorted list"
>   printList(a)

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


Re: Html character entity conversion

2006-07-30 Thread Claudio Grondi
[EMAIL PROTECTED] wrote:
> Claudio Grondi wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>Here is my script:
>>>
>>>from mechanize import *
>>>from BeautifulSoup import *
>>>import StringIO
>>>b = Browser()
>>>f = b.open("http://www.translate.ru/text.asp?lang=ru";)
>>>b.select_form(nr=0)
>>>b["source"] = "hello python"
>>>html = b.submit().get_data()
>>>soup = BeautifulSoup(html)
>>>print  soup.find("span", id = "r_text").string
>>>
>>>OUTPUT:
>>>привет
>>>питон
>>>--
>>>In russian it looks like:
>>>"привет питон"
>>>
>>>How can I translate this using standard Python libraries??
>>>
>>>--
>>>Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
>>>
>>
>>Translate to what and with what purpose?
>>
>>Assuming your intention is to get a Python Unicode string, what about:
>>
>>strHTML = 'привет
>>питон'
>>strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
>>strUnicode = eval("u'%s'"%strUnicodeHexCode)
>>
>>?
>>
>>I am sure, there is a more elegant and direct solution, but just wanted
>>to provide here some quick response.
>>
>>Claudio Grondi
> 
> 
> Thank you, Claudio.
> Really interest solution, but it doesn't work...
> 
> In [19]: strHTML = 'привет
> питон'
> 
> In [20]: strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
> 
> In [21]: strUnicode = eval("u'%s'"%strUnicodeHexCode)
> 
> In [22]: print strUnicode
> ---
> exceptions.UnicodeEncodeErrorTraceback (most
> recent call last)
> 
> C:\Documents and Settings\dron\
> 
> C:\usr\lib\encodings\cp866.py in encode(self, input, errors)
>  16 def encode(self,input,errors='strict'):
>  17
> ---> 18 return codecs.charmap_encode(input,errors,encoding_map)
>  19
>  20 def decode(self,input,errors='strict'):
> 
> UnicodeEncodeError: 'charmap' codec can't encode characters in position
> 0-5: character maps to 
> 
> In [23]: print strUnicode.encode("utf-8")
> сВЗсВИсВАсБ┤сБ╖сВР сВЗсВАсВРсВЖсВЕ
> <-- it's not my string "привет питон"
> 
> In [24]: strUnicode.encode("utf-8")
> Out[24]:
> '\xe1\x82\x87\xe1\x82\x88\xe1\x82\x80\xe1\x81\xb4\xe1\x81\xb7\xe1\x82\x90
> \xe1\x82\x87\xe1\x82\x80\xe1\x82\x90\xe1\x82\x86\xe1\x82\
> x85' <-- and too many chars
> 
Have you considered, that the HTML page specifies charset=windows-1251 
in its
 tag ?
You are apparently on Linux or so, so I can't track this problem down 
having only a Windows box here, but inbetween I know that there is 
another problem with it:
I have erronously assumed, that the numbers in п are hexadecimal, 
but they are decimal, so it is necessary to do hex(int('1087')) on them 
to get at the right code to put into eval().
As you know now the idea I hope you will succeed as I did with:

 >>> lstIntUnicodeDecimalCode = strHTML.replace('&#','').split(';')
 >>> lstIntUnicodeDecimalCode
['1087', '1088', '1080', '1074', '1077', '1090', ' 1087', '1080', 
'1090', '1086', '1085', '']
 >>> lstIntUnicodeDecimalCode = lstIntUnicodeDecimalCode[:-1]
 >>> lstHexUnicode = [ hex(int(item)) for item in lstIntUnicodeDecimalCode]
 >>> lstHexUnicode
['0x43f', '0x440', '0x438', '0x432', '0x435', '0x442', '0x43f', '0x438', 
'0x442', '0x43e', '0x43d']
 >>> eval( 'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
u'\u043f\u0440\u0438\u0432\u0435\u0442\u043f\u0438\u0442\u043e\u043d'
 >>> strUnicode = eval( 
'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
 >>> print strUnicode
приветпитон

Sorry for that mess not taking the space into consideration, but I think 
  you can get the idea anyway.

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

Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> Philippe Martin wrote:
> 
>>
>> Thanks John, I do not have a long available on the device: stuck with 16
>> bits.
>>
> 
> What does "available on the device" mean? Having a "long" is a property
> of a C complier, not a device. What is the CPU in the device? What is
> the C compiler you are using? N.B. Last time I looked, gcc would
> generate code for just about any CPU since Babbage's. I would expect
> *any* C compiler that is targetting a 16-bit CPU to provide a 32-bit
> long and generate reasonably efficient code for most simple operations.
> Is there no library of utility routines for *elementary* base
> conversions such as you need? Is there no 32-bit-arithmetic-simulation
> package?

Hi John,

I'm working on an embedded 8 bit device and have no choice as to which
cross-compiler to use: in this case the guy knows up to short and that's
it.

Regards,

Philippe

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


Re: BCD List to HEX List

2006-07-30 Thread Paul Rubin
Philippe Martin <[EMAIL PROTECTED]> writes:
> Thanks John, I do not have a long available on the device: stuck with 16
> bits.

Oh, I think I understand now, why you were asking about algorithms.
You really did want something whose intermediate results all fit in 16
bits.  

Even if your C compiler doesn't support a long int datatype, it may
have some library functions to do long arithmetic.  Look for functions
with names like lmul, ldiv, etc.

Will the decimal digit strings always be 8 digits?  If yes, there are
probably a few math tricks you can use to do the hex conversion
simply.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Philippe Martin wrote:

> Hi,
> 
> I'm looking for an algo that would convert a list such as:
> 
> I'm using python to prototype the algo: this will move to C in an embedded
> system where an int has 16 bits - I do not wish to use any python library.
> 
> l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> l2 = func (l1)
> # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> 
> 
> Regards,
> 
> Philippe

Thanks to all,

I decided to attack the problem another way and change the code in device #2
so it can now take the output from device #1.

As device #2 only needs to compare, add, and subtract the stuff .. it makes
my life much simpler.

Sample (potentially buggy):


l1 = [1,2,3,4]
l2 = [0,2,3,9]


def sup (l1, l2): #assume same length
for i in range(len(l1) ):
if l1[i] > l2[i]:
return 1
if l1[i] < l2[i]:
return -1
return 0



def add (l1, l2): #assume same length
r = []
idx =  range (len(l1))
idx.reverse()
carry = 0
for i in idx:

if l1[i] + l2[i] > 10:
carry = 1
r.insert(0,(l1[i] + l2[i]) % 10)
else:
r.insert(0,l1[i] + l2[i] + carry)
carry = 0
return r





print sup(l1,l2)
print add (l1,l2)

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin

Philippe Martin wrote:
> John Machin wrote:
>
> > Philippe Martin wrote:
> >
> >>
> >> Thanks John, I do not have a long available on the device: stuck with 16
> >> bits.
> >>
> >
> > What does "available on the device" mean? Having a "long" is a property
> > of a C complier, not a device. What is the CPU in the device? What is
> > the C compiler you are using? N.B. Last time I looked, gcc would
> > generate code for just about any CPU since Babbage's. I would expect
> > *any* C compiler that is targetting a 16-bit CPU to provide a 32-bit
> > long and generate reasonably efficient code for most simple operations.
> > Is there no library of utility routines for *elementary* base
> > conversions such as you need? Is there no 32-bit-arithmetic-simulation
> > package?
>
> Hi John,
>
> I'm working on an embedded 8 bit device and have no choice as to which
> cross-compiler to use: in this case the guy knows up to short and that's
> it.
>

What do you mean, no choice? You generate code, you stuff it into the
device, it doesn't give a rat's where the code came from ...

Perhaps we could help you better if you actually answered the
questions, like:
What is the CPU in the device?
What is the C compiler you are using?

Is there an assembler for the CPU that's in the device?

Have you considered asking on a newsgroup where your problem might
actually be on-topic, like:
comp.lang.c
a NG devoted to microprocessors
?

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


Re: Small problem with print and comma

2006-07-30 Thread Tim Chase
> I have a small problem with my function: printList. I use print with a
> ',' . Somehow the last digit of the last number isn't printed. I wonder
> why.

Posting actual code might help...the code you sent has a horrible 
mix of tabs and spaces.   You've also got some craziness in your 
"creating random list" string.  First off, it looks like you're 
using a docstring, but they only go immediately after the def 
line.  I'd recommend putting it where it belongs, or changing the 
line to a comment.

There are some unpythonic bits in here:

printList() would usually just idiomatically be written as

print ' '.join(a)

although there are some int-to-string problems with that, so it 
would be written as something like

print ' '.join([str(x) for x in listOfNumbers])

which is efficient, and avoids the possibility of off-by-one 
errors when range(0,length).

Another idiom would be the list-building of createRandomList:

return [random.randrange(100) for x in xrange(0,length)]

Additionally, this can be reduced as range/xrange assume 0 as the 
default starting point

return [random.randrange(100) for x in xrange(length)]

(using xrange also avoids building an unneeded list, just to 
throw it away)

Additionally, rather than rolling your own bubble-sort, you can 
just make use of a list's sort() method:

a.sort()

Other items include sensibly naming your parameters rather than 
generically calling them "param", just to reassign them to 
another name inside.

Taking my suggestions into consideration, your original program 
condenses to



import random

def createRandomList(length):
 return [random.randrange(100) for x in xrange(length)]

def printList(listOfNumbers):
 print ' '.join([str(x) for x in listOfNumbers])

if __name__ == "__main__":
 length = 10
 a = createRandomList(length)
 printList(a)
 a.sort()
 print "sorted list"
 printList(a)



one might even change createRandomList to allow a little more 
flexibility:

def createRandomList(length, maximum=100):
 return [random.randrange(maximum) for x in xrange(length)]


So it can be called as you already do, or you can specify the 
maximum as well with

createRandomList(10, 42)

for future use when 100 doesn't cut it for you in all cases.

Just a few thoughts.

-tkc




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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> Have you considered asking on a newsgroup where your problem might
> actually be on-topic, like:
> comp.lang.c

Yes, I came here for the "algorithm" question, not the code result.

Regards,

Philippe

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


Windows vs. Linux

2006-07-30 Thread noahmd
Okay, once-upon-a-time I tried to start programming by learning C.  At
the time I was younger and didn't really understand all that C had to
offer.  I eventually moved over to Microsoft's Visual Basic.  It was
nice to be able to design a visual application with no effort (too bad
I didn't really learn the ins and outs of programming)

Long story short, I want to get back into programming, and Python looks
like a good choice for me to start with, and maybe become advanced
with.  Right now I run Windows as my main operating system.  On my old
laptop I ran Ubuntu, and liked it very much; however, my new laptop has
a Broadcom wireless card, and it's not very Linux friendly.  Is Windows
an okay enviornment in which to program under Python, or do you
recommend that I run a dual-boot of Linux or maybe a VMWare install to
program under Python?

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


Re: non-blocking PIPE read on Windows

2006-07-30 Thread placid

Dennis Lee Bieber wrote:
> On 27 Jul 2006 22:26:25 -0700, "placid" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> >
> > readline() blocks until the newline character is read, but when i use
> > read(X) where X is a number of bytes then it doesnt block(expected
> > functionality) but i dont know how many bytes the line will be and its
> > not constant so i cant use this too.
> >
> > Any ideas of solving this problem?
> >
>   Use a thread that reads one character at a time; when it sees
> whatever signals "end of line" (it sounds like you're reading a progress
> bar implemented via overwrite). Combine the characters into a
> string, return the string to the main program via a queue.
>

Yes it is a progress bar implemented via  overwrite. I will try
this.

>   If there is no such "end of line" character, but there IS a
> noticeable delay between "writes", a more complex method might suffice
> -- in which one thread does the byte reads, setting a time value on each
> read; a related thread then does a sleep() loop, checking the "last read
> time" against the pause length -- if close enough to the pause duration,
> combine and return...

i dont think there is a noticeable delay between "writes".


>   Alternatively, take a good old style terminal keyboard (a VT100
> Tempest-rated model should be ideal), and use it to beat Bill Gates over
> the head until he agrees to push a high-priority upgrade to the command
> line I/O system... or makes files work with select() (so you can combine
> the time-out with the byte read)

;)  Tsk Tsk

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin

Philippe Martin wrote:
> Philippe Martin wrote:
>
> > Hi,
> >
> > I'm looking for an algo that would convert a list such as:
> >
> > I'm using python to prototype the algo: this will move to C in an embedded
> > system where an int has 16 bits - I do not wish to use any python library.
> >
> > l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> > l2 = func (l1)
> > # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> >
> >
> > Regards,
> >
> > Philippe
>
> Thanks to all,
>
> I decided to attack the problem another way and change the code in device #2
> so it can now take the output from device #1.
>
> As device #2 only needs to compare, add, and subtract the stuff .. it makes
> my life much simpler.
>

I'm confused.
1. Was the original device #1 or #2?
2. How many bits does the non-original device's C compiler support?
3. If the original device is device #1, please explain where *it*
obtained an 8-digit decimal number expressed as 1 digit per byte (or
int) ...

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


Re: Windows vs. Linux

2006-07-30 Thread Aahz
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>
>Long story short, I want to get back into programming, and Python looks
>like a good choice for me to start with, and maybe become advanced
>with.  Right now I run Windows as my main operating system.  On my old
>laptop I ran Ubuntu, and liked it very much; however, my new laptop has
>a Broadcom wireless card, and it's not very Linux friendly.  Is Windows
>an okay enviornment in which to program under Python, or do you
>recommend that I run a dual-boot of Linux or maybe a VMWare install to
>program under Python?

Windows is an excellent environment for Python!  Just Do It.  ;-)

(Despite the prepronderence of Linux programmers in the dev team, there
are probably more Windows Python programmers than for any other OS,
simply because there are more Windows users.)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread John Machin

Philippe Martin wrote:
> John Machin wrote:
>
> > Have you considered asking on a newsgroup where your problem might
> > actually be on-topic, like:
> > comp.lang.c
>
> Yes, I came here for the "algorithm" question, not the code result.
>

This is comp.lang.python, not comp.algorithms

Why are you avoiding naming the chip and its compiler?

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


Re: Windows vs. Linux

2006-07-30 Thread Damjan
> Right now I run Windows as my main operating system.  On my old
> laptop I ran Ubuntu, and liked it very much; however, my new laptop has
> a Broadcom wireless card, and it's not very Linux friendly.

of topic: that Broadcom wireless card has a driver included in the latest
kernel 2.6.17, and probably you could easily make it work if you make some
upgrades to Ubuntu.


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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> 
> Philippe Martin wrote:
>> Philippe Martin wrote:
>>
>> > Hi,
>> >
>> > I'm looking for an algo that would convert a list such as:
>> >
>> > I'm using python to prototype the algo: this will move to C in an
>> > embedded system where an int has 16 bits - I do not wish to use any
>> > python library.
>> >
>> > l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
>> > l2 = func (l1)
>> > # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>> >
>> >
>> > Regards,
>> >
>> > Philippe
>>
>> Thanks to all,
>>
>> I decided to attack the problem another way and change the code in device
>> #2 so it can now take the output from device #1.
>>
>> As device #2 only needs to compare, add, and subtract the stuff .. it
>> makes my life much simpler.
>>
> 
> I'm confused.
> 1. Was the original device #1 or #2?
> 2. How many bits does the non-original device's C compiler support?
> 3. If the original device is device #1, please explain where *it*
> obtained an 8-digit decimal number expressed as 1 digit per byte (or
> int) ...


Well I don't want to bore you guys more than needed ;-) but:

Device #1 has an 8 bit processor - uses a C cross-compiler that does not
know anything above a 16 bit integer. I use this device to get information
from users "1234...".

Device #2 has an 8 bit processor - uses a subset of Java ... that does not
know anything above a 16 bit integer.


The information gathered in device number #1 must then be sent to device #2
(after being encrypted  ) to be compared, subtracted or added.

The code I already have in device #2 makes the assumption that the
information received is an array of bytes of length N which represents an
actual value. ex: 0x67DF5 ==> [0x6, 0x7, 0xD, 0xF, 0x5] ... so it can
compare/add/subtract values ... and do its job.

As a python fan, I figured (back to my initial not very clear request), that
I could prototype the above without making any major assumption as to the
capabilities of the interpreter.


I still believe that to be true.

Regards,

Philippe














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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> 
> Philippe Martin wrote:
>> John Machin wrote:
>>
>> > Have you considered asking on a newsgroup where your problem might
>> > actually be on-topic, like:
>> > comp.lang.c
>>
>> Yes, I came here for the "algorithm" question, not the code result.
>>
> 
> This is comp.lang.python, not comp.algorithms
> 
> Why are you avoiding naming the chip and its compiler?


I must disagree on that one: There are many threads on this site where
people just have fun talking algorithm. I'm not an algo. expert and I know
there are many here.


> Why are you avoiding naming the chip and its compiler?
I am not but I do not see what that brings to the discussion: but if you
wish ==>

on one device, the processor in an 8-bit arm and the X-compiler is made by
epson 

on the other device, the processor is unknown to me and the environment is a
subset of java made for smartcards called javacard.

Regards,

Philippe

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


Re: Windows vs. Linux

2006-07-30 Thread William Witteman
On Sun, Jul 30, 2006 at 04:21:34PM -0700, [EMAIL PROTECTED] wrote:

>offer.  I eventually moved over to Microsoft's Visual Basic.  It was


I'm very sorry.

>Long story short, I want to get back into programming, and Python looks
>like a good choice for me to start with, and maybe become advanced
>with.  Right now I run Windows as my main operating system.  On my old

A good choice.  I write Python code both at home, on a Linux box, and at
work, on Windoze.  I find it slightly easier to write Python on Linux
only because I can interact so easily with the OS from the command line
- there are more itches to scratch and Python is one of the best
backscratchers.  Python on Linux lets me automate huge swathes of my
life with ease.  That said, there is a heck of a lot I can easily do on
Windoze too.  The real selling point for me is that I can work on code
for work at home, on a completely different platform, and then take it
to work and I know it'll Just Work(TM).

As a Linux zealot, I'd say use Linux :-)  As a pragmatist, use what you
find more comfortable, and enjoy yourself.
-- 

yours,

William
woolgathering.cx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows vs. Linux

2006-07-30 Thread OMouse
Python should port nicely between Windows and Linux so there should be
no need to dual-boot.

[EMAIL PROTECTED] wrote:
> Okay, once-upon-a-time I tried to start programming by learning C.  At
> the time I was younger and didn't really understand all that C had to
> offer.  I eventually moved over to Microsoft's Visual Basic.  It was
> nice to be able to design a visual application with no effort (too bad
> I didn't really learn the ins and outs of programming)
>
> Long story short, I want to get back into programming, and Python looks
> like a good choice for me to start with, and maybe become advanced
> with.  Right now I run Windows as my main operating system.  On my old
> laptop I ran Ubuntu, and liked it very much; however, my new laptop has
> a Broadcom wireless card, and it's not very Linux friendly.  Is Windows
> an okay enviornment in which to program under Python, or do you
> recommend that I run a dual-boot of Linux or maybe a VMWare install to
> program under Python?

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin
Philippe Martin wrote:
> John Machin wrote:
>
> >
> > Philippe Martin wrote:
> >> Philippe Martin wrote:
> >>
> >> > Hi,
> >> >
> >> > I'm looking for an algo that would convert a list such as:
> >> >
> >> > I'm using python to prototype the algo: this will move to C in an
> >> > embedded system where an int has 16 bits - I do not wish to use any
> >> > python library.
> >> >
> >> > l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
> >> > l2 = func (l1)
> >> > # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
> >> >
> >> >
> >> > Regards,
> >> >
> >> > Philippe
> >>
> >> Thanks to all,
> >>
> >> I decided to attack the problem another way and change the code in device
> >> #2 so it can now take the output from device #1.
> >>
> >> As device #2 only needs to compare, add, and subtract the stuff .. it
> >> makes my life much simpler.
> >>
> >
> > I'm confused.
> > 1. Was the original device #1 or #2?
> > 2. How many bits does the non-original device's C compiler support?
> > 3. If the original device is device #1, please explain where *it*
> > obtained an 8-digit decimal number expressed as 1 digit per byte (or
> > int) ...
>
>
> Well I don't want to bore you guys more than needed ;-) but:
>
> Device #1 has an 8 bit processor - uses a C cross-compiler that does not
> know anything above a 16 bit integer. I use this device to get information
> from users "1234...".
>
> Device #2 has an 8 bit processor - uses a subset of Java ... that does not
> know anything above a 16 bit integer.
>
>
> The information gathered in device number #1 must then be sent to device #2
> (after being encrypted  ) to be compared, subtracted or added.
>
> The code I already have in device #2 makes the assumption that the
> information received is an array of bytes of length N which represents an
> actual value. ex: 0x67DF5 ==> [0x6, 0x7, 0xD, 0xF, 0x5] ... so it can
> compare/add/subtract values ... and do its job.
>
> As a python fan, I figured (back to my initial not very clear request), that
> I could prototype the above without making any major assumption as to the
> capabilities of the interpreter.
>
>
> I still believe that to be true.
>

Try this:
C:\junk>type bcd.py
def reconstitute_int(alist):
reghi, reglo = 0, 0
for digit in alist:
assert 0 <= digit <= 9
reghi, reglo = mul32by10(reghi, reglo)
reghi, reglo = add32(reghi, reglo, 0, digit)
return reghi, reglo

def uadd16(a, b):
return (a + b) & 0x

def shr32by4(hi, lo):
newhi = (hi >> 4) & 0x
newlo = ((lo >> 4) | ((hi & 0xF) << 12)) & 0x

return newhi, newlo

def add32(hia, loa, hib, lob):
lox = uadd16(loa, lob)
hix = uadd16(hia, hib)
inx = ((lox & 0x8000) >> 13) + ((lob & 0x8000) >> 14) + ((loa &
0x8000) >> 1
5)
carry = [0, 1, 1, 1, 0, 0, 0, 1][inx]
# The above is admittedly ugly but sheesh I haven't even had my
# second cup of coffee yet today :-)
# Anybody who's good at solving equations in Boolean algebra,
# pls beautify this!!
if carry:
hix = uadd16(hix, 1)
expected = (hia+hib)*65536 + loa + lob
actual = hix*65536 + lox
if actual != expected:
print (hia, loa), (hib, lob), (hix, lox), actual, expected,
inx, carry
return hix, lox

def mul32by10(hi, lo):
tmphi, tmplo = add32(hi, lo, hi, lo) # 2 times
tmphi, tmplo = add32(tmphi, tmplo, tmphi, tmplo) # 4 times
tmphi, tmplo = add32(tmphi, tmplo, hi, lo) # 5 times
tmphi, tmplo = add32(tmphi, tmplo, tmphi, tmplo) # 10 times
return tmphi, tmplo

def make_hex32(aninthi, anintlo):
result = []
while aninthi or anintlo:
result.append(anintlo & 0xF)
aninthi, anintlo = shr32by4(aninthi, anintlo)
return result

def reverse_list(alist):
n = len(alist)
for i in xrange(n >> 1):
reg1 = alist[n - 1 - i]
reg2 = alist[i]
alist[i] = reg1
alist[n - 1 - i] = reg2


C:\junk>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import bcd
>>> num = bcd.reconstitute_int([1,2,3,4,5,6,7,8])
>>> num
(188, 24910)
>>> num[0]*65536 + num[1]
12345678
>>> result = bcd.make_hex32(*num)
>>> result
[14, 4, 1, 6, 12, 11]
>>> bcd.reverse_list(result)
>>> result
[11, 12, 6, 1, 4, 14]
>>> ['0x%x' % digit for digit in result]
['0xb', '0xc', '0x6', '0x1', '0x4', '0xe']
>>> ^Z

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin

Philippe Martin wrote:
> John Machin wrote:
>
> >
> > Philippe Martin wrote:
> >> John Machin wrote:
> >>
> >> > Have you considered asking on a newsgroup where your problem might
> >> > actually be on-topic, like:
> >> > comp.lang.c
> >>
> >> Yes, I came here for the "algorithm" question, not the code result.
> >>
> >
> > This is comp.lang.python, not comp.algorithms
> >
> > Why are you avoiding naming the chip and its compiler?
>
>
> I must disagree on that one: There are many threads on this site where
> people just have fun talking algorithm. I'm not an algo. expert and I know
> there are many here.

Get this through your head: some time in the last 25 years someone will
have made some general-purpose functions for doing the elementary
32-bit operations with a C compiler that offers no more than 16 bit
arithmetic, and published the C source code. Go find it.

>
>
> > Why are you avoiding naming the chip and its compiler?
> I am not but I do not see what that brings to the discussion:

Readers may actually know something about the device and/or compiler!!

> but if you
> wish ==>
>
> on one device, the processor in an 8-bit arm and the X-compiler is made by
> epson

1. You still haven't *NAMED* the CPU and the compiler!!

2. Do you mean ARM as in "Acorn/Advanced RISC Machines"?? They make
8-bit CPUs

3. How does the device manage to compute the 8-decimal-digit number
that is your input??

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


Re: Windows vs. Linux

2006-07-30 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Okay, once-upon-a-time I tried to start programming by learning C.  At
> the time I was younger and didn't really understand all that C had to
> offer.  I eventually moved over to Microsoft's Visual Basic.  It was
> nice to be able to design a visual application with no effort (too bad
> I didn't really learn the ins and outs of programming)
> 
> Long story short, I want to get back into programming, and Python looks
> like a good choice for me to start with, and maybe become advanced
> with.  Right now I run Windows as my main operating system.  On my old
> laptop I ran Ubuntu, and liked it very much; however, my new laptop has
> a Broadcom wireless card, and it's not very Linux friendly.  Is Windows
> an okay enviornment in which to program under Python, or do you
> recommend that I run a dual-boot of Linux or maybe a VMWare install to
> program under Python?
> 

I recommend a triple boot mac.

James



-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


pass parameters in SPYCE

2006-07-30 Thread kepioo
Hi all,

I started to use the so good spyce server. I manage to do all the
basics, however, I still block on one problem :

How can I pass parameters to a spy page : example

I have an index page :

link1
link2
link3
link4

I want all theses html links to point to process.spy with the value of
the link as parameter ( equivalent to call process.spy -link1 ).

Is this feasible with html links or I have to use forms and replace my
links with buttons?

Thank you for your help

NVk

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


Re: Small problem with print and comma

2006-07-30 Thread Dustan
Dennis Lee Bieber wrote:
> > for i in range(0,len(param)):
> > print a[i],
>
>   for it in param:
>   print it,

That's one way. However, if you need the position (this is for future
reference; you don't need the position number here):

for i in range(len(param)+1):
print a[i],

The last position was excluded because you forgot the '+1' part,
creating an off-by-one bug.

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


Re: Windows vs. Linux

2006-07-30 Thread BartlebyScrivener
Windows XP is fine. I am learning Python on Windows first with an eye
toward moving to Linux.

If you like, get the ActivePython distribution, which comes with the
Win32 extensions.

If you start liking Python, consider adding the IPython shell. There
are commandline tweaks you can do to make the XP commandline bearable,
in fact, I found them on this forum, so perhaps search on XP
commandline.

Good luck,

rd

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


re: how to stop python

2006-07-30 Thread Dan
bruce bedouglas at earthlink.net posted:

 > perl has the concept of "die". does python have anything
 > similar. how can a python app be stopped?

I see this sort of statement a lot in Perl:
 open(FH, "myfile.txt") or die ("Could not open file");

I've no idea why you're asking for the Python equivalent to die, but if 
it's for this sort of case, you don't need it.  Usually in Python you 
don't need to explicitly check for an error.  The Python function will 
raise an exception instead of returning an error code.  If you want to 
handle the error, enclose it in a try/except block.  But if you just 
want the program to abort with an error message so that you don't get 
silent failure, it will happen automatically if you don't catch the 
exception.  So the equivalent Python example looks something like this:
 fh = file("myfile.txt")

If the file doesn't exist, and you don't catch the exception, you get 
something like this:
$ ./foo.py
Traceback (most recent call last):
   File "./foo.py", line 3, in ?
 fh = file("myfile.txt")
IOError: [Errno 2] No such file or directory: 'myfile.txt'

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


Re: Html character entity conversion

2006-07-30 Thread John Machin
Claudio Grondi wrote:
> [EMAIL PROTECTED] wrote:
> > Claudio Grondi wrote:
> >
> >>[EMAIL PROTECTED] wrote:
> >>
> >>>Here is my script:
> >>>
> >>>from mechanize import *
> >>>from BeautifulSoup import *
> >>>import StringIO
> >>>b = Browser()
> >>>f = b.open("http://www.translate.ru/text.asp?lang=ru";)
> >>>b.select_form(nr=0)
> >>>b["source"] = "hello python"
> >>>html = b.submit().get_data()
> >>>soup = BeautifulSoup(html)
> >>>print  soup.find("span", id = "r_text").string
> >>>
> >>>OUTPUT:
> >>>привет
> >>>питон
> >>>--
> >>>In russian it looks like:
> >>>"привет питон"
> >>>
> >>>How can I translate this using standard Python libraries??
> >>>
> >>>--
> >>>Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
> >>>
> >>
> >>Translate to what and with what purpose?
> >>
> >>Assuming your intention is to get a Python Unicode string, what about:
> >>
> >>strHTML = 'привет
> >>питон'
> >>strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
> >>strUnicode = eval("u'%s'"%strUnicodeHexCode)
> >>
> >>?
> >>
> >>I am sure, there is a more elegant and direct solution, but just wanted
> >>to provide here some quick response.
> >>
> >>Claudio Grondi
> >
> >
> > Thank you, Claudio.
> > Really interest solution, but it doesn't work...
> >
> > In [19]: strHTML = 'привет
> > питон'
> >
> > In [20]: strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
> >
> > In [21]: strUnicode = eval("u'%s'"%strUnicodeHexCode)
> >
> > In [22]: print strUnicode
> > ---
> > exceptions.UnicodeEncodeErrorTraceback (most
> > recent call last)
> >
> > C:\Documents and Settings\dron\
> >
> > C:\usr\lib\encodings\cp866.py in encode(self, input, errors)
> >  16 def encode(self,input,errors='strict'):
> >  17
> > ---> 18 return codecs.charmap_encode(input,errors,encoding_map)
> >  19
> >  20 def decode(self,input,errors='strict'):
> >
> > UnicodeEncodeError: 'charmap' codec can't encode characters in position
> > 0-5: character maps to 
> >
> > In [23]: print strUnicode.encode("utf-8")
> > сВЗсВИсВАсБ┤сБ╖сВР сВЗсВАсВРсВЖсВЕ
> > <-- it's not my string "привет питон"
> >
> > In [24]: strUnicode.encode("utf-8")
> > Out[24]:
> > '\xe1\x82\x87\xe1\x82\x88\xe1\x82\x80\xe1\x81\xb4\xe1\x81\xb7\xe1\x82\x90
> > \xe1\x82\x87\xe1\x82\x80\xe1\x82\x90\xe1\x82\x86\xe1\x82\
> > x85' <-- and too many chars
> >
> Have you considered, that the HTML page specifies charset=windows-1251
> in its
>  tag ?
> You are apparently on Linux or so, so I can't track this problem down
> having only a Windows box here, but inbetween I know that there is
> another problem with it:
> I have erronously assumed, that the numbers in п are hexadecimal,
> but they are decimal, so it is necessary to do hex(int('1087')) on them
> to get at the right code to put into eval().
> As you know now the idea I hope you will succeed as I did with:
>
>  >>> lstIntUnicodeDecimalCode = strHTML.replace('&#','').split(';')
>  >>> lstIntUnicodeDecimalCode
> ['1087', '1088', '1080', '1074', '1077', '1090', ' 1087', '1080',
> '1090', '1086', '1085', '']
>  >>> lstIntUnicodeDecimalCode = lstIntUnicodeDecimalCode[:-1]
>  >>> lstHexUnicode = [ hex(int(item)) for item in lstIntUnicodeDecimalCode]
>  >>> lstHexUnicode
> ['0x43f', '0x440', '0x438', '0x432', '0x435', '0x442', '0x43f', '0x438',
> '0x442', '0x43e', '0x43d']
>  >>> eval( 'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
> u'\u043f\u0440\u0438\u0432\u0435\u0442\u043f\u0438\u0442\u043e\u043d'
>  >>> strUnicode = eval(
> 'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
>  >>> print strUnicode
> приветпитон
>
> Sorry for that mess not taking the space into consideration, but I think
>   you can get the idea anyway.

I hope he *doesn't* get that "idea".

#>>> strHTML =
'приветпит&#
1086;н'
#>>> strUnicode = [unichr(int(x)) for x in
strHTML.replace('&#','').split(';') if
 x]
#>>> strUnicode
[u'\u043f', u'\u0440', u'\u0438', u'\u0432', u'\u0435', u'\u0442',
u'\u043f', u'
\u0438', u'\u0442', u'\u043e', u'\u043d']
#>>>

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

Re: replacing single line of text

2006-07-30 Thread saad82
Simon & Tim, very valuable responses. Thank you much!

Simon Forman wrote:
> [EMAIL PROTECTED] wrote:
> > I want to be able to replace a single line in a large text file
> > (several hundred MB). Using the cookbook's method (below) works but I
> > think the replace fxn chokes on such a large chunk of text. For now, I
> > simply want to replace the 1st line (CSV header) in the file but I'd
> > also like to know a more general solution for any line in the file.
> > There's got a be quick and dirty (and cheap) way to do this... any
> > help?
> >
> > Cookbook's method:
> > output_file.write(input_file.read().replace(stext, rtext))
> >
> > Thanks,
> > Pythonner
>
> The read() method of a file will "read all data until EOF is reached"
> if you don't pass it a size argument.  If your file is "several hundred
> MB" and your RAM is not, you may have some trouble with this.
>
> I don't know how well the replace() method works on tenths-of-a-GB
> strings.
>
> The file object supports line-by-line reads through both the readline()
> and readlines() methods, but be aware that the readlines() method will
> also try to read ALL the data into memory at once unless you pass it a
> size argument.
>
> You can also iterate through the lines in an open file object like so:
>
> for line in input_file:
> # Do something with the line here.
>
> so, if you know that you want to replace a whole actual line, you could
> do this like so:
>
> for line in input_file:
> if line == stext:
> output_file.write(rtext)
> else:
> output_file.write(line)
>
>
> Check out the docs on the file object for more info:
> http://docs.python.org/lib/bltin-file-objects.html
> 
> 
> HTH,
> ~Simon

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


Re: BCD List to HEX List

2006-07-30 Thread Grant Edwards
On 2006-07-30, John Machin <[EMAIL PROTECTED]> wrote:

>> Yes, I came here for the "algorithm" question, not the code
>> result.
>
> This is comp.lang.python, not comp.algorithms
>
> Why are you avoiding naming the chip and its compiler?

It's top secret.  If he told us, he'd have to kill us.

-- 
Grant Edwards   grante Yow!  ... I see TOILET
  at   SEATS...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread Grant Edwards
On 2006-07-31, John Machin <[EMAIL PROTECTED]> wrote:

>> but if you
>> wish ==>
>>
>> on one device, the processor in an 8-bit arm and the X-compiler is made by
>> epson
>
> 1. You still haven't *NAMED* the CPU and the compiler!!

He obviously doesn't want to have to kill all of us.

> 2. Do you mean ARM as in "Acorn/Advanced RISC Machines"??

That's the only "arm" processor I know about.

> They make 8-bit CPUs

Nope.

> 3. How does the device manage to compute the 8-decimal-digit number
> that is your input??


-- 
Grant Edwards   grante Yow!  Yow! Maybe I should
  at   have asked for my Neutron
   visi.comBomb in PAISLEY--
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Dennis Lee Bieber wrote:

> On Sun, 30 Jul 2006 17:07:57 -0500, Philippe Martin
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
>> Paul Rubin wrote:
>> 
>> > 
>> > If you prefer, You can do it all in one line:
>> > 
>> >vlist = [int(d, 16) for d in ('%X' % int(''.join(map(str, l1]
>> 
>> Thanks Paul,
>> 
>> I'm just using Python to prototype, so I cannot use any of these great
>> features of the language.
>>
> 
> You asked for "algorithm"... The above can be translated to C fairly
> easily without changing the algorithm... The array handling requires
> some thought, but...
> 
> Or did you want a literal "recipe"
> 
> for each integer in list I1:
> convert to string representation
> join the resultant strings into one string
> convert result to binary integer
> "print" the integer to string using Hex format code
> for each hex-digit in the string representation:
> convert to binary representation
> 
> But then, that description was given to you... 
> 
> That /is/ the algorithm... Implementation is a detail for the
> student 
> --
> Wulfraed  Dennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff: [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/


Thank you very much 


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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Grant Edwards wrote:

> On 2006-07-31, John Machin <[EMAIL PROTECTED]> wrote:
> 
>>> but if you
>>> wish ==>
>>>
>>> on one device, the processor in an 8-bit arm and the X-compiler is made
>>> by epson
>>
>> 1. You still haven't *NAMED* the CPU and the compiler!!
> 
> He obviously doesn't want to have to kill all of us.
> 
>> 2. Do you mean ARM as in "Acorn/Advanced RISC Machines"??
> 
> That's the only "arm" processor I know about.
> 
>> They make 8-bit CPUs
> 
> Nope.
> 
>> 3. How does the device manage to compute the 8-decimal-digit number
>> that is your input??
> 
> 
> --
> Grant Edwards   grante Yow!  Yow! Maybe I
> should
>   at   have asked for my
>   Neutron
>visi.comBomb in PAISLEY--

Yes I had arm in mind (for some reason) while it is the Smc8831
(http://www.google.com/url?sa=U&start=1&q=http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/944b73008b0bad33492570a00015d6ba/%24FILE/S5U1C88000C_2Ev3.pdf&e=9797)


>> 3. How does the device manage to compute the 8-decimal-digit number
>> that is your input??

What device manager ? think about it before being rude

Regards,

Philippe






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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
Philippe Martin wrote:

> Grant Edwards wrote:
> 
>> On 2006-07-31, John Machin <[EMAIL PROTECTED]> wrote:
>> 
 but if you
 wish ==>

 on one device, the processor in an 8-bit arm and the X-compiler is made
 by epson
>>>
>>> 1. You still haven't *NAMED* the CPU and the compiler!!
>> 
>> He obviously doesn't want to have to kill all of us.
>> 
>>> 2. Do you mean ARM as in "Acorn/Advanced RISC Machines"??
>> 
>> That's the only "arm" processor I know about.
>> 
>>> They make 8-bit CPUs
>> 
>> Nope.
>> 
>>> 3. How does the device manage to compute the 8-decimal-digit number
>>> that is your input??
>> 
>> 
>> --
>> Grant Edwards   grante Yow!  Yow! Maybe I
>> should
>>   at   have asked for my
>>   Neutron
>>visi.comBomb in PAISLEY--
> 
> Yes I had arm in mind (for some reason) while it is the Smc8831
>
(http://www.google.com/url?sa=U&start=1&q=http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/944b73008b0bad33492570a00015d6ba/%24FILE/S5U1C88000C_2Ev3.pdf&e=9797)
> 
> 
>>> 3. How does the device manage to compute the 8-decimal-digit number
>>> that is your input??
> 
> What device manager ? think about it before being rude
> 
> Regards,
> 
> Philippe



PS:

That is the first time I feel insulted posting on this list in _many_
years ... but I'm certain it is my fault.



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


Re: BCD List to HEX List

2006-07-30 Thread Philippe Martin
John Machin wrote:

> Philippe Martin wrote:
>> John Machin wrote:
>>
>> >
>> > Philippe Martin wrote:
>> >> Philippe Martin wrote:
>> >>
>> >> > Hi,
>> >> >
>> >> > I'm looking for an algo that would convert a list such as:
>> >> >
>> >> > I'm using python to prototype the algo: this will move to C in an
>> >> > embedded system where an int has 16 bits - I do not wish to use any
>> >> > python library.
>> >> >
>> >> > l1 = [1,2,3,4,6,7,8] #represents the decimal number 12345678
>> >> > l2 = func (l1)
>> >> > # l2 = [0x1, 0x2, 0xD, 0x6, 0x8, 0x7] #represents 0x12D687
>> >> >
>> >> >
>> >> > Regards,
>> >> >
>> >> > Philippe
>> >>
>> >> Thanks to all,
>> >>
>> >> I decided to attack the problem another way and change the code in
>> >> device
>> >> #2 so it can now take the output from device #1.
>> >>
>> >> As device #2 only needs to compare, add, and subtract the stuff .. it
>> >> makes my life much simpler.
>> >>
>> >
>> > I'm confused.
>> > 1. Was the original device #1 or #2?
>> > 2. How many bits does the non-original device's C compiler support?
>> > 3. If the original device is device #1, please explain where *it*
>> > obtained an 8-digit decimal number expressed as 1 digit per byte (or
>> > int) ...
>>
>>
>> Well I don't want to bore you guys more than needed ;-) but:
>>
>> Device #1 has an 8 bit processor - uses a C cross-compiler that does not
>> know anything above a 16 bit integer. I use this device to get
>> information from users "1234...".
>>
>> Device #2 has an 8 bit processor - uses a subset of Java ... that does
>> not know anything above a 16 bit integer.
>>
>>
>> The information gathered in device number #1 must then be sent to device
>> #2 (after being encrypted  ) to be compared, subtracted or added.
>>
>> The code I already have in device #2 makes the assumption that the
>> information received is an array of bytes of length N which represents an
>> actual value. ex: 0x67DF5 ==> [0x6, 0x7, 0xD, 0xF, 0x5] ... so it can
>> compare/add/subtract values ... and do its job.
>>
>> As a python fan, I figured (back to my initial not very clear request),
>> that I could prototype the above without making any major assumption as
>> to the capabilities of the interpreter.
>>
>>
>> I still believe that to be true.
>>
> 
> Try this:
> C:\junk>type bcd.py
> def reconstitute_int(alist):
> reghi, reglo = 0, 0
> for digit in alist:
> assert 0 <= digit <= 9
> reghi, reglo = mul32by10(reghi, reglo)
> reghi, reglo = add32(reghi, reglo, 0, digit)
> return reghi, reglo
> 
> def uadd16(a, b):
> return (a + b) & 0x
> 
> def shr32by4(hi, lo):
> newhi = (hi >> 4) & 0x
> newlo = ((lo >> 4) | ((hi & 0xF) << 12)) & 0x
> 
> return newhi, newlo
> 
> def add32(hia, loa, hib, lob):
> lox = uadd16(loa, lob)
> hix = uadd16(hia, hib)
> inx = ((lox & 0x8000) >> 13) + ((lob & 0x8000) >> 14) + ((loa &
> 0x8000) >> 1
> 5)
> carry = [0, 1, 1, 1, 0, 0, 0, 1][inx]
> # The above is admittedly ugly but sheesh I haven't even had my
> # second cup of coffee yet today :-)
> # Anybody who's good at solving equations in Boolean algebra,
> # pls beautify this!!
> if carry:
> hix = uadd16(hix, 1)
> expected = (hia+hib)*65536 + loa + lob
> actual = hix*65536 + lox
> if actual != expected:
> print (hia, loa), (hib, lob), (hix, lox), actual, expected,
> inx, carry
> return hix, lox
> 
> def mul32by10(hi, lo):
> tmphi, tmplo = add32(hi, lo, hi, lo) # 2 times
> tmphi, tmplo = add32(tmphi, tmplo, tmphi, tmplo) # 4 times
> tmphi, tmplo = add32(tmphi, tmplo, hi, lo) # 5 times
> tmphi, tmplo = add32(tmphi, tmplo, tmphi, tmplo) # 10 times
> return tmphi, tmplo
> 
> def make_hex32(aninthi, anintlo):
> result = []
> while aninthi or anintlo:
> result.append(anintlo & 0xF)
> aninthi, anintlo = shr32by4(aninthi, anintlo)
> return result
> 
> def reverse_list(alist):
> n = len(alist)
> for i in xrange(n >> 1):
> reg1 = alist[n - 1 - i]
> reg2 = alist[i]
> alist[i] = reg1
> alist[n - 1 - i] = reg2
> 
> 
> C:\junk>python
> Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
 import bcd
 num = bcd.reconstitute_int([1,2,3,4,5,6,7,8])
 num
> (188, 24910)
 num[0]*65536 + num[1]
> 12345678
 result = bcd.make_hex32(*num)
 result
> [14, 4, 1, 6, 12, 11]
 bcd.reverse_list(result)
 result
> [11, 12, 6, 1, 4, 14]
 ['0x%x' % digit for digit in result]
> ['0xb', '0xc', '0x6', '0x1', '0x4', '0xe']
 ^Z


Thanks John,

I will give it a good look.

Regards,

Philippe

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin

Philippe Martin wrote:

> >> 3. How does the device manage to compute the 8-decimal-digit number
> >> that is your input??
>
> What device manager ? think about it before being rude
>

No device manager [noun] was mentioned. You may have inferred rudeness
where astonishment was being implied. I'll try again:

How does the [8-bit] device manage [verb, as in "how is it able"] to
compute the [32-bit] 8-decimal-digit number that is [split up one
decimal digit per array element thus becoming] your input??

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


Re: non-blocking PIPE read on Windows

2006-07-30 Thread placid

Dennis Lee Bieber wrote:
> On 30 Jul 2006 16:22:34 -0700, "placid" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> >
> > ;)  Tsk Tsk
>
>   Have you ever seen a Tempest VT-100? Lead shielding on the monitor
> FACE... Turn the brightness all the way up and it still looked dim.
> Fiber optic to the computer. And a shield keyboard about three inches
> thick and weighing 5 lbs.
>
>   All to keep "them" from using radio equipment to pick up key strokes
> or the display scan line radiation (use an external vertical/horizontal
> sweep generator to an oscilloscope, and a high-gain amplifier to detect
> the brightness variation of the CRT).


Nope, i have not seen one.

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


Re: python and JMS

2006-07-30 Thread Ravi Teja

Alan Kennedy wrote:
> [tksri2000]
> > I am looking to use python to talk to JMS. Can some please point me to
> > such resources if this is possible.
>
> PyHJB is the python-to-JMS gateway. ... via HJB, the HTTP JMS bridge.
> http://hjb.python-hosting.com/
>
> HJB (HTTP JMS Bridge)
> http://hjb.berlios.de/

Neat. Apparently ActiveMQ supports multi-language clients through STOMP
too.
http://www.activemq.org/site/cross-language-clients.html

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


Re: BCD List to HEX List

2006-07-30 Thread John Machin
Philippe Martin wrote:

>
> Yes I had arm in mind (for some reason) while it is the Smc8831
> (http://www.google.com/url?sa=U&start=1&q=http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/944b73008b0bad33492570a00015d6ba/%24FILE/S5U1C88000C_2Ev3.pdf&e=9797)

That appears to be volume 2 of the 2-volume set of manuals that come
with the tools package. It says that vol 1 has details about the C
compiler.

This appears to be volume 1:
http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/1410881ddee374f7492570a00015d65e/$FILE/C88000C_1Ev3.pdf

Section 1.2.3 Data Types mentions unsigned and signed long (32-bit)
data types. There are several references to "long" later, including
declarations in sample C code, and details of how long (32-bit)
function args are passed.

There appears to be a fundamental disconnection here somewhere ...

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


Re: How do you implement this Python idiom in C++

2006-07-30 Thread alainpoint

Pierre Barbier de Reuille wrote:
> [EMAIL PROTECTED] wrote:
> > Pierre Barbier de Reuille wrote:
> [...]
> >
> > I thank you for your response. The equivalent of your solution is
> > posted hereunder:
> > class cA(object):
> > count=0
> > def __init__(self):
> > self.__class__.count +=1
> > @classmethod
> > def getcount(cls):
> > return cls.count
> > def __del__(self):
> > self.__class__.count -=1
> > class cB(cA):
> > count=0
> > def __init__(self):
> > super(cB,self).__init__()
> > for klass in self.__class__.__bases__:
> > klass.count +=1
> >
> > a=cA() ; b=cA(); c= cA()
> > d=cB() ; e=cB(); f= cB()
> > a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
> > g=cA()
> > g.a=1
> > print  '#cA=',cA.getcount()  # 7
> > print '#cB=',cB.getcount() #  3
> > del g
> > print  '#cA=',cA.getcount()  # 6
> > print '#cB=',cB.getcount() #  3
> >
> > There is nothing impossible in Python ;-)
> >
> > Alain
> >
>
> Well, nothing is impossible, but it is now much much more complex ! As a
> proof of that, your version does not work completely :P (try deleting d
> for example).
>
> I add a working version, but you will also notice that I have to
> *explicitly* walk over all the classes of the hierarchy, testing for the
> one who have a "count" attribute, hoping that this attribute is indeed
> for counting the number of objects and not anything else ... so the
> solution is quite fragile and very slow.
>
> class cA(object):
> count=0
> def __init__(self):
> self.__class__.count +=1
> for klass in self.__class__.__bases__:
> if hasattr( klass, "count" ):
> klass.count += 1
>
> @classmethod
> def getcount(cls):
> return cls.count
> def __del__(self):
> self.__class__.count -=1
> for klass in self.__class__.__bases__:
> if hasattr( klass, "count" ):
> klass.count -= 1
> class cB(cA):
> count=0
>
> a=cA() ; b=cA(); c= cA()
> d=cB() ; e=cB(); f= cB()
> a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
> g=cA()
> g.a=1
> print  '#cA=',cA.getcount()  # 7
> print '#cB=',cB.getcount() #  3
> del g
> del d
> print  '#cA=',cA.getcount()  # 5
> print '#cB=',cB.getcount() #  2
>
> Pierre

Good point Pierre. But you'll have to admit that the class usage in
Python is much simpler (just derive from the class)
class cB(cA):
  count=0
contrarily to the C++ usage where you must remind the compiler of the
Counted class in every derived class.

In  Python, you have to bite only once thru the sour apple  


Alain

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


import a user created python file as module

2006-07-30 Thread Phoe6
Hi,
 I have the following directory structure in my project.
Base:
 file1.py
 file2.py
 Directory1:
   file1-dir1.py

I am able to import file1 into file2.py
What I need to do is, import file1 in the file file1-dir1.py.
I did not create the entire dir structure as package. Adding
__init__.py file in both Base: as well as Directory1: is not helpful. I
am unable to import file1 in the file1-dir1.py. It is not able to find
the path of the file1.py.

How and what should I do to import file1.py into file1-dir1.py ? Please
give me some references to the tutorial topic which I can study as
well.

Thanks,
Senthil

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


Re: BCD List to HEX List

2006-07-30 Thread Paul Rubin
Philippe Martin <[EMAIL PROTECTED]> writes:
> > Why are you avoiding naming the chip and its compiler?
> 
> I must disagree on that one: There are many threads on this site where
> people just have fun talking algorithm. I'm not an algo. expert and I know
> there are many here.

This is just like the very common situation here and on sci.crypt,
where a person has a programming or algorithm question and gets asked
what the application is, and when they answer, it turns out that what
they need is not anything like what they thought they needed.

> on one device, the processor in an 8-bit arm and the X-compiler is made by
> epson 
> 
> on the other device, the processor is unknown to me and the environment is a
> subset of java made for smartcards called javacard.

 You mean ARM?? There is no such thing as an 8-bit ARM; they are
32-bit cpu's that (in some models) support a 16-bit instruction
format.

Javacard is an interpreter that runs in many 8-bit processors.  The
interpreter supports 32-bit arithmetic.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem (- variable definition branch)

2006-07-30 Thread H J van Rooyen
"Gerhard Fiedler" <[EMAIL PROTECTED]> wrote:

8<-

| I'm not sure where you're trying to go. I think that most people (and even
| Bruno, who argued this issue most strongly) call Python variables
| "variables" every now and then, or maybe even usually. But it was helpful
| for me to see the difference between Python variables and, say, C
| variables. I think this has been a useful discussion in this respect. There
| is a difference, and it is important (IMO).
|
| Whether Python variables are in fact "variables" probably depends mostly on
| your definition of "variable", and that's IMO a tough one -- a definition
| of "variable" that includes all those language elements that various
| languages call "variables", and nothing else (that's the tough part).
| Whether that definition exists, and whether it includes Python "variables",
| remains to be seen :)

I am not one for formal definitions but I think something like this:

if s is a python string containing "hello world "
and I can write :

s = s + "some extra stuff"

then for me s is a variable - the fact that in the python implementation there
are two things, namely the original hello world string and the new longer one is
kind of irrelevant - if I try to print s I will get the new longer string, so
from where I stand s is a variable - it has changed over time from having one
"value" to another one...
and that is about the simplest definition you can get - its a symbolic reference
to something that can change over time - and in python it seems to me that every
name is a variable, cos you can tie the name to very different things at
different times:

>>> s = "hello world"
>>> print s
hello world
>>> s = s + " some more stuff"
>>> print s
hello world some more stuff
>>> s = [1,2,3,4,5,6,7,8,9,0]
>>> print s
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> def foo():
 print "banana"

 >>> s = foo
>>> s

>>> s()
banana
>>>

s is surely a variable - there is nothing constant over time about it, and from
this point of view its very "mutable" indeed - and what is more - in every case,
after the assignment, unless you have stored a reference with a different name
to them, the old values look from a programmer's point of view as if they have
been "overwritten" - you can't use anything about s to get at them again...

Now there's a thought - an optional slice notation that slices s over time,
so that s{0} is the current s, and s{-1} the previous one, and so on, with
the default being s[{0}] the {0} being optional

This should be relatively easy to implement at the point of re binding the name
by replacing the pointer (or whatever) to the object with a stack of them.  I
think you could only do it in python, but I may be wrong...

Another world first for python?  - (TIC)

"Look mommy! - I only use one variable name! "

- Hendrik


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


Re: import a user created python file as module

2006-07-30 Thread Amit Khemka
On 30 Jul 2006 23:07:07 -0700, Phoe6 <[EMAIL PROTECTED]> wrote:
> Hi,
>  I have the following directory structure in my project.
> Base:
>  file1.py
>  file2.py
>  Directory1:
>file1-dir1.py
>
> I am able to import file1 into file2.py
> What I need to do is, import file1 in the file file1-dir1.py.
> I did not create the entire dir structure as package. Adding
> __init__.py file in both Base: as well as Directory1: is not helpful. I
> am unable to import file1 in the file1-dir1.py. It is not able to find
> the path of the file1.py.
>
> How and what should I do to import file1.py into file1-dir1.py ? Please
> give me some references to the tutorial topic which I can study as
> well.

 Modify the path where python searches for modules, for example in
file1-dir1.py add:

 import sys
 sys.path.append("/path/to/Base")
 import file1


cheers,
amit.
-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Html character entity conversion

2006-07-30 Thread Claudio Grondi
John Machin wrote:
> Claudio Grondi wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>Claudio Grondi wrote:
>>>
>>>
[EMAIL PROTECTED] wrote:


>Here is my script:
>

>from mechanize import *
>from BeautifulSoup import *

>import StringIO
>b = Browser()
>f = b.open("http://www.translate.ru/text.asp?lang=ru";)
>b.select_form(nr=0)
>b["source"] = "hello python"
>html = b.submit().get_data()
>soup = BeautifulSoup(html)
>print  soup.find("span", id = "r_text").string
>
>OUTPUT:
>привет
>питон
>--
>In russian it looks like:
>"привет питон"
>
>How can I translate this using standard Python libraries??
>
>--
>Pak Andrei, http://paxoblog.blogspot.com, icq://97449800
>

Translate to what and with what purpose?

Assuming your intention is to get a Python Unicode string, what about:

strHTML = 'привет
питон'
strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
strUnicode = eval("u'%s'"%strUnicodeHexCode)

?

I am sure, there is a more elegant and direct solution, but just wanted
to provide here some quick response.

Claudio Grondi
>>>
>>>
>>>Thank you, Claudio.
>>>Really interest solution, but it doesn't work...
>>>
>>>In [19]: strHTML = 'привет
>>>питон'
>>>
>>>In [20]: strUnicodeHexCode = strHTML.replace('&#','\u').replace(';','')
>>>
>>>In [21]: strUnicode = eval("u'%s'"%strUnicodeHexCode)
>>>
>>>In [22]: print strUnicode
>>>---
>>>exceptions.UnicodeEncodeErrorTraceback (most
>>>recent call last)
>>>
>>>C:\Documents and Settings\dron\
>>>
>>>C:\usr\lib\encodings\cp866.py in encode(self, input, errors)
>>> 16 def encode(self,input,errors='strict'):
>>> 17
>>>---> 18 return codecs.charmap_encode(input,errors,encoding_map)
>>> 19
>>> 20 def decode(self,input,errors='strict'):
>>>
>>>UnicodeEncodeError: 'charmap' codec can't encode characters in position
>>>0-5: character maps to 
>>>
>>>In [23]: print strUnicode.encode("utf-8")
>>>сВЗсВИсВАсБ┤сБ╖сВР сВЗсВАсВРсВЖсВЕ
>>><-- it's not my string "привет питон"
>>>
>>>In [24]: strUnicode.encode("utf-8")
>>>Out[24]:
>>>'\xe1\x82\x87\xe1\x82\x88\xe1\x82\x80\xe1\x81\xb4\xe1\x81\xb7\xe1\x82\x90
>>>\xe1\x82\x87\xe1\x82\x80\xe1\x82\x90\xe1\x82\x86\xe1\x82\
>>>x85' <-- and too many chars
>>>
>>
>>Have you considered, that the HTML page specifies charset=windows-1251
>>in its
>> tag ?
>>You are apparently on Linux or so, so I can't track this problem down
>>having only a Windows box here, but inbetween I know that there is
>>another problem with it:
>>I have erronously assumed, that the numbers in п are hexadecimal,
>>but they are decimal, so it is necessary to do hex(int('1087')) on them
>>to get at the right code to put into eval().
>>As you know now the idea I hope you will succeed as I did with:
>>
>> >>> lstIntUnicodeDecimalCode = strHTML.replace('&#','').split(';')
>> >>> lstIntUnicodeDecimalCode
>>['1087', '1088', '1080', '1074', '1077', '1090', ' 1087', '1080',
>>'1090', '1086', '1085', '']
>> >>> lstIntUnicodeDecimalCode = lstIntUnicodeDecimalCode[:-1]
>> >>> lstHexUnicode = [ hex(int(item)) for item in lstIntUnicodeDecimalCode]
>> >>> lstHexUnicode
>>['0x43f', '0x440', '0x438', '0x432', '0x435', '0x442', '0x43f', '0x438',
>>'0x442', '0x43e', '0x43d']
>> >>> eval( 'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
>>u'\u043f\u0440\u0438\u0432\u0435\u0442\u043f\u0438\u0442\u043e\u043d'
>> >>> strUnicode = eval(
>>'u"%s"'%''.join(lstHexUnicode).replace('0x','\u0' ) )
>> >>> print strUnicode
>>приветпитон
>>
>>Sorry for that mess not taking the space into consideration, but I think
>>  you can get the idea anyway.
> 
> 
> I hope he *doesn't* get that "idea".
> 
> #>>> strHTML =
> 'приветпит&#
> 1086;н'
> #>>> strUnicode = [unichr(int(x)) for x in
> strHTML.replace('&#','').split(';') if
>  x]
> #>>> strUnicode
> [u'\u043f', u'\u0440', u'\u0438', u'\u0432', u'\u0435', u'\u0442',
> u'\u043f', u'
> \u0438', u'\u0442', u'\u043e', u'\u043d']
> #>>>
Knowing about the built-in function unichr() is a good thing, but ... 
there are still drawbacks, because (not tested!) e.g. :
'100x hallo Python' translates to
'100x привет 
Питон'
and can't be handled by improving the core idea by usage of unichr() 
instead of the eval() stuff because of the wrong approach with using 
.replace() and .split() which work only on the given example but not in 
general case.
I am just too lazy to sit down and work on code extracting from the HTML 
the &#; sequences to convert only them letting the other content of 
the string unchanged in order to arrive at a solution that works in 
general case (it should be not hard and I suppose the OP has it already 
:-) if he is at a Python skill level of playing around with the 
mechanize module).
I am still convinced, that there must be a mor

Re: import a user created python file as module

2006-07-30 Thread Rob Wolfe


> How and what should I do to import file1.py into file1-dir1.py ? Please
> give me some references to the tutorial topic which I can study as
> well.

And some reference:

http://docs.python.org/tut/node8.html

Regards,
Rob

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