Python strings and coding conventions

2009-01-10 Thread koranthala
Hi,
   Python Coding Convention (PEP 8) suggests :
  Maximum Line Length

Limit all lines to a maximum of 79 characters.

  I have a string which is ~110 char long. It is a string which I am
going to print in a text file as a single string.
  i.e. in that text file, each line is taken as a different record -
so it has to be in a single line.

  Now, how can I write this code - while following PEP 8?
  I tried blockstrings, but as shown in the example below:
>>> s = r'''
... abcd
... efgh
... '''
>>> s
'\nabcd\nefgh\n'
   it has "\n" inserted - which will disallow printing it to a single
line.

   I thought about other options like concatenating strings etc, but
it seems very kludgy - esp since the whole string has a single meaning
and cannot be easily split to many logically. Then I thought of
creating a blockstring and then removing "\n", but it seemed
kludgier...

   I am sure this is a very usual issue and I am missing some very
very simple solution. But I cannot think of it at all...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python strings and coding conventions

2009-01-10 Thread koranthala
On Jan 11, 9:26 am, Robert Kern  wrote:
> [email protected] wrote:
> > Hi,
> >    Python Coding Convention (PEP 8) suggests :
> >   Maximum Line Length
>
> >     Limit all lines to a maximum of 79 characters.
>
> >   I have a string which is ~110 char long. It is a string which I am
> > going to print in a text file as a single string.
> >   i.e. in that text file, each line is taken as a different record -
> > so it has to be in a single line.
>
> >   Now, how can I write this code - while following PEP 8?
> >   I tried blockstrings, but as shown in the example below:
>  s = r'''
> > ... abcd
> > ... efgh
> > ... '''
>  s
> > '\nabcd\nefgh\n'
> >    it has "\n" inserted - which will disallow printing it to a single
> > line.
>
> >    I thought about other options like concatenating strings etc, but
> > it seems very kludgy - esp since the whole string has a single meaning
> > and cannot be easily split to many logically. Then I thought of
> > creating a blockstring and then removing "\n", but it seemed
> > kludgier...
>
> I usually use implicit concatenation:
>
> s = ('some long text that '
>       'needs to be split')
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

This is a very good method.
I found another method too - on further investigation
>>> s = "abc\
... efg"
>>> s
'abcefg'
Only problem being that it doesnt support indentation.
So, implicit concatenation it is...
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHON HTTP POST

2009-01-14 Thread koranthala
Does google accept POST?

Anyways, if you dont need to post files, you can use urlencode itself.
def encode_formdata(fields):
body = urllib.urlencode(dict())
content_type = "application/x-www-form-urlencoded"
return content_type, body

If you need to post files too, then you will have to use multipart
data
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form
fields.
files is a sequence of (name, filename, value) elements for data
to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (key, filename))
L.append('Content-Type: %s' % mimetypes.guess_type(filename)
[0] or 'application/octet-stream'
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body

Since POST files doesnt work with urllib, you might have to use
httplib - or go for very high level tools like twisted.
I here show an example with httplib.

def post(host, selector, fields, files):
if files:
   content_type, body = encode_multipart_formdata(fields, files)
else:
   content_type, body = encode_formdata(fields)

h = httplib.HTTPConnection(host)
#Spoof Mozilla
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',
'Content-Type': content_type
}
h.request('POST', selector, body, headers)
res = h.getresponse()
return res.status, res.reason, res.read()

Please note that you can use multipart whether or not files are there,
but parsing multipart usually is slower.

Hope this helps.

[email protected] wrote:
> Hi,
>
> I need one complete example of how to do a http post to any site.
> I have tried making a POST to google but all I am returned with is a
> 405 error.
> I don't want to use Pygoogle as I want to try and do this with other
> sites.
> I am also having problems inputing with the param
> I have tried Mechanize. There are no problems with getting data only
> posting.
>
> >>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
> ... 'User-Agent':'Mozilla/4.0',
> ... 'Content-Length':'7'}
> >>> conn = httplib.HTTPConnection("www.google.com")
> >>> conn.request("POST","/search",params,headers)
> >>> r2 =  conn.getresponse()
> >>> print r2.status, r2.reason
> 405 Method Not Allowed
>
> Regards,
> Dhaval
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHON HTTP POST

2009-01-14 Thread koranthala
On Jan 14, 2:21 pm, [email protected] wrote:
> Does google accept POST?
>
> Anyways, if you dont need to post files, you can use urlencode itself.
> def encode_formdata(fields):
>         body = urllib.urlencode(dict())
>         content_type = "application/x-www-form-urlencoded"
>         return content_type, body
>
> If you need to post files too, then you will have to use multipart
> data
> def encode_multipart_formdata(fields, files):
>     """
>     fields is a sequence of (name, value) elements for regular form
> fields.
>     files is a sequence of (name, filename, value) elements for data
> to be uploaded as files
>     Return (content_type, body) ready for httplib.HTTP instance
>     """
>     BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
>     CRLF = '\r\n'
>     L = []
>     for (key, value) in fields:
>         L.append('--' + BOUNDARY)
>         L.append('Content-Disposition: form-data; name="%s"' % key)
>         L.append('')
>         L.append(value)
>     for (key, filename, value) in files:
>         L.append('--' + BOUNDARY)
>         L.append('Content-Disposition: form-data; name="%s";
> filename="%s"' % (key, filename))
>         L.append('Content-Type: %s' % mimetypes.guess_type(filename)
> [0] or 'application/octet-stream'
>         L.append('')
>         L.append(value)
>     L.append('--' + BOUNDARY + '--')
>     L.append('')
>     body = CRLF.join(L)
>     content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
>     return content_type, body
>
> Since POST files doesnt work with urllib, you might have to use
> httplib - or go for very high level tools like twisted.
> I here show an example with httplib.
>
> def post(host, selector, fields, files):
>     if files:
>        content_type, body = encode_multipart_formdata(fields, files)
>     else:
>        content_type, body = encode_formdata(fields)
>
>     h = httplib.HTTPConnection(host)
>     #Spoof Mozilla
>     headers = {
>         'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
> rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',
>         'Content-Type': content_type
>         }
>     h.request('POST', selector, body, headers)
>     res = h.getresponse()
>     return res.status, res.reason, res.read()
>
> Please note that you can use multipart whether or not files are there,
> but parsing multipart usually is slower.
>
> Hope this helps.
>
> [email protected] wrote:
> > Hi,
>
> > I need one complete example of how to do a http post to any site.
> > I have tried making a POST to google but all I am returned with is a
> > 405 error.
> > I don't want to use Pygoogle as I want to try and do this with other
> > sites.
> > I am also having problems inputing with the param
> > I have tried Mechanize. There are no problems with getting data only
> > posting.
>
> > >>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
> > ...         'User-Agent':'Mozilla/4.0',
> > ...         'Content-Length':'7'}
> > >>> conn = httplib.HTTPConnection("www.google.com")
> > >>> conn.request("POST","/search",params,headers)
> > >>> r2 =  conn.getresponse()
> > >>> print r2.status, r2.reason
> > 405 Method Not Allowed
>
> > Regards,
> > Dhaval
>
>

oops - Forgot to mention that POSTing files mechanism is taken from a
recipe in active state -
http://code.activestate.com/recipes/146306/
--
http://mail.python.org/mailman/listinfo/python-list


Python Crashes

2009-01-14 Thread koranthala
Hi,
I have a twisted based application based on Python 2.4.3. I also
have one thread in this application.

I found that my program crashes repeatedly after a random interval
(ranging from 10 min to 3 hr). When I say crash, it is not just that
the program dies. Rather in WinXP - a window comes mentioning that
'Python.exe unexpectedly crashed'.
I tried putting in catching the exception by using try: except -
and logging everything. But the logging code is also not hit, i.e.
even the 'except' code is not hit. I feel that the base python
interpreter itself is crashing due to some bug in my program.
Earlier, I had put code as
try:
except:
  log
 At this time, my whole machine also froze. It was so slow that
one mouse movement happened after 7-8 minutes after I moved the
mouse.

Then I modified the code to
try:
except Exception:
  log

Then, the machine no longer freezes. But, still there is no
logging of errors happening too.

Could anyone guide me on this? I have been facing this issue for a
day, and cannot seem to solve it.

P.S ->I am not allowed to post the code of application - so I hope
I have explained it enough.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Crashes

2009-01-14 Thread koranthala
On Jan 15, 3:12 am, "James Mills" 
wrote:
> On Thu, Jan 15, 2009 at 6:57 AM, koranthala  wrote:
> > Hi,
> >    I have a twisted based application based on Python 2.4.3. I also
> > have one thread in this application.
>
> >    I found that my program crashes repeatedly after a random interval
> > (ranging from 10 min to 3 hr). When I say crash, it is not just that
> > the program dies. Rather in WinXP - a window comes mentioning that
> > 'Python.exe unexpectedly crashed'.
> >    I tried putting in catching the exception by using try: except -
> > and logging everything. But the logging code is also not hit, i.e.
> > even the 'except' code is not hit. I feel that the base python
> > interpreter itself is crashing due to some bug in my program.
> >    Earlier, I had put code as
> > try:
> > except:
> >  log
> >     At this time, my whole machine also froze. It was so slow that
> > one mouse movement happened after 7-8 minutes after I moved the
> > mouse.
>
> > Then I modified the code to
> > try:
> > except Exception:
> >  log
>
> >    Then, the machine no longer freezes. But, still there is no
> > logging of errors happening too.
>
> >    Could anyone guide me on this? I have been facing this issue for a
> > day, and cannot seem to solve it.
>
> > P.S ->    I am not allowed to post the code of application - so I hope
> > I have explained it enough.
>
> Do you use any 3rd party extensions (DLLs) ?
>
> cheers
> James

I am using 9 3rd party modules and there are some DLLs too - PIL etc.
But the problem is that the issue comes only after 3 hrs usually.
When I checked the memory using taskmanager, I found that it is not
going too high.
Is there any tool or anything which will help me debug this?
--
http://mail.python.org/mailman/listinfo/python-list


Python Style Guide Questions

2009-01-15 Thread koranthala
Hi,
   Which is more advisable?
import x
b = x.a
 or
from x import a
b = a

   I read in Learning Python that it is always better to use the
former - especially since namespace wont be dirtied. But, doing that
with PEP 8 together causes my code to look rather cluttered. Reason
being that - PEP 8 suggests that have max line length = 79 chars.
So my code mostly looks like this:
class x:
 def y():
  try:
  if test:
  obj.filename = str(os.path.basename
(obj1.find_next_element().\
  get_file_path()))
  obj.modify_time = obj.filename.find_created_time()
+  \
  datetime.timedelta
(seconds=time.find_time())

etc .. etc..
Almost every line requires the '\'. Also, especially since Python also
uses whitespace as indentation, I keep confusing the block indentation
with the indentation that the '\' causes in the next line.

Could you please let me know what you guys usually do in such cases?
Is it advisable to go for the
from x import a to avoid this clutter?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Style Guide Questions

2009-01-15 Thread koranthala
On Jan 16, 12:00 pm, Terry Reedy  wrote:
> koranthala wrote:
> > Hi,
> >    Which is more advisable?
> > import x
> > b = x.a
> >              or
> > from x import a
> > b = a
>
> If I know I want just one thing from x, I tend to use latter.
> I also like 'import xyzlib as x'
>
> >    I read in Learning Python that it is always better to use the
> > former - especially since namespace wont be dirtied.
>
> Namespace get cluttered, not dirtied.  In any case, either 'x' or 'a'
> gets added.  One new name either way.
>
> > class x:
> >      def y():
> >           try:
> >               if test:
> >                   obj.filename = str(os.path.basename
> > (obj1.find_next_element().\
> >                                               get_file_path()))
> >                   obj.modify_time = obj.filename.find_created_time()
> > +  \
> >                                               datetime.timedelta
> > (seconds=time.find_time())
>
> Use 4 spaces instead of 5 for indents
>
> > Almost every line requires the '\'.
>
> As Steven said, usually no
>
> > Also, especially since Python also
> > uses whitespace as indentation, I keep confusing the block indentation
> > with the indentation that the '\' causes in the next line.
>
> '\' causes no indentation
>
> Beyond that, consider find a style you like.  I agree with Stvhen about
> using 'thought-sized' expressions.
>
> tjr

Thank you Steven and TJR. I will try to implement the thought sized
expressions.
I was rather misled by trying to decrease the line count as much as
possible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start two threads in same time

2009-01-16 Thread koranthala
On Jan 16, 7:36 pm, [email protected] wrote:
> Hello,
>
> Does anybody know how can I start two threads in same time?
>
> Regards,
> John

Use threading module.
Creating a new thread is as easy as --
---
import threading

class ThreadedClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)

def run(self):
 **Do whatever you want do in the new thread here**

threaded_obj = ThreadedClass()
threaded_obj.setDaemon(True)  # If you want a daemon thread
threaded_obj.start() # Start the new thread

Do whatever you want to do in main thread here%%%

threaded_obj.join() #Close the new thread by joining it with the main
thread



The following document might be of help:
http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Start two threads in same time

2009-01-16 Thread koranthala
On Jan 16, 7:46 pm, koranthala  wrote:
> On Jan 16, 7:36 pm, [email protected] wrote:
>
> > Hello,
>
> > Does anybody know how can I start two threads in same time?
>
> > Regards,
> > John
>
> Use threading module.
> Creating a new thread is as easy as --
> ---
> import threading
>
> class ThreadedClass(threading.Thread):
>     def __init__(self):
>         threading.Thread.__init__(self)
>
>     def run(self):
>          **Do whatever you want do in the new thread here**
>
> threaded_obj = ThreadedClass()
> threaded_obj.setDaemon(True)  # If you want a daemon thread
> threaded_obj.start() # Start the new thread
>
> Do whatever you want to do in main thread here%%%
>
> threaded_obj.join() #Close the new thread by joining it with the main
> thread
>
> 
>
> The following document might be of 
> help:http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf

If you want to create n threads, just create and call the threaded_obj
n times.
So, the code will look like:

threaded_obj = []

for i in range(n):
   threaded_obj[i] = ThreadedClass()
   threaded_obj[i].setDaemon(True)  # If you want a daemon thread
   threaded_obj[i].start() # Start the new thread

Do whatever you want to do in main thread here%%%

#To close the threads
for o in threaded_obj:
   o.join()

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


Python Style Guide Questions - Contd.

2009-01-19 Thread koranthala
Hi,
   I have some more questions about python code styling.
   1. Global Variables: In my code, I am using some global variables.
Now, when I ran PyLint, it raised convention errors mentioning that
they should be CAPITAL_ALPHABETS. Now, in PEP 8, I did not see that
mentioned. Please let me know whether that is the usual styling
mechanism which is used.
   2. I have many loops wherein I define a variable as just a counter.
   for x in range(counter):
  do_something()
   Please note that I am not using x anywhere in the program.
   Pylint again raises warnings saying that the variable should be
used.
   Should I disregard it or use the default variable _ ?
   for _ in range(counter):
  do_something()
   pylint does not raise errors for those. Are there any issues in
using _ ?
--
http://mail.python.org/mailman/listinfo/python-list


Logging help

2009-01-19 Thread koranthala
Hi,
   Is it possible somehow to have the logging module rotate the files
every time I start it.
   Basically, I can automatically rotate using RotatingFileHandler;
Now I want it rotated every time I start the program too.
   Ex: The logging file - log.txt
   Now, rotatingfilehandler goes and updates to log.txt.1, log.txt.2,
log.txt.3 etc.
   Now, I also want to rotate it automatically I start the program -
i.e.
   The second time I start the program - log.txt -> log.txt.1, log.txt.
1 -> log.txt.2 etc.

   I can write up a simple script to move it by 1 digit every time.
   My question is - is it possible automatically via logging
functionality? This is needed because say TimedRotatingFileHandler etc
wont work that well otherwise.

   It does look like  twisted.python.logfile.DailyLogFile seems to be
an Ok option, but I want to use the logging module in the Python
distribution, since it is more powerful.

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


Re: Logging help

2009-01-20 Thread koranthala
On Jan 20, 5:45 am, Chris Rebert  wrote:
> On Mon, Jan 19, 2009 at 11:36 AM, koranthala  wrote:
> > Hi,
> >   Is it possible somehow to have the logging module rotate the files
> > every time I start it.
> >   Basically, I can automatically rotate using RotatingFileHandler;
> > Now I want it rotated every time I start the program too.
>
> Just call the .doRollover() method of the RotatingFileHandler at the
> start of the program.
> Reading The Fine Documentation for the module is helpful.
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

My question was poorly framed. I will try to explain the issue a
little more.
Current doRollover method is not very helpful to rolling over every
day if the process starts and stops many times.
For example:
TimedRotatingFileHandler - when='D' Interval=1. I call
handler.doRollover everytime process starts.

First run - the output files are
log.txt
--
Second run - files are
log.txt, log.txt.2009-01-20
--
Till now, fine.
Third run - files are
log.txt, log.txt.2009-01-20 ***But the earlier file is overwritten***

The doRollover method does not append to the earlier file. Rather, it
creates a new file with the same name.
Due to this the earlier logs are all gone.

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


Re: Logging help

2009-01-21 Thread koranthala
On Jan 21, 2:55 pm, Vinay Sajip  wrote:
> On Jan 20, 10:11 am,koranthala wrote:
>
>
>
> > The doRollover method does not append to the earlier file. Rather, it
> > creates a new file with the same name.
>
> Err... that's what rollover means - switching to a new log file (and
> renaming the old ones). If it just appended to the old one, why would
> it be called doRollover ? ;-)
>
> Regards,
>
> Vinay Sajip

I understand Vinay. But my point is that I wanted a mechanism to
rotate the log files based on data - i.e. today one log, tomorrow
another. This is easier because when trouble tickets are raised, users
mention that X failed at this time.
Now, timedrotatingfilehandler does it - but only if the program is
running the whole length of time.
My tool is invoked by a cron job - so the program runs, then stops
again and again.
When I posted the question here, I was forwarded to the doRollover
mechanism as a solution.
I was just mentioning that doRollover, due to overwriting the files I
would lose everything that is stored before.
What I did now was to copy the file, and then append to the rolledover
file - which does serve the purpose.
But it is kludgy, and I dont think my situation is unique. I did see
other people asking for the same functionality.

So I was wondering whether it would be good idea to have this also in
the next version.
--
http://mail.python.org/mailman/listinfo/python-list


Dictionary : items()

2009-01-21 Thread koranthala
Hi,
   Dictionary has the items method which returns the value as a list
of tuples.
   I was wondering whether it would be a good idea to have an extra
parameter - sort - to allow the tuples to be sorted as the desire of
users.
   Currently what I do is:

class SDict(dict):
def items(self, sort=None):
'''Returns list. Difference from basic dict in that it is
sortable'''
if not sort:
return super(SDict, self).items()
return sorted(self.iteritems(), key=sort)

Usage:
for a dictionary of strings sorted:
l = abcd.items(sort=lambda x:(x[1].lower(), x[0]))

Now what I wanted was to incorporate this in the basic dictionary
itself. Not only items(), but the methods similar to it - iteritems
etc all can also have this parameter.

Please let me know your views.
Is this a good enough idea to be added to the next version of Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging help

2009-01-22 Thread koranthala
On Jan 22, 2:14 pm, Vinay Sajip  wrote:
> On Jan 22, 6:49 am,koranthala wrote:
>
> > I understand Vinay. But my point is that I wanted a mechanism to
> > rotate the log files based on data - i.e. today one log, tomorrow
>
> Did you mean "based on date"?
>
> > another. This is easier because when trouble tickets are raised, users
> > mention that X failed at this time.
> > Now, timedrotatingfilehandler does it - but only if the program is
> > running the whole length of time.
> > My tool is invoked by a cron job - so the program runs, then stops
> > again and again.
>
> If you just want a log file whose name is date-based, you don't need a
> rotating file handler. Compute the file name from the date and use the
> API to create a FileHandler specifying that file name, and add it to
> your logger. For example:
>
> import logging, time
>
> logging.basicConfig(level=logging.DEBUG, filename=time.strftime("/path/
> to/my/logs/myapp-%Y-%m-%d-%H%M.log", time.localtime()), filemode="w")
> logging.debug("Hello, world!")
>
> Hopefully you can adapt this snippet to your needs.
>
> Regards,
>
> Vinay Sajip

Thank you very much Vinay. You have been extremely helpful.
This was my first design - but then I found that log system was taking
up quite a huge chunk of the memory.
That is why I went to rotating file handler.
Anyways, now I have modified doRollover to append if file is there,
so, for me it is working.
What I was thinking was such an option in the basic logging system
might be of good help.
Again, Vinay, Thank you very much. You were extremely helpful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging help

2009-01-22 Thread koranthala
On Jan 22, 10:25 pm, Vinay Sajip  wrote:
> On Jan 22, 3:40 pm,koranthala wrote:
>
> > Thank you very much Vinay. You have been extremely helpful.
> > This was my first design - but then I found that log system was taking
> > up quite a huge chunk of the memory.
> > That is why I went to rotating file handler.
>
> Using just plain FileHandler takes up less memory than using
> RotatingFileHandler (because using the latter imports the "handlers"
> module into memory, whereas using the former does not). I'm not aware
> of any problem where logging takes up a huge chunk of memory (under
> normal usage) - how did you measure the memory usage which was due to
> logging?
>
> > Anyways, now I have modified doRollover to append if file is there,
> > so, for me it is working.
> > What I was thinking was such an option in the basicloggingsystem
> > might be of good help.
>
> The solution I suggested is IMO better than using a patched
> RotatiingFileHandler, both because it avoids importing an extra module
> (if memory really is a concern) and because you don't need to change
> your code across Python version updates. How does my suggestion to use
> FileHandler not meet your use case?
>
> > Again, Vinay, Thank you very much. You were extremely helpful.
>
> You're welcome.
>
> Best wishes,
>
> Vinay Sajip

oops - again I was very unclear in my post.
What i meant was that due to the log getting very big - i.e. the log
was in 100MB range (since it is a new product - a lot of debugging is
done via logs). Not RAM.
Having a rotating file handler helped there - because I could say only
5 such logs are needed.
--
http://mail.python.org/mailman/listinfo/python-list


A Twisted Design Decision

2009-01-27 Thread koranthala
Twisted, being twisted in its behavior is causing quite a lot of
confusion in design decisions.

I will put forward a comparison of reactor and non-reactor patterns.
The code is not exact - whatever is shown is the gist of it.

For example, a message handler - in a usual scenario:
class messageHandler:
   def run():
 msg = self.get_next_msg()
 if not msg.send():
 self.handle_failure()

To handle parallel execution, we will have to use threads, but the
code flow is similar.

How do we do the same in a reactor pattern (Twisted)?
msg.send will cause a deferred to be raised - the failure, if it
happens will happen much later.
i.e. other than sending messageHandler object in msg.send(), I cannot
see any mechanism of running handle_failure.

In Twisted:
class messageHandler:
   def run():
 msg = self.get_next_msg()
 msg.send(self):

class msgClass:
def send(o):
d = deferred.addCallBack(success_handler, o).addErrBack
(failure_handler, o)

def failure_handler(o):
o.handle_failure()

Basically, what I find is that a lot of functional encapsulation is
now lost by following reactor pattern. handle_failure is
messageHandlers code and makes for pretty viewing if called from
inside messageHandler itself. But, due to the twisted nature of
reactor pattern, the msg Class - who is functionally a lower class to
messageHandler invoking messageHandler's code.

Is there a way to solve this in a more beautiful way? Am I missing
something here?

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


Re: A Twisted Design Decision

2009-01-27 Thread koranthala
On Jan 27, 6:57 pm, Jean-Paul Calderone  wrote:
> On Tue, 27 Jan 2009 05:46:25 -0800 (PST), koranthala  
> wrote:
> >Twisted, being twisted in its behavior is causing quite a lot of
> >confusion in design decisions.
>
> I'm not sure I agree with your premise. ;)
>
>
>
> >I will put forward a comparison of reactor and non-reactor patterns.
> >The code is not exact - whatever is shown is the gist of it.
>
> >For example, a message handler - in a usual scenario:
> >class messageHandler:
> >   def run():
> >         msg = self.get_next_msg()
> >         if not msg.send():
> >             self.handle_failure()
>
> >To handle parallel execution, we will have to use threads, but the
> >code flow is similar.
>
> >How do we do the same in a reactor pattern (Twisted)?
> >msg.send will cause a deferred to be raised - the failure, if it
> >happens will happen much later.
> >i.e. other than sending messageHandler object in msg.send(), I cannot
> >see any mechanism of running handle_failure.
>
> >In Twisted:
> >class messageHandler:
> >   def run():
> >         msg = self.get_next_msg()
> >         msg.send(self):
>
> >class msgClass:
> >    def send(o):
> >        d = deferred.addCallBack(success_handler, o).addErrBack
> >(failure_handler, o)
>
> >    def failure_handler(o):
> >        o.handle_failure()
>
> This doesn't look like a correct or faithful translation of the original.
> Here are two possibilities.  First:
>
>     class messageHandler:
>         def run():
>             msg = self.get_next_msg()
>             d = msg.send()
>             def cbSendFailed(result):
>                 if not result:
>                     self.handle_failure()
>             d.addErrback(cbSendFailed)
>             return d
>
> Next:
>
>     class messageHandler:
>         @inlineCallbacks
>         def run():
>             msg = self.get_next_msg()
>             if not (yield msg.send()):
>                 self.handle_failure()
>
> These are both just straight translations from your version so as to
> be able to handle a Deferred from `msg.send´.
>
> >Basically, what I find is that a lot of functional encapsulation is
> >now lost by following reactor pattern. handle_failure is
> >messageHandlers code and makes for pretty viewing if called from
> >inside messageHandler itself. But, due to the twisted nature of
> >reactor pattern, the msg Class - who is functionally a lower class to
> >messageHandler invoking messageHandler's code.
>
> You don't need to lose anything.  I don't know what your motivation was
> for re-arranging the code when you wrote the Twisted version, but it doesn't
> appear to have been necessary.
>
> >Is there a way to solve this in a more beautiful way? Am I missing
> >something here?
>
> Hope this helps,
>
> Jean-Paul

Thank you Jean-Paul.
My code is more complex than what I have mentioned. When I mentioned
msg.send, the msg object actually gets the data from DB etc to send.
And there are many other items being done.
I will try to see whether I can change the code to incorporate what
you mentioned.

I rewrote most of my code after learning just raw deferreds - I had
planned to study inlineCallbacks - but then it slipped my mind  - now
it has come to bit me. :-(
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Twisted Design Decision

2009-01-28 Thread koranthala
On Jan 27, 9:27 pm, koranthala  wrote:
> On Jan 27, 6:57 pm, Jean-Paul Calderone  wrote:
>
>
>
> > On Tue, 27 Jan 2009 05:46:25 -0800 (PST), koranthala  
> > wrote:
> > >Twisted, being twisted in its behavior is causing quite a lot of
> > >confusion in design decisions.
>
> > I'm not sure I agree with your premise. ;)
>
> > >I will put forward a comparison of reactor and non-reactor patterns.
> > >The code is not exact - whatever is shown is the gist of it.
>
> > >For example, a message handler - in a usual scenario:
> > >class messageHandler:
> > >   def run():
> > >         msg = self.get_next_msg()
> > >         if not msg.send():
> > >             self.handle_failure()
>
> > >To handle parallel execution, we will have to use threads, but the
> > >code flow is similar.
>
> > >How do we do the same in a reactor pattern (Twisted)?
> > >msg.send will cause a deferred to be raised - the failure, if it
> > >happens will happen much later.
> > >i.e. other than sending messageHandler object in msg.send(), I cannot
> > >see any mechanism of running handle_failure.
>
> > >In Twisted:
> > >class messageHandler:
> > >   def run():
> > >         msg = self.get_next_msg()
> > >         msg.send(self):
>
> > >class msgClass:
> > >    def send(o):
> > >        d = deferred.addCallBack(success_handler, o).addErrBack
> > >(failure_handler, o)
>
> > >    def failure_handler(o):
> > >        o.handle_failure()
>
> > This doesn't look like a correct or faithful translation of the original.
> > Here are two possibilities.  First:
>
> >     class messageHandler:
> >         def run():
> >             msg = self.get_next_msg()
> >             d = msg.send()
> >             def cbSendFailed(result):
> >                 if not result:
> >                     self.handle_failure()
> >             d.addErrback(cbSendFailed)
> >             return d
>
> > Next:
>
> >     class messageHandler:
> >         @inlineCallbacks
> >         def run():
> >             msg = self.get_next_msg()
> >             if not (yield msg.send()):
> >                 self.handle_failure()
>
> > These are both just straight translations from your version so as to
> > be able to handle a Deferred from `msg.send´.
>
> > >Basically, what I find is that a lot of functional encapsulation is
> > >now lost by following reactor pattern. handle_failure is
> > >messageHandlers code and makes for pretty viewing if called from
> > >inside messageHandler itself. But, due to the twisted nature of
> > >reactor pattern, the msg Class - who is functionally a lower class to
> > >messageHandler invoking messageHandler's code.
>
> > You don't need to lose anything.  I don't know what your motivation was
> > for re-arranging the code when you wrote the Twisted version, but it doesn't
> > appear to have been necessary.
>
> > >Is there a way to solve this in a more beautiful way? Am I missing
> > >something here?
>
> > Hope this helps,
>
> > Jean-Paul
>
> Thank you Jean-Paul.
> My code is more complex than what I have mentioned. When I mentioned
> msg.send, the msg object actually gets the data from DB etc to send.
> And there are many other items being done.
> I will try to see whether I can change the code to incorporate what
> you mentioned.
>
> I rewrote most of my code after learning just raw deferreds - I had
> planned to study inlineCallbacks - but then it slipped my mind  - now
> it has come to bit me. :-(

Hi,
  I tried to update the code as per the suggestion, but to no avail.
  My system uses Python2.4.3 (cannot move to 2.5) - so I tried to
rewrite with deferredGenerators - since I thought inlineCallbacks are
similar to deferredGenerators.

  But I cannot seem to rewrite it in a format where the functional
encapsulation is not broken.
  i.e. as I mentioned in the first example - I have to pass SELF to
child objects for them to modify it.

  The code was not exactly as I mentioned. I will try to explain more
below:
  The code before Twisted was incorporated.

  class MessageHandler:
def send_message():
  if self.execute():  #Lots of checks going inside this
for i in self.msgs: #Sends many messages at the same time
   if msg.send():
 self.success += 1
   else
 self.failure += 1

  class Message:
def send():
  self.update_data() #The data to be sent is updated here
  return self.protocol.

Re: self-aware list of objects able to sense constituent member alterations?

2009-01-28 Thread koranthala
On Jan 28, 2:16 am, Reckoner  wrote:
> I'm not sure this is possible, but I would like to have
> a list of  objects
>
> A=[a,b,c,d,...,z]
>
> where,  in the midst of a lot of processing I might do something like,
>
> A[0].do_something_which_changes_the_properties()
>
> which alter the properties of the object 'a'.
>
> The trick is that I would like A to be mysteriously aware that
> something about the  object 'a' has changed so that when I revisit A,
> I will know that the other items in the list need to be refreshed to
> reflect the changes in A as a result of changing 'a'.
>
> Even better would be to automatically percolate the subsequent changes
> that resulted from altering 'a' for the rest of the items in the list.
> Naturally, all of these items are related in some parent-child
> fashion.
>
> that might be a lot to ask, however.
>
> Any advice appreciated.

I think Python Cookbook has a recipe which deals with this.
- 6.12 Checking an Instance for Any State Change.
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Twisted Design Decision

2009-01-28 Thread koranthala
On Jan 28, 7:10 pm, Jean-Paul Calderone  wrote:
> On Wed, 28 Jan 2009 02:02:57 -0800 (PST), koranthala  
> wrote:
> >On Jan 27, 9:27 pm, koranthala  wrote:
> >> On Jan 27, 6:57 pm, Jean-Paul Calderone  wrote:
> > [snip]
>
> >> Thank you Jean-Paul.
> >> My code is more complex than what I have mentioned. When I mentioned
> >> msg.send, the msg object actually gets the data from DB etc to send.
> >> And there are many other items being done.
> >> I will try to see whether I can change the code to incorporate what
> >> you mentioned.
>
> >> I rewrote most of my code after learning just raw deferreds - I had
> >> planned to study inlineCallbacks - but then it slipped my mind  - now
> >> it has come to bit me. :-(
>
> >Hi,
> >  I tried to update the code as per the suggestion, but to no avail.
> >  My system uses Python2.4.3 (cannot move to 2.5) - so I tried to
> >rewrite with deferredGenerators - since I thought inlineCallbacks are
> >similar to deferredGenerators.
>
> >  But I cannot seem to rewrite it in a format where the functional
> >encapsulation is not broken.
> >  i.e. as I mentioned in the first example - I have to pass SELF to
> >child objects for them to modify it.
>
> Why?  You don't do this in the original version of your code.  Why do
> it after switching to Twisted (particularly since you seem to want *not*
> to)?
>
> Jean-Paul

Without that, I am unable to increment success and failure counters
which are part of the message handler object.
In the original version, if send fails the return value of
protocol.send is propogated back to msg.send and to msg handler.send.
But in twisted, it is not so. So, I have to pass in SELF through to
increment success and failure counter.
Is it possible otherwise in twisted?
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Twisted Design Decision

2009-01-28 Thread koranthala
On Jan 28, 8:36 pm, Jean-Paul Calderone  wrote:
> On Wed, 28 Jan 2009 06:30:32 -0800 (PST), koranthala  
> wrote:
> >On Jan 28, 7:10 pm, Jean-Paul Calderone  wrote:
> >> On Wed, 28 Jan 2009 02:02:57 -0800 (PST), koranthala 
> >>  wrote:
> >> >On Jan 27, 9:27 pm, koranthala  wrote:
> >> >> On Jan 27, 6:57 pm, Jean-Paul Calderone  wrote:
> >> > [snip]
>
> >> >> Thank you Jean-Paul.
> >> >> My code is more complex than what I have mentioned. When I mentioned
> >> >> msg.send, the msg object actually gets the data from DB etc to send.
> >> >> And there are many other items being done.
> >> >> I will try to see whether I can change the code to incorporate what
> >> >> you mentioned.
>
> >> >> I rewrote most of my code after learning just raw deferreds - I had
> >> >> planned to study inlineCallbacks - but then it slipped my mind  - now
> >> >> it has come to bit me. :-(
>
> >> >Hi,
> >> >  I tried to update the code as per the suggestion, but to no avail.
> >> >  My system uses Python2.4.3 (cannot move to 2.5) - so I tried to
> >> >rewrite with deferredGenerators - since I thought inlineCallbacks are
> >> >similar to deferredGenerators.
>
> >> >  But I cannot seem to rewrite it in a format where the functional
> >> >encapsulation is not broken.
> >> >  i.e. as I mentioned in the first example - I have to pass SELF to
> >> >child objects for them to modify it.
>
> >> Why?  You don't do this in the original version of your code.  Why do
> >> it after switching to Twisted (particularly since you seem to want *not*
> >> to)?
>
> >> Jean-Paul
>
> >Without that, I am unable to increment success and failure counters
> >which are part of the message handler object.
> >In the original version, if send fails the return value of
> >protocol.send is propogated back to msg.send and to msg handler.send.
> >But in twisted, it is not so. So, I have to pass in SELF through to
> >increment success and failure counter.
> >Is it possible otherwise in twisted?
>
> Why isn't the return value of protocol.send propagated back to msg.send?
> It sounds like it should be.
>
> Jean-Paul

Thank you very much again Jean-Paul for helping me out.
I am unable to understand how I will be able to propogate the return
value of protocol.send to msg.send.
Maybe I am being foolish - but my understanding is as follows.

In a non-reactor pattern scenario:
msg_handler.send_message calls msg.send which inturn calls
protocol.send.
So, the reply to protocol.send actually goes up the stack till
msg_handler.send_message wherein I can increment/decrement success/
failure counter.

In reactor pattern:
msg_handler.send_message calls msg.send which call protocol.send which
causes a deferred to be created.
Now, when the deferred finishes its work, reactor calls the callback
associated - but the original context (stack etc) is lost.
Now, the only mechanism of interaction is via the parameters passed in
the callback.
This means that msg_handler has to pass in its object to msg.send
which inturn has to send either msg_handler or self to protocol.send
so that it is stored in the parameter to the callback.
When callback is hit, I use this parameter to call methods in each
object.

This is what I was trying to say in my first mail that - Twisted,
being twisted in its behavior is causing quite a lot of
confusion in design decisions - because now I have to break functional
encapsulation - by asking lower layer objects to handler upper layer
objects behaviors.

As I said earlier, maybe I am being completely stupid -  there might
be a very easy and obvious solution. But I cannot seem to get it at
all.

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


Re: A Twisted Design Decision

2009-01-28 Thread koranthala
> You can still interact via return values.  You should be thinking about
> a Deferred in the same way as you think about a function which returns
> a result synchronously.  The Deferred represents the result, even though
> it isn't the result itself (since the result doesn't exist yet).  Anything
> you would have done by calling a function and then using its return value
> you can do by calling a function and then using the Deferred it returns.
>

Oh! This makes it very clear.

Thank you very much Jean-Paul and Chris Mellon.
My view of deferred was very different from this. That was the reason
behind these persistent questions.
My view of deferred was that of it being a mechanism to provide
asynchronous behavior and nothing more.

The twisted documentation explicitly mentions this - 'Twisted’s
Deferred abstraction, which symbolises a ’promised’ result and which
can pass an eventual result to handler functions.' But with my earlier
view I understood it completely differently.

Thank you once more, Jean-Paul & Chris for taking your valuable time
out to help me out.
--
http://mail.python.org/mailman/listinfo/python-list


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-28 Thread koranthala
On Jan 28, 5:42 pm, koranthala  wrote:
> On Jan 28, 2:16 am, Reckoner  wrote:
>
>
>
> > I'm not sure this is possible, but I would like to have
> > a list of  objects
>
> > A=[a,b,c,d,...,z]
>
> > where,  in the midst of a lot of processing I might do something like,
>
> > A[0].do_something_which_changes_the_properties()
>
> > which alter the properties of the object 'a'.
>
> > The trick is that I would like A to be mysteriously aware that
> > something about the  object 'a' has changed so that when I revisit A,
> > I will know that the other items in the list need to be refreshed to
> > reflect the changes in A as a result of changing 'a'.
>
> > Even better would be to automatically percolate the subsequent changes
> > that resulted from altering 'a' for the rest of the items in the list.
> > Naturally, all of these items are related in some parent-child
> > fashion.
>
> > that might be a lot to ask, however.
>
> > Any advice appreciated.
>
> I think Python Cookbook has a recipe which deals with this.
> - 6.12 Checking an Instance for Any State Change.

Were you able to get this? If not, let me know. I will try to type it
in here - (it is a big recipe, so not doing it now)
--
http://mail.python.org/mailman/listinfo/python-list


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-28 Thread koranthala
On Jan 28, 10:39 pm, Reckoner  wrote:
> On Jan 28, 9:16 am, koranthala  wrote:
>
>
>
> > On Jan 28, 5:42 pm, koranthala  wrote:
>
> > > On Jan 28, 2:16 am, Reckoner  wrote:
>
> > > > I'm not sure this is possible, but I would like to have
> > > > a list of  objects
>
> > > > A=[a,b,c,d,...,z]
>
> > > > where,  in the midst of a lot of processing I might do something like,
>
> > > > A[0].do_something_which_changes_the_properties()
>
> > > > which alter the properties of the object 'a'.
>
> > > > The trick is that I would like A to be mysteriously aware that
> > > > something about the  object 'a' has changed so that when I revisit A,
> > > > I will know that the other items in the list need to be refreshed to
> > > > reflect the changes in A as a result of changing 'a'.
>
> > > > Even better would be to automatically percolate the subsequent changes
> > > > that resulted from altering 'a' for the rest of the items in the list.
> > > > Naturally, all of these items are related in some parent-child
> > > > fashion.
>
> > > > that might be a lot to ask, however.
>
> > > > Any advice appreciated.
>
> > > I think Python Cookbook has a recipe which deals with this.
> > > - 6.12 Checking an Instance for Any State Change.
>
> > Were you able to get this? If not, let me know. I will try to type it
> > in here - (it is a big recipe, so not doing it now)
>
> Actually, I have the python cookbook, but cannot find the recipe you
> mention. maybe I have an older version?
>
> thanks.

Mine is 2nd Edition.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing subservient threads

2009-02-20 Thread koranthala
On Feb 20, 9:47 pm, jimzat  wrote:
> I am trying to create an app which will have a main window from which
> the user will launch other (children) windows.
>
> When I launch the child window I start a new thread which periodically
> polls another device and updates the child window accordingly.  When I
> dismiss the child window the "polling" thread stays alive and then
> crashes with an exception when trying to write to the now defunct
> child window.
>
> How can I handle this?  I want to either 1) have the destructor for
> the child window kill the spawned thread or 2) catch the exception
> within the "polling" thread and see that the child window is gone and
> then commit suicide.
>
> I am an experienced embedded C programmer but have VERY little
> experience with GUI programming and no experience in the Micro$oft
> programming world.

thread.setDaemon(True)
Makes it a daemon thread which means that interpreter will not stay
alive if only that thread is alive.
--
http://mail.python.org/mailman/listinfo/python-list


Videocapture in python

2008-12-31 Thread koranthala
I face issues in videocapture in python. Cant find anyplace where we
can raise bug reports, so mentioning here. Also help required if
somebody has solved it earlier.

On using videocapture (python 2.4), I am facing the following issues
while creating a video sort of application.
-> Pull out the usb cable : Videocapture gets the data stored
initially in the buffer and returns always. The images are not updated
- but also there is no error returned.
i.e. there is no information to the viewer that it is not working
anymore. Especially because since the timestamp is updated everytime
(it is done inside videocapture.py - wherein current time is
overwritten on the received image), it gives a feeling that video is
running.

Currently I have done a workaround in that every 2 captures, i setup
the camera again - but it takes too much time. Anyone has any
suggestions on solving this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Videocapture in python

2009-01-01 Thread koranthala
On Jan 1, 1:58 pm, "alex goretoy"  wrote:
> Can you post your code or a code segment? I would be interested in seeing
> how this works.
>
>
>
> On Thu, Jan 1, 2009 at 3:29 AM,  wrote:
> > I face issues in videocapture in python. Cant find anyplace where we
> > can raise bug reports, so mentioning here. Also help required if
> > somebody has solved it earlier.
>
> > On using videocapture (python 2.4), I am facing the following issues
> > while creating a video sort of application.
> > -> Pull out the usb cable : Videocapture gets the data stored
> > initially in the buffer and returns always. The images are not updated
> > - but also there is no error returned.
> > i.e. there is no information to the viewer that it is not working
> > anymore. Especially because since the timestamp is updated everytime
> > (it is done inside videocapture.py - wherein current time is
> > overwritten on the received image), it gives a feeling that video is
> > running.
>
> > Currently I have done a workaround in that every 2 captures, i setup
> > the camera again - but it takes too much time. Anyone has any
> > suggestions on solving this?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я

Since the code uses a lot of other variables - due to being a part of
a larger project, I will try to provide pseudocode.
At initialization:
def setup_cam():
  global cam, i
  cam = Device (devnum = 0)
  i = 0

def take_photo(obj):
  i += 1
  if i >2:
setup_cam()
  obj.img = cam.getImage(timestamp=3)

I actually would like to have the code as
try:
  obj.img = cam.getImage(timestamp=3)
except CamException:
  setup_cam()

But, since no exception is provided, I have to resort to the kludge
shown.
Please let me know if you need any more information.

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


initialization in python

2009-01-01 Thread koranthala
How does an average product handle initialization in python?
I am facing lot of issues in handling initialization, especially if I
import specific variables, due to the variables not getting updated.

For example - taking a sqlalchemy based product:
Module database:
^^^
Session = None

def init(dbname):
   engine = create_engine('sqlite:///%s' %dbname)
   ...
   global Session
   Session = sessionmaker(bind=engine)

In entry module to the application (APPENTRY):
^^^
import A, B, C, D  < Please note, very important


database.init('testdb.db')

Now in user module A:
^^
from database import Session
print Session
--->This will print None, because at APPENTRY, during importing A
itself, Session is stored.
I have to call database.Session to get the values.

Why is the variable not getting updated? Can anyone help me out?
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialization in python

2009-01-01 Thread koranthala
On Jan 1, 6:54 pm, John Machin  wrote:
> On Jan 1, 11:44 pm, [email protected] wrote:
>
>
>
> > How does an average product handle initialization in python?
> > I am facing lot of issues in handling initialization, especially if I
> > import specific variables, due to the variables not getting updated.
>
> > For example - taking a sqlalchemy based product:
> > Module database:
> > ^^^
> > Session = None
>
> > def init(dbname):
> >    engine = create_engine('sqlite:///%s' %dbname)
> >    ...
> >    global Session
> >    Session = sessionmaker(bind=engine)
>
> > In entry module to the application (APPENTRY):
> > ^^^
> > import A, B, C, D  < Please note, very important
> > 
> > 
> > database.init('testdb.db')
>
> > Now in user module A:
> > ^^
> > from database import Session
> > print Session
> > --->This will print None, because at APPENTRY, during importing A
> > itself, Session is stored.
>
> This is happening when you import A, which happens *before* you call
> database.init(). database.init binds the name database.Session to a
> new value. The name A.Session has been bound earlier to the value
> None.
>
> > I have to call database.Session to get the values.
>
> I don't understand that sentence. Is database.Session callable (i.e.
> is a function or class)? What valueS (plural)?
>
> > Why is the variable not getting updated?
>
> Firstly, it's not a "variable" in the sense of a named slice of memory
> to which various values can be assigned.
>
> Secondly, it could be updated only if the "from database import
> Session" operated like it was creating an alias e.g.
>     A.Session isanaliasof database.Session
> like a C macro
>     #define A_Session database_Session
> but it isn't; its effect is that of a fancy "assignment", more or less
> like:
>     import database
>     Session = database.Session
>     del database
>
> In any case, mucking about with module globals like you are trying to
> do is not a good idea. As you have seen, it introduces dependencies
> like you need to import A after the database is initiated. As soon as
> you need more than one session at a time, or the single session needs
> to be closed and restarted, it really falls apart. Try passing your
> session around as a function arg, or as an attribute of an object that
> contains current state information.
>
> HTH,
> John

> This is happening when you import A, which happens *before* you call
> database.init(). database.init binds the name database.Session to a
> new value. The name A.Session has been bound earlier to the value
> None.

I guessed as much. But, I was under the impression that if the
original value is modified, the variables value also will change.

> I don't understand that sentence. Is database.Session callable (i.e.
> is a function or class)? What valueS (plural)?

Session() here is a session manager in SQLAlchemy. database.Session()
creates a new session.

> import database
> Session = database.Session
> del database

Thank you. This answers my query.

> In any case, mucking about with module globals like you are trying to
> do is not a good idea. As you have seen, it introduces dependencies

I avoid global variables as much as possible. But SQLAlchemy tutorial
recommends this method of assignment. So, I was using this. Anyways, I
now use database.Session always, and these dependencies are no longer
there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Videocapture in python

2009-01-01 Thread koranthala
On Jan 1, 7:26 pm, Marc 'BlackJack' Rintsch  wrote:
> On Thu, 01 Jan 2009 04:28:21 -0800, koranthala wrote:
> > Please let me know if you need any more information.
>
> Where does `videocapture.py` coming from?  It's not part of the standard
> library.  And which operating system are we talking about?
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Hi Marc,
   It is not part of standard library. Sorry for me being very brief
earlier.
   It is taken from http://videocapture.sourceforge.net/, - a very
good tool for webcam capture in Win32.
Hi David,
   I am in Windows. And there is a possibility that I might be using
device 0 or 1. So, I am using the excellent VideoCapture tool created
by Markus Gritsch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialization in python

2009-01-01 Thread koranthala
On Jan 1, 11:14 pm, Terry Reedy  wrote:
> [email protected] wrote:
> >>> Module database:
> >>> ^^^
> >>> Session = None
>
> 'Initializing' names is not necessary.  Delete this.  Without it, your
> error would be more obvious.
>
> >>> def init(dbname):
> >>>    engine = create_engine('sqlite:///%s' %dbname)
> >>>    ...
> >>>    global Session
> >>>    Session = sessionmaker(bind=engine)
>
> This **rebinds* the module name 'Session' to a new object, making the
> initial bindin irrelevant and misleading.
>
> [snip]
>
>
>
> > I guessed as much. But, I was under the impression that if the
> > original value is modified, the variables value also will change.
>
> Python has names and slots bound to objects.  Some objects are mutable
> and some not.  None is not mutable.  You replaced it.
>
> If you had done something like
>
> Session = sessionmaker()
>
> def init(dbname):
>      Session.engine = create_engine('sqlite:///%s' %dbname)
>      ...
>
> then you would have *modified* the original object (value) bound to
> 'Session' and would have seen the behavior you expected.
>
> Terry Jan Reedy

I did not think about it. I was using database.Session till now.
I have now modified the code.
Thank you very much, Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list


Python logging question

2009-01-02 Thread koranthala
Hi,
I was reading through Python Logging tutorial, and I found one
scenario which I couldnt properly understand.
The tutorial (http://docs.python.org/library/logging.html)
mentions at first that -- "Multiple calls to getLogger() with the same
name will return a reference to the same logger object".

In an example for Python Logging Adapter, the tutorial then
mentions that -
"While it might be tempting to create Logger instances on a per-
connection basis, this is not a good idea because these instances are
not garbage collected".

I am confused reading both together. I will try to explain my
confusion with an example:

basicLogger = logging.getLogger("basic")

Class A():
  def __init__(self):
 self.logger = logging.getLogger("basic.class_a")

   Now, I make say 10 instances of A and then delete one by one.

My understanding was that since the same name is used, a single
basic.class_a logger object is created inside the logging system, and
any calls to getLogger("basic.class_a") would return the same object
everytime.

So, my confusion is based on the second tutorial item I mentioned -
why is it not a good idea to create logger instances on a per-instance
basis? We are not creating new instances, right? And, if I create an
instance of A, it will be garbage collected later, right?

Could somebody help me out?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python logging question

2009-01-02 Thread koranthala
On Jan 2, 6:21 pm, Vinay Sajip  wrote:
> On Jan 2, 11:31 am, [email protected] wrote:
>
> >     I am confused reading both together. I will try to explain my
> > confusion with an example:
>
> > basicLogger =logging.getLogger("basic")
>
> > Class A():
> >   def __init__(self):
> >      self.logger =logging.getLogger("basic.class_a")
>
> >    Now, I make say 10 instances of A and then delete one by one.
>
> > My understanding was that since the same name is used, a single
> > basic.class_a logger object is created inside theloggingsystem, and
> > any calls to getLogger("basic.class_a") would return the same object
> > everytime.
>
> That is correct. The logger instances stay around for the life of the
> process, and are not garbage collected.
>
> > So, my confusion is based on the second tutorial item I mentioned -
> > why is it not a good idea to create logger instances on a per-instance
> > basis? We are not creating new instances, right? And, if I create an
> > instance of A, it will be garbage collected later, right?
>
> It's not a problem to create loggers per *class*, as in your example.
> It can be a bad idea to create different logger per class *instances*.
> The second example in the docs talks about creating loggers on a per-
> connection basis in a networked app. This is not per connection class,
> mind you, but per connection instance. You would typically have only a
> few dozen classes, but you might have hundreds of thousands of
> connection instances created in a long-lived server app. If you
> created a unique logger for each connection, for example based on the
> time the connection was instantiated - e.g. with name "connection.
> 20090102123456543", this would create hundreds of thousands of unique
> logger instances and have a potentially adverse impact on process
> memory. That's when you use LoggerAdapters.
>
> I hope that's clearer.
>
> Regards,
>
> Vinay Sajip

Thank you very much Vinay.
I was confused by the way it was mentioned in the tutorial.
Again, Thank you
Regards
Koranthala
--
http://mail.python.org/mailman/listinfo/python-list


Doubt on creating threads

2009-01-03 Thread koranthala
I was going through Python posts and this post caught my attention
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f99326a4e5d394e/14cd708956bd1c1a#14cd708956bd1c1a


 You have missed an important point. A well designed application does
 neither create so many threads nor processes. The creation of a
thread
 or forking of a process is an expensive operation. You should use a
pool
 of threads or processes.


I am creating an application and it creates ~1-2 threads every second
and kill it within 10 seconds. After reading this I am worried. Is
creating a thread a very costly operation? I cannot use a pool of
threads because I am using an external application (twisted) to create
the threads (deferToThread).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubt on creating threads

2009-01-03 Thread koranthala
On Jan 4, 4:59 am, Bryan Olson  wrote:
> [email protected] wrote:
> > I am creating an application and it creates ~1-2 threads every second
> > and kill it within 10 seconds. After reading this I am worried. Is
> > creating a thread a very costly operation?
>
> Compared to a procedure call it's expensive, but a couple threads per
> second is insignificant. My out-dated Pentium 4 desktop can create and
> destroy a few thousand threads per second under WinXP; more under recent
> Linux.
>
> --
> --Bryan

Thank you very much.
I was worried about this a lot.
--
http://mail.python.org/mailman/listinfo/python-list


Python return values

2009-01-05 Thread koranthala
I have a newbie doubt about Python return values.

In (say) C/C++, if we try to return a value which is stored inside the
procedure stack, we will get an error when trying to access it outside
of that procedure.
For example:
function foo():
   dcl y int
   dcl x pointer to int pointing to y
   return x


function bar():
   x = foo()
   ...
   use x

This will error out since the memory has be taken back.

Now, in Python, we do it everytime, because all variables are
references, and even returns just copies the references.
function pyfoo():
  return 786

function pyfoo1():
  x = xclass()
  return x

function pybar():
  x = pyfoo()
  y = pyfoo1()
  ...
  use x, y

Why doesnt it error out?
--
http://mail.python.org/mailman/listinfo/python-list


Encrypted Logging in python

2009-01-09 Thread koranthala
   I was wondering if there is a mechanism to encrypt logging
automatically in python.
   The issue is as follows:
(a) An application (after py2exe) will go as executable and there
is no need for the user to know that it is written in python. If an
exception occurs and it is logged, then the user can understand it is
written in python.
(b) A security threat. If an exception occurs, the code is seen by
the user - and possibly be misused.

   Base64 encoding somewhat helps - which is supported by logging
module - but even that is not very secure. If there can be an option -
wherein we send in the password and the logging is encrypted - it
might be better.
   I would have loved to provide the code, but I am completely tied up
at the moment and wont be able to help for another month.

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


Re: Encrypted Logging in python

2009-01-09 Thread koranthala
On Jan 9, 3:16 pm, Steven D'Aprano  wrote:
> On Fri, 09 Jan 2009 00:21:09 -0800, koranthala wrote:
> > I was wondering if there is a mechanism to encrypt logging automatically
> > in python.
> >    The issue is as follows:
> >     (a) An application (after py2exe) will go as executable and there
> > is no need for the user to know that it is written in python. If an
> > exception occurs and it is logged, then the user can understand it is
> > written in python.
> >     (b) A security threat. If an exception occurs, the code is seen by
> > the user - and possibly be misused.
>
> Security by obscurity is not security. If your application isn't secure
> against people who know what language is written in, then it isn't secure.
>
> --
> Steven

I understand that completely.
My point is that even though I can try to make the application
completely secure - I can never be sure of that. Especially if your
company is a very small one - and might not be able to have the best
programmers around. So, another layer of security - even security
through obscurity - can give that bit extra time in which the bugs in
the system can be ironed out.

Also, what I am asking is a generic option in logging - which can help
the adoption of the logging framework in even closed source systems.
It is not just about security - just that a closed source company
might be much more comfortable in using the system if crypt is there.
--
http://mail.python.org/mailman/listinfo/python-list


Server programming

2009-02-23 Thread koranthala
Hi,
  Is server programming in Python procedure oriented or object
oriented?
  I have this question because lately I am asked to make a medium
complex web program (extremely database oriented) using Django. When I
used to do application programs earlier (in Python itself), the whole
thing being object oriented came out easily in programming. So, I was
able to use different patterns etc for programming and the whole thing
was - quite fun to design and create.
  But when I program in Django, since I just have to work on user
responses - everything else being taken care of by Django - only, the
complete coding has become procedure oriented. It is not kludgy or
anything, but it doesnt have the nice feeling that we get when we code
a proper object oriented program.
  Is my coding in error here? This is infact my first web program,
so it might be the reason. What does other people find? Does web
server programming using web frameworks (Django, TurboGears etc) make
it procedure oriented? If I am in the wrong, it might be due to a
wrong design or mindset, and I would like to change it.


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


Re: file locking...

2009-03-01 Thread koranthala
On Mar 1, 2:28 pm, Nigel Rantor  wrote:
> bruce wrote:
> > Hi.
>
> > Got a bit of a question/issue that I'm trying to resolve. I'm asking
> > this of a few groups so bear with me.
>
> > I'm considering a situation where I have multiple processes running,
> > and each process is going to access a number of files in a dir. Each
> > process accesses a unique group of files, and then writes the group
> > of files to another dir. I can easily handle this by using a form of
> > locking, where I have the processes lock/read a file and only access
> > the group of files in the dir based on the  open/free status of the
> > lockfile.
>
> > However, the issue with the approach is that it's somewhat
> > synchronous. I'm looking for something that might be more
> > asynchronous/parallel, in that I'd like to have multiple processes
> > each access a unique group of files from the given dir as fast as
> > possible.
>
> I don't see how this is synchronous if you have a lock per file. Perhaps
> you've missed something out of your description of your problem.
>
> > So.. Any thoughts/pointers/comments would be greatly appreciated. Any
> >  pointers to academic research, etc.. would be useful.
>
> I'm not sure you need academic papers here.
>
> One trivial solution to this problem is to have a single process
> determine the complete set of files that require processing then fork
> off children, each with a different set of files to process.
>
> The parent then just waits for them to finish and does any
> post-processing required.
>
> A more concrete problem statement may of course change the solution...
>
>    n

Using twisted might also be helpful.
Then you can avoid the problems associated with threading too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Server programming

2009-03-03 Thread koranthala
On Feb 24, 1:02 am, Bruno Desthuilliers
 wrote:
> koranthalaa écrit :
>
> > Hi,
> >       Is server programming in Python procedure oriented or object
> > oriented?
>
> It's how you want it to be.
>
> >       I have this question because lately I am asked to make a medium
> > complex web program (extremely database oriented) using Django. When I
> > used to do application programs earlier (in Python itself),  the whole
> > thing being object oriented came out easily in programming. So, I was
> > able to use different patterns etc for programming and the whole thing
> > was - quite fun to design and create.
> >       But when I program in Django, since I just have to work on user
> > responses - everything else being taken care of by Django - only, the
> > complete coding has become procedure oriented. It is not kludgy or
> > anything, but it doesnt have the nice feeling that we get when we code
> > a proper object oriented program.
>
> So you may want to learn to enjoy the nice feeling we get when we code a
> proper procedural program - or a proper functional one FWIW !-)
>
> There's nothing inherently wrong with procedural programming. Nor with a
> mix of procedural, OO and functional code - which is usually the case in
> Python. It's just a matter of using the right tool for the problem to
> solve.
>
> >       Is my coding in error here?
>
> Don't know - I don't have access to your code. But my experience with
> Django is that I tend to have quite a lot of code in models and
> templatetags, and much less in the views themselves. So I wouldn't say
> that "Django takes care of everything else". If you really ends up
> writing pages upon pages of repeting procedural code in your views and
> nothing in the other parts of the app, then yes, there might be
> something wrong - probably a case of AnemicDomainModel, and possibly a
> lack of knowledge of the whole framework. One of the reasons views are
> usually implemented as functions is that in most cases, you shouldn't
> have a need for more. FWIW, you sometimes don't even need to write a
> specific view - Django's GenericViews can handle quite a lot of cases
>
> Note also that Django doesn't _require_ that you use functions as view
> handlers - any callable object will do. But given how the HTTP protocol
> works and how Django is designed, there's more often than not just no
> *need* for a custom callable object.
>
> And finally, as Steve already mentioned, OO is first about objects, and
> that's what you're dealing with in your views - request objects, session
> objects, model objects etc...
>
> > This is infact my first web program,
> > so it might be the reason. What does other people find? Does web
> > server programming using web frameworks (Django, TurboGears etc) make
> > it procedure oriented?
>
> Not necessarily, no. Some frameworks requires your request handlers to
> be methods of classes FWIW, and nothing in Django prevents you from
> doing so if you want.
>
> > If I am in the wrong, it might be due to a
> > wrong design or mindset, and I would like to change it.

Hi Bruno,
   After reading your email, I tried reworking my code so that most of
my logic moves to Models.
   But, most probably because this is my first application
development, I am unable to do so.
   For example:
I have Models A,B, C, D . Now, there is not much model specific
code (preprocessing before updating code inside Models)in it. Rather
most of the code is of the format:
 data received and to be added to D. But for adding to D, check
whether it is already in C - if not add to C and B. etc...
   Now, I tried putting this code inside Model D,but it does not seem
to belong there - since it modifies other Models.

   Is keeping such code inside views against Django's/Application-
Developments philosophy? In that case, where will this go?

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


Re: Server programming

2009-03-03 Thread koranthala
On Mar 3, 8:09 pm, Bruno Desthuilliers  wrote:
> koranthala a écrit :
> (snip)
>
> > Hi Bruno,
> >    After reading your email, I tried reworking my code so that most of
> > my logic moves to Models.
> >    But, most probably because this is my first application
> > development, I am unable to do so.
> >    For example:
> >     I have Models A,B, C, D . Now, there is not much model specific
> > code (preprocessing before updating code inside Models)in it. Rather
> > most of the code is of the format:
> >      data received and to be added to D. But for adding to D, check
> > whether it is already in C - if not add to C and B. etc...
>
> And you don't find it "model specific" ? Man, this is business rules,
> and as such belongs to the models part, not to views. You surely want to
> make sure these rules always apply, don't you ?
>
> >    Now, I tried putting this code inside Model D,but it does not seem
> > to belong there - since it modifies other Models.
>
> And ? Who said a Model (or ModelManager) shouldn't touch other models ?
>
> >    Is keeping such code inside views against Django's/Application-
> > Developments philosophy?
>
> FWIW, I see this antipattern (AnemicDomainModel) way too often in django
> apps. This doesn't make it less of an antipattern.
>
> > In that case, where will this go?
>
> It's impossible to say exactly where in the models module without a
> sufficiant knowledge of the domain, rules etc. Sorry, but my crystal
> ball is out for repair.

Thank you, Bruce.
Sorry for the rather naive questions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6.1 - simple division

2009-03-08 Thread koranthala
On Mar 8, 7:22 pm, [email protected] wrote:
> On Mar 8, 2:16 pm, [email protected] wrote:
>
> > >>> 4 / 5.0
>
> > 0.84>>> 0.8 * 5
>
> > 4.0
>
> > python 2.6.1 on mac. What the hell is going on here?
>
> Pure curiosity prompted me to try the following:>>> 40 / 5.0
>
> 8.0
>
> Strange...

Please see http://docs.python.org/library/decimal.html for explanation
of why this happens.
To get the proper values, try
>>> Decimal(4)/Decimal("5.0")
Decimal("0.8")
--
http://mail.python.org/mailman/listinfo/python-list


Implementing chain of responsibility

2009-03-08 Thread koranthala
Hi,
I want to implement chain of responsibility pattern in Python (for
a Django project)
The problem that I see is a rather odd one - how to link the
subclasses with the super class.

Ex: Suppose the two child classes are as given below (A1, A2 child
classes of A)
class A:
   ...

class A1(A):
   ...

class A2(A):
   ...

Now, I want to call A.method(x) and I want A1 and A2 to act on x.
The ways I could think of till now are
1. have a registry in A. A1 and A2 objects register to A's registry.
Then loop through the registry.
2. loop through A.__subclasses__ to invoke each subclass.

I am leaning towards option 1.

The problem is that A1 and A2 are in different modules from A. So, how
can I make A aware that A1 and A2 are there?
i.e.
The module structure is MA (contains class A), MA1 (contains class A1)
MA2 (contains class A2).
Where do I do import MA1 and MA2 etc so that the register methods of
MA1 and MA2 are hit?
Now, from the code (when I receive a HTTP request), I will be calling
MA.A.method(x) only. So there is no need of importing MA1 and MA2.

Is __init__.py used for this purpose - i.e. just import all the
modules inside __init__.py so that the code is it in each?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implementing chain of responsibility

2009-03-09 Thread koranthala
On Mar 9, 12:16 pm, Chris Rebert  wrote:
> On Sun, Mar 8, 2009 at 11:53 PM, koranthala  wrote:
> > Hi,
> >    I want to implement chain of responsibility pattern in Python (for
> > a Django project)
> >    The problem that I see is a rather odd one - how to link the
> > subclasses with the super class.
>
> Grabbing out my copy of Head First Design Patterns and looking up this
> pattern, it sounds like you're going about this the wrong way. From
> what I can grok, Chain-of-Responsibility looks like this:
>
> class SomeHandler(object)
>     def __init__(self, successor=None):
>         self.successor = successor
>
>     def theMethod(self, theRequest):
>         result = try_and_handle(theRequest)
>         if did_not_handle(theRequest) and self.successor is not None:
>             return successor.theMethod(theRequest)
>         else:
>             return result
>
> #imagine some other handler classes
> #setup:
> masterHandler = SomeHandler(OtherHandler(ThirdHandler()))
> #usage:
> result = masterHandler.theMethod(aRequest)
>
> So the *classes* don't ever know anything about each other; you pass a
> handler class an instance of its successor handler at
> construction-time. So there's no need for any registry or
> introspection at all. You determine the ordering at runtime when you
> construct the instances.
>
> Of course, this entire pattern is usually unnecessary in Python as you
> can usually write the same thing less verbosely and more
> straightforwardly as:
> def someHandler(theRequest):
>     result = try_and_handle(theRequest)
>     if did_not_handle(theRequest):
>         return False, None
>     else:
>         return True, result
>
> #imagine some other handler functions
> #setup:
> handlers = [someHandler, otherHandler, thirdHandler]
> #usage:
> for handler in handlers:
>     success, result = handler(theRequest)
>     if success: break
>
> Note the lack of classes and how the sequencing is now made explicit.
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Hi,
Thank you very much Chris for the extremely quick and helpful
reply.
I agree that it is not perfect CoR as per the examples given. But,
I have done it very similar to the second example that you had given.
I needed classes because I am not doing just one thing - I have a lot
of pre-processing and post processing, so I had used classes. The
register methods etc are just a fancy way of creating the list as you
mentioned. I am using the registry because there are many procedures
wherein different methods of the classes in registry are being used.
I am not sure whether I have understood your points completely. I
still cannot understand how to do the import so that the register
methods are hit.
--
http://mail.python.org/mailman/listinfo/python-list


converting a string to a function parameter

2009-03-13 Thread koranthala
Hi,
Is it possible to convert a string to a function parameter?
Ex:
str = 'True, type=rect, sizes=[3, 4]'
and I should be able to use it as:
test(convert(str)) and the behaviour should be same as calling test
with those values :
i.e. test(True, type=rect, sizes=[3, 4])

I tried eval, but it did not work. And any other mechanism I think
turns out to be creating a full fledged python parser.

Is there any mechanism with which we can do this straight away?



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


Re: converting a string to a function parameter

2009-03-13 Thread koranthala
On Mar 13, 1:01 pm, Chris Rebert  wrote:
> On Fri, Mar 13, 2009 at 12:52 AM, koranthala  wrote:
> > Hi,
> >    Is it possible to convert a string to a function parameter?
> > Ex:
> > str = 'True, type=rect, sizes=[3, 4]'
> > and I should be able to use it as:
> > test(convert(str)) and the behaviour should be same as calling test
> > with those values :
> > i.e. test(True, type=rect, sizes=[3, 4])
>
> > I tried eval, but it did not work. And any other mechanism I think
> > turns out to be creating a full fledged python parser.
>
> > Is there any mechanism with which we can do this straight away?
>
> Firstly, don't use `str` as a variable name since it conflicts with
> the name of the builtin type.
>
> Now here's how to use eval() properly:
>
> [insert standard 'eval() is EVIL!' warning/lecture here]
>
> eval("test("+the_str+")")
>
> or
>
> eval(test.__name__+"("+the_str+")")
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Thank you very much Chris.
I also thought about the first method a second after I posted this.
But I never thought about the second method.
I will heed the warning about the str part.

Thank you very much again, Chris.


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


Re: Help with setting up Tkinter

2009-04-08 Thread koranthala
On Apr 8, 1:20 pm, Eclipse  wrote:
> G'day All
>
> I was following the instructions (listed at bottom of post) from the
> PythonInfo Wiki which says to run three tests.
>
> I ran the tests and test 1 and 2 worked
>
> Test 3 gave me an error - 
>
> can anyone help ???
>
> Tks in advance
>
> Pete
>
> >>> import _tkinter
> >>> import Tkinter
> >>> Tkinter._test
>
> 
>
> _
>
> Checking your Tkinter support
>
> A good way to systematically check whether your Tkinter support is
> working is the following.
>
> Enter an interactive Python interpreter in a shell on an X console.
>
> Step 1 - can _tkinter be imported?
>
> Try the following command at the Python prompt:
>
> >>> import _tkinter # with underscore, and lowercase 't'
>
>     * If it works, go to step 2.
>     * If it fails with "No module named _tkinter", your Python
> configuration needs to be modified to include this module (which is an
> extension module implemented in C). Do **not** edit Modules/Setup (it
> is out of date). You may have to install Tcl and Tk (when using RPM,
> install the -devel RPMs as well) and/or edit the setup.py script to
> point to the right locations where Tcl/Tk is installed. If you install
> Tcl/Tk in the default locations, simply rerunning "make" should build
> the _tkinter extension.
>     * If it fails with an error from the dynamic linker, see above
> (for Unix, check for a header/library file mismatch; for Windows,
> check that the TCL/TK DLLs can be found).
>
> Step 2 - can Tkinter be imported?
>
> Try the following command at the Python prompt:
>
> >>> import Tkinter # no underscore, uppercase 'T'
>
>     * If it works, go to step 3.
>     * If it fails with "No module named Tkinter", your Python
> configuration need to be changed to include the directory that
> contains Tkinter.py in its default module search path. You have
> probably forgotten to define TKPATH in the Modules/Setup file. A
> temporary workaround would be to find that directory and add it to
> your PYTHONPATH environment variable. It is the subdirectory named
> "lib-tk" of the Python library directory (when using Python 1.4 or
> before, it is named "tkinter").
>
> Step 3 - does Tkinter work?
>
> Try the following command at the Python prompt:
>
> >>> Tkinter._test( ) # note underscore in _test( )
>
>     * This should pop up a small window with two buttons. Clicking the
> "Quit" button makes it go away and the command return. If this works,
> you're all set. (When running this test on Windows, from Python run in
> a MS-DOS console, the new window somehow often pops up *under* the
> console window. Move it aside or locate the Tk window in the Taskbar.)
>     *
>
>       If this doesn't work, study the error message you get; if you
> can't see how to fix the problem, ask for help.

Can you try Tkinter._test() instead of Tkinter._test
Just Tkinter._test  will go and hit its __repr__ code - i.e.
representation I guess - which displays the function data instead of
running actual function.
--
http://mail.python.org/mailman/listinfo/python-list


Reg: MFC71.DLL

2009-05-03 Thread koranthala
Hi,
   I had written a python 2.4 program. When I made it to an executable
with py2exe, it told that the mfc71.dll is not added - so I may have
to ship it separately. It also showed many other dll's which are all
in windows/system32 - which again it said is not added.
   Now, I have two questions -
  (1) Should I include mfc71.dll separately? - I found in the
following dicsussion -
http://groups.google.com/group/comp.lang.python/browse_thread/thread/96933f0b9a1a0f12/887675601f5c5c63
- that mfc71 might not be needed. Should I ship it separately?
  (2) The dlls in windows/system32 - do I need to ship it separately?

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


Creating temperory files for a web application

2009-05-08 Thread koranthala
Hi,
   I am doing web development using Django. I need to create an image
(chart) and show it to the users - based on some data which user
selects.
   My question is - how do I create a temporary image for the user? I
thought of tempfile, but I think it will be deleted once the process
is done - which would happen by the time user starts seeing the image.
I can think of no other option other than to have another script which
will delete all images based on time of creation.
   Since python is extensively used for web development, I guess this
should be an usual scenario for many people here. How do you usually
handle this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating temperory files for a web application

2009-05-08 Thread koranthala
On May 8, 2:49 pm, "Diez B. Roggisch"  wrote:
> koranthala wrote:
> > Hi,
> >    I am doing web development using Django. I need to create an image
> > (chart) and show it to the users - based on some data which user
> > selects.
> >    My question is - how do I create a temporary image for the user? I
> > thought of tempfile, but I think it will be deleted once the process
> > is done - which would happen by the time user starts seeing the image.
>
> What makes you think that? You are the one creating it, you are responsible
> for deleting it.
>
> > I can think of no other option other than to have another script which
> > will delete all images based on time of creation.
> >    Since python is extensively used for web development, I guess this
> > should be an usual scenario for many people here. How do you usually
> > handle this?
>
> There are various solutions - tempfiles, files based on a criteria (e.g.
> username and image-properties) so that they don't pollute the harddrive.
>
> For both approaches cleaning up as you suggest might be needed.
>
> Alternatively, if you use sessions, you can use memory-cached images.
>
> Or you can use the database.
>
> But the cleaning-up might get necessary here as well.
>
> The cleanest solution would be if the image would be rendered on the fly,
> based on GET-parameters (or REST-ful urls) so that you can render it into
> memory as string, but then forget immediately about it.
>
> Diez

Thank you Diez.
I would like to go ahead with the cleanest solution indeed.
I am creating the image on the fly. But I could not understand what
you meant by render to memory as a string.
How do we send the image to the browser?

Were you mentioning about having the image as a string and then
passing to the browser based on data URL scheme  ?
Or is it something else like XBM format or something? I am sorry - but
I am quite unsure of what you meant?

I am actually creating PDFs, CSVs and images on the fly. So, I need to
delete them all after that.
The images can be somewhat large - ~2MB. The RFC mentions that large
data cannot be sent that way.

Is it that I will have to delete the images using a separate script
later?

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


Re: Creating temperory files for a web application

2009-05-08 Thread koranthala
On May 8, 5:22 pm, koranthala  wrote:
> On May 8, 2:49 pm, "Diez B. Roggisch"  wrote:
>
>
>
> > koranthala wrote:
> > > Hi,
> > >    I am doing web development using Django. I need to create an image
> > > (chart) and show it to the users - based on some data which user
> > > selects.
> > >    My question is - how do I create a temporary image for the user? I
> > > thought of tempfile, but I think it will be deleted once the process
> > > is done - which would happen by the time user starts seeing the image.
>
> > What makes you think that? You are the one creating it, you are responsible
> > for deleting it.
>
> > > I can think of no other option other than to have another script which
> > > will delete all images based on time of creation.
> > >    Since python is extensively used for web development, I guess this
> > > should be an usual scenario for many people here. How do you usually
> > > handle this?
>
> > There are various solutions - tempfiles, files based on a criteria (e.g.
> > username and image-properties) so that they don't pollute the harddrive.
>
> > For both approaches cleaning up as you suggest might be needed.
>
> > Alternatively, if you use sessions, you can use memory-cached images.
>
> > Or you can use the database.
>
> > But the cleaning-up might get necessary here as well.
>
> > The cleanest solution would be if the image would be rendered on the fly,
> > based on GET-parameters (or REST-ful urls) so that you can render it into
> > memory as string, but then forget immediately about it.
>
> > Diez
>
> Thank you Diez.
> I would like to go ahead with the cleanest solution indeed.
> I am creating the image on the fly. But I could not understand what
> you meant by render to memory as a string.
> How do we send the image to the browser?
>
> Were you mentioning about having the image as a string and then
> passing to the browser based on data URL scheme  ?
> Or is it something else like XBM format or something? I am sorry - but
> I am quite unsure of what you meant?
>
> I am actually creating PDFs, CSVs and images on the fly. So, I need to
> delete them all after that.
> The images can be somewhat large - ~2MB. The RFC mentions that large
> data cannot be sent that way.
>
> Is it that I will have to delete the images using a separate script
> later?

Hi Diez,
   I think I understood your point now.
   Is it ?
   (1) Have a separate URL for the image - update urls.py for that
   (2) Pass all the GET parameters to that URL again.
   (3) Recalculate the fields again in that URL
   (4) Create the image and send back as image/png based on the
received fields.
   Other than the fact that I will be hitting the DB twice - for the
fields in the original URL and for creating Image in the second URL, I
think this is the best option.
   Please let me know whether I have understood correctly.

   The same option can be done for CSV and PDF files too. Thank you
very much Diez.
--
http://mail.python.org/mailman/listinfo/python-list


Python py2exe - memory load error

2009-11-29 Thread koranthala
This is cross post from stackoverflow - I couldnt get the solution
there. Hopefully, nobody would mind.

I am creating a medium level application in Python. Everything works
well now, and I am trying to make this a windows executable with
py2exe. The executable is created fine, but when I try to run it, it
fails with the following error.

  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\__init__.pyc", line 1, in ?
  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\AA.pyc", line 8, in ?
  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\pyAAc.pyc", line 5, in ?
  File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd

I am using pyAA in this application. I searched internet, but was
unable to get any solution. I copied msvcp71.dll to windows/system32,
but still issue is there.

I had solved it earlier (around 7 months back), but my hard drive
crashed and when I try to recreate it, I cannot seem to solve it
now. :-(

I would be much obliged if someone could help me out here.

When I use py2exe without bundle files option, it is working
perfectly. But when I use bundle file option, it is failing.

I tried without zipfile option, wherein it creates a library.zip
alongwith the executable. Again it failed. I did unzip of library.zip
using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside
the zip file. So, it looks like some issue with memoryloadlibrary
function.

>dir
11/30/2009  09:48 AM25,172 AA.pyc
11/30/2009  09:48 AM 3,351 Defer.pyc
11/30/2009  09:48 AM 2,311 Path.pyc
11/30/2009  09:48 AM11,216 pyAAc.pyc
11/30/2009  09:48 AM 5,920 Watcher.pyc
08/20/2005  02:00 PM49,152 _pyAAc.pyd
11/30/2009  09:48 AM   162 __init__.pyc

>From the trace it does look like it can extract AA.pyc etc. I am using
windows7 - can it be some clue?
-- 
http://mail.python.org/mailman/listinfo/python-list


pywintypes error

2009-11-30 Thread koranthala
Hi,
   When I try to use Django with Apache and mod_python, I am facing an
issue. Since this is a very usual configuration, I hope this issue is
already solved.
   My web sites fail with the following error :

"C:\\Python24\\Lib\\site-packages\\win32\\lib\\pywintypes.py", line
124, in?\n __import_pywin32_system_module__("pywintypes", globals())
[Mon Nov 30 15:13:50 2009] [error] [client 127.0.0.1] File"C:\
\Python24\\Lib\\site-packages\\win32\\lib\\pywintypes.py", line 114,
in__import_pywin32_system_module__\n assert sys.modules[modname]
isold_mod
[Mon Nov 30 15:13:50 2009] [error] [client 127.0.0.1] AssertionError

I checked the code in pywintypes and it is a sure assertion error:

old_mod = sys.modules[modname]
# Python can load the module
mod = imp.load_dynamic(modname, found)
# Check the sys.modules[] behaviour we describe above is true...
if sys.version_info < (3,0):
assert sys.modules[modname] is old_mod
assert mod is old_mod
else:
assert sys.modules[modname] is not old_mod
assert sys.modules[modname] is mod
# as above - re-reset to the *old* module object then update
globs.
sys.modules[modname] = old_mod
globs.update(mod.__dict__)

I have python 2.4 so, it goes to the first check and fails. Has
anyone else faced this issue? How to solve the same?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python py2exe - memory load error

2009-11-30 Thread koranthala
On Nov 30, 10:10 am, koranthala  wrote:
> This is cross post from stackoverflow - I couldnt get the solution
> there. Hopefully, nobody would mind.
>
> I am creating a medium level application in Python. Everything works
> well now, and I am trying to make this a windows executable with
> py2exe. The executable is created fine, but when I try to run it, it
> fails with the following error.
>
>   File "zipextimporter.pyc", line 82, in load_module
>   File "pyAA\__init__.pyc", line 1, in ?
>   File "zipextimporter.pyc", line 82, in load_module
>   File "pyAA\AA.pyc", line 8, in ?
>   File "zipextimporter.pyc", line 82, in load_module
>   File "pyAA\pyAAc.pyc", line 5, in ?
>   File "zipextimporter.pyc", line 98, in load_module
> ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
>
> I am using pyAA in this application. I searched internet, but was
> unable to get any solution. I copied msvcp71.dll to windows/system32,
> but still issue is there.
>
> I had solved it earlier (around 7 months back), but my hard drive
> crashed and when I try to recreate it, I cannot seem to solve it
> now. :-(
>
> I would be much obliged if someone could help me out here.
>
> When I use py2exe without bundle files option, it is working
> perfectly. But when I use bundle file option, it is failing.
>
> I tried without zipfile option, wherein it creates a library.zip
> alongwith the executable. Again it failed. I did unzip of library.zip
> using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside
> the zip file. So, it looks like some issue with memoryloadlibrary
> function.
>
> >dir
>
> 11/30/2009  09:48 AM            25,172 AA.pyc
> 11/30/2009  09:48 AM             3,351 Defer.pyc
> 11/30/2009  09:48 AM             2,311 Path.pyc
> 11/30/2009  09:48 AM            11,216 pyAAc.pyc
> 11/30/2009  09:48 AM             5,920 Watcher.pyc
> 08/20/2005  02:00 PM            49,152 _pyAAc.pyd
> 11/30/2009  09:48 AM               162 __init__.pyc
>
> From the trace it does look like it can extract AA.pyc etc. I am using
> windows7 - can it be some clue?

Can anyone provide some clues on how to solve this issue?
I would be much obliged if you could do the same.
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding a cookie

2010-01-17 Thread koranthala
Hi,
I am creating a webscraper for a specific web site for an
application.
Now, that website has a specific cookie which needs to be set in
the request. Otherwise, the website is redirected.
I have been trying for the last 6 hours to add a cookie to the
HTTP request, but to no avail.
I tried mechanize for some time, then found the cookielib module
which again is a copy of it.
For such a small thing, the whole setup seems to be too
complicated.

   The only way I could get any cookie in using the extract_cookies
from a cookiejar. But that will not help me because I want to add one
cookie - not get cookie from req and send it back.

Can anyone help me out?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global array in python

2009-09-29 Thread koranthala
On Sep 29, 5:48 am, Rudolf  wrote:
> How can i declare a global array in python?

As others have mentioned, you do not have concept of declaration. But
if you are looking for creating a global variable, it is like any
other language. Declare the same in a module, outside any procedures
or classes.

But, please note that it is not completely global. You have to go
inside the modules namespace to get it.
So, it will be like

Module A:
l = []

Module B:
import A
A.l ==> This is the global variable you are looking for.

To explain it further, every variable lives in a namespace. The
namespace can be that of a module (which is the global thing you are
looking for, I guess), or a class/object or even a procedure.

There is also a global keyword etc if that is what you are looking
for. Check out python documentation for more details.

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


Re: How to find number of line that is currently executing?

2009-10-10 Thread koranthala
On Oct 10, 8:54 am, Chris Rebert  wrote:
> On Fri, Oct 9, 2009 at 8:46 PM, Dr. Phillip M. Feldman
>
>  wrote:
>
> > I would like to put a statement on line N of my program that prints the line
> > number that is currently executing. This may sound fairly trivial, but I
> > don't want to hard code the line number because N will change if lines are
> > inserted or deleted above that point. Any advice will be appreciated.
>
> If you're doing this for debugging, it's often more convenient to just
> come up with a unique string you can grep for, but anyway:
>
> import traceback
> print traceback.extract_stack()[-1][1]
>
> Cheers,
> Chris
> --http://blog.rebertia.com

You can also use the logging module for good effect.
say: logging.info('Random Text')
A log generated this way also contains the line number.
-- 
http://mail.python.org/mailman/listinfo/python-list


sqlite question

2009-10-16 Thread koranthala
Hi,
   I use sqlalchemy to use a sqlite db in my program. The program is
working perfectly as of now. But now, a new requirement has come that
the db has to be encrypted.
   I found two options while searching internet - SQLite Encryption
Extension and Sqlite-Crypt. Now, buying the license is not an issue.
But I cannot understand how to use it along with sqlalchemy.
   There are two issues here -
(1) If I am buying the encrypted db, then I get only the C-code. I am
not sure how sqlalchemy links to the sqlite code.
(2) In the sqlalchemy documention, I couldnt find anything associated
with encryption.

Has anybody done this? Is it possible to use encrypted sqlite along
with sqlalchemy?

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


Re: sqlite question

2009-10-17 Thread koranthala
On Oct 17, 12:18 pm, Roger Binns  wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> Dennis Lee Bieber wrote:
> >    I suspect, besides building an sqlite3.dll (if Windows), you might
> > have to modify the pysqlite DB-API adapter to support whatever new
> > arguments have been added to various calls (most like the db.connect()
> > parameters have changed to require an encryption password)
>
> The extension requires an extra C api call after the database is opened to
> set the encryption key.  (There is also another API to change the key.)
>
> This means that it is not possible for the same pysqlite to work against
> SQLite built with and without the encryption extension.  The changes needed
> in pysqlite are a simple matter of programming although you'll want them
> incorporated back into the core so you don't have to maintain them (wrapped
> in some sort of ifdef).
>
> Roger
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.9 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org
>
> iEYEARECAAYFAkrZb6sACgkQmOOfHg372QRSYwCg2J/YSvkqLs8EJ1iJkE2wnbaY
> nl0AoKYxgMEnBQNjDyYHv1xWC0Tia74U
> =eA2B
> -END PGP SIGNATURE-

One problem is that pysqlite is written in C, and I have no knowledge
of C whatsoever. I will try to incorporate the changes mentioned, but
I am not sure now at all :-(

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


python os.path.exists failure

2009-10-31 Thread koranthala
Hi all,
   My code is as follows:

path = r'C:/"Program Files"/testfolder/2.3/test.txt'
if os.path.lexists(path):
print 'Path Exists'
else:
print 'No file found in path - %s' %path
print Popen(path, stdout=PIPE, shell=True).stdout.read()

The output comes as
No file found in path - C:/"Program Files"/testfolder/2.3/test.txt
but the test.txt file is opened.

The issue, I guess, is that the double quotes inside is failing the
check. But without the double quotes, Popen fails.
One solution, I can think is to check without double quotes, and then
using some code, put the double quotes back inside, but it looks quite
kludgy.

What is the usual solution to this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Urllib2 urlopen and read - difference

2010-04-15 Thread koranthala
Hi,
   Suppose I am doing the following:
req = urllib2.urlopen('http://www.python.org')
data = req.read()

   When is the actual data received? is it done by the first line? or
is it done only when req.read() is used?
  My understanding is that when urlopen is done itself, we would have
received all the data, and req.read() just reads it from the file
descriptor.
  But, when I read the source code of pylot, it mentioned the
following:
resp = opener.open(request)  # this sends the HTTP request
and returns as soon as it is done connecting and sending
connect_end_time = self.default_timer()
content = resp.read()
req_end_time = self.default_timer()

Here, it seems to suggest that the data is received only after you do
resp.read(), which made me all confused.

If someone could help me out, it would be much helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-Threading and KeyboardInterrupt

2009-06-13 Thread koranthala
On Jun 13, 10:25 am, Mike Kazantsev  wrote:
> On Thu, 11 Jun 2009 22:35:15 -0700
> Dennis Lee Bieber  wrote:
>
>
>
> > On Thu, 11 Jun 2009 08:44:24 -0500, "Strax-Haber, Matthew (LARC-D320)"
> >  declaimed the following in
> > gmane.comp.python.general:
>
> > > I sent this to the Tutor mailing list and did not receive a response.
> > > Perhaps one of you might be able to offer some sagely wisdom or pointed
> > > remarks?
>
> > > Please reply off-list and thanks in advance. Code examples are below in
> > > plain text.
>
> >    Sorry -- you post to a public forum, expect to get the response on a
> > public forum...
>
> > > > My program runs interactively by allowing the user to directly
> > > > interact with the python prompt. This program has a runAll() method
> > > > that runs a series of subprocesses with a cap on how many instances
> > > > are running at a time. My intent is to allow the user to use Ctrl-C to
> > > > break these subprocesses. Note that while not reflected in the demo
>
> >    Are they subprocesses or threads? Your sample code seems to be using
> > threads.
>
> >    When using threads, there is no assurance that any thread other than
> > the main program will receive a keyboard interrupt.
>
> In fact, no thread other than the main will get interrupt.
>
>
>
> > > def runAll():
> > >     workers = [ Thread(target = runSingle, args = [i])
> > >             for i in xrange(MAX_SUBPROCS + 1) ]
> > >     try:
> > >         for w in workers:
> > >             w.start()
> > >     except KeyboardInterrupt:
> > >         ## I want this to be shown on a KeyboardInterrupt
> > >         print '* stopped midway '
>
> >    You are unlikely to see that... After you start the defined worker
> > /threads/ (which doesn't take very long -- all threads will be started,
> > but some may immediately block on the semaphore) this block will exit
> > and you will be at...
>
> > >     for w in workers:
> > >         w.join()
>
> >    ... a .join() call, which is the most likely position at which the
> > keyboard interrupt will be processed, killing the main program thread
> > and probably generating some errors as dangling active threads are
> > forceably killed.
>
> There was quite interesting explaination of what happens when you send
> ^C with threads, posted on concurrency-sig list recently:
>
>  http://blip.tv/file/2232410
>  http://www.dabeaz.com/python/GIL.pdf
>
> Can be quite shocking, but my experience w/ threads only confirms that.
>
> --
> Mike Kazantsev // fraggod.net
>
>  signature.asc
> < 1KViewDownload

Thank you very much for the link Mike.
Are there other videos/audio like this? I am learning more from these
videos than by experience alone.
I did find one - http://www.awaretek.com/python/ - are there other
links?
-- 
http://mail.python.org/mailman/listinfo/python-list


Good books in computer science?

2009-06-13 Thread koranthala
Hi all,
I do understand that this is not a python question and I apologize
for that straight up.
But I am a full time follower of this group and I have seen very
very brilliant programmers and solutions.
I also want to be a good programmer - so this question.

Which are the classic books in computer science which one should
peruse?
I have  (a) Code Complete (b) GOF (c) Art of programming.

Art of programming was too tough for me - and I couldnt understand
much. The other two were good books - I understood and implemented
quite a bit from both.
What are the other books which I should peruse?

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


Re: Good books in computer science?

2009-06-13 Thread koranthala

> Code Complete and GOF are software engineering books but not really
> CS books.

I understand and concur. Since I am a software engineer - coming in to
software from a different background - what I am looking for is self-
improvement books for a software engineer. This can include both CS
and Software books - even though I found that CS books are much less
understandable to me :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good books in computer science?

2009-06-13 Thread koranthala
On Jun 14, 1:52 am, "Rhodri James" 
wrote:
> On Sat, 13 Jun 2009 18:37:13 +0100, koranthala   
> wrote:
>
>
>
> >> Code Complete and GOF are software engineering books but not really
> >> CS books.
>
> > I understand and concur. Since I am a software engineer - coming in to
> > software from a different background - what I am looking for is self-
> > improvement books for a software engineer.
>
> In that case The Mythical Man-Month (Brooks) is a must.
>
> --
> Rhodri James *-* Wildebeest Herder to the Masses

Thank you Rhodri.
I do have Mythical Man-Month - a great book indeed.
I was looking for more technical books -
I have now got a good set - Putting it across so that others can also
use maybe -

Code Complete,
GOF,
Mythical Man-Month,
SICP - Thank you Paul - I have downloaded it from Web Site,
Introduction to algorithm - I have placed an order for the same,
The Pragmatic Programmer - Planning to buy,
Refactoring: Improving the Design of Existing Code - again planning to
buy,
The C Programming Language - I had this, lost it, now I will buy
again,
The Little Schemer - I am not sure about buying this - I dont know
scheme
Software Tools - Seems to be a classic - not sure whether I will buy.

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


Re: Good books in computer science?

2009-06-15 Thread koranthala
> There are huge numbers (millions?) of lousy programmers who program every
> single day and never become good programmers.

I think I can attest to that.
I was a programmer (in a low level language) in a huge MNC code monkey
shop for > 7 years.
I consider myself to be Ok - not great, but not very poor either.
I had written a lot of code in those 7 years, but due to lack of
exposure and laziness, never knew that I have to read books.
As I mentioned before, I come in from a non-computing engineering
degree, so I did not even know which books to read etc.

I had seen many of the frameworks written by others, and was extremely
impressed. I considered those people who wrote those frameworks to be
geniuses - until I accidently came across one site where I read about
GOF.
I bought it and read it - and straight away understood that whatever I
learned in the last 7 years, I could have learned most of them in 6
months, provided I had read the right books. All the frameworks were
just amalgamation of these patterns.

Now, I voraciously purchase and read books - both in the domain of my
work and on computer science in general. Even though I am not going to
be recruited by google any time soon :-), I think I have become a much
better programmer over the last one year. I see my code before 1 year
and I am horrified :-).

Practice makes perfect only if you push yourself - and you need
exposure to know that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On the property function

2009-06-16 Thread koranthala
On Jun 16, 9:19 am, Chris Rebert  wrote:
> On Mon, Jun 15, 2009 at 5:43 AM, Virgil Stokes wrote:
> > Does anyone have a good example (or examples) of when "property(...)" can be
> > useful?
>
> Erm, when you want to create a property (i.e. computed attribute).
>
> from __future__ import division
> class TimeDelta(object):
>     def __init__(self, secs):
>         self. seconds =secs
>
>     @property
>     def minutes(self):
>         return self.seconds/60
>
>     @property
>     def hours(self):
>         return self.minutes/60
>
>     @property
>     def days(self):
>         return self.hours/24
>
> td = TimeDelta(555)
> print td.days, "days", "=", td.hours, "hours", "=", td.minutes, "minutes"
>
> Cheers,
> Chris
> --http://blog.rebertia.com

To add a little more, this link _ 
http://dirtsimple.org/2004/12/python-is-not-java.html
_ might help. - Search for 'Getters and setters' and you will reach
the place where property is explained more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Matplotlib - an odd problem

2009-06-24 Thread koranthala
Hi,
I am using Matplotlib with Django to display charts on the web page.
I am facing an odd problem in that, everytime I do a refresh on the
web page, the image darkens - and the text becomes little unreadable.
5/6 refreshes later, the text becomes completely unreadable.
Since I am using Django test server, the same process is being used.
i.e. every refresh does not create a new process. When I tried killing
the process, the image again cleared.
So I think it is sort of memory leak or a saved value which is messing
up something.
But I cannot seem to find the issue at all.

The code is as follows -

import pylab
from cStringIO import StringIO

def print_pie_chart(request):
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
data = [15,30,45, 10]
pylab.figure(1, figsize=(2,2))
ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
pylab.pie(data, explode=None, labels=labels, autopct='%1.1f%%',
shadow=True)
out = StringIO()
pylab.savefig(out, format="PNG")
out.seek(0)
response = HttpResponse()
response['Content-Type'] = 'image/png'
response.write(out.read())
return response

Can anyone help me out here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib - an odd problem

2009-06-24 Thread koranthala
On Jun 25, 2:55 am, Jean-Paul Calderone  wrote:
> On Wed, 24 Jun 2009 11:38:02 -0700 (PDT), koranthala  
> wrote:
> >Hi,
> >I am using Matplotlib with Django to display charts on the web page.
> >I am facing an odd problem in that, everytime I do a refresh on the
> >web page, the image darkens - and the text becomes little unreadable.
> >5/6 refreshes later, the text becomes completely unreadable.
> >Since I am using Django test server, the same process is being used.
> >i.e. every refresh does not create a new process. When I tried killing
> >the process, the image again cleared.
> >So I think it is sort of memory leak or a saved value which is messing
> >up something.
> >But I cannot seem to find the issue at all.
>
> >The code is as follows -
>
> >import pylab
> >from cStringIO import StringIO
>
> >def print_pie_chart(request):
> >    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
> >    data = [15,30,45, 10]
> >    pylab.figure(1, figsize=(2,2))
> >    ax = pylab.axes([0.1, 0.1, 0.8, 0.8])
> >    pylab.pie(data, explode=None, labels=labels, autopct='%1.1f%%',
> >shadow=True)
> >    out = StringIO()
> >    pylab.savefig(out, format="PNG")
> >    out.seek(0)
> >    response = HttpResponse()
> >    response['Content-Type'] = 'image/png'
> >    response.write(out.read())
> >    return response
>
> >Can anyone help me out here?
>
> Your code redraws over the same graph over and over again.  You need to
> create a new graph each time you want to draw something new.  It took me
> ages (and help) to figure out how the non-global APIs in matplotlib.
>
> Here's an example:
>
>   from matplotlib.figure import Figure
>   from matplotlib.axes import Axes
>   from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as 
> FigureCanvas
>
>   fig = Figure(figsize=(9, 9), dpi=100)
>   axe = Axes(fig, (0, 0, 1.0, 1.0))
>   axe.pie(range(5))
>   fig.add_axes(axe)
>
>   canvas = FigureCanvas(fig)
>   canvas.set_size_request(640, 480)
>
>   fig.savefig("foo.png")
>
> Hope this helps,
> Jean-Paul

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


Re: Recipes for trace statements inside python programs?

2009-06-25 Thread koranthala
On Jun 25, 1:40 pm, Francesco Bochicchio  wrote:
> Sorry, hit the send button by mistake ...
> The definition of the trace function should be like:
>
> if __debug__ :
>    def TRACE(*args):
>      if  trace_enabled(): print "TRACE(%s) : %s " % ( context(),
>                               " ".join( str(x) for x in args ) )
> else : # optimazed code, only a function call performance penalty
>    def TRACE(*args): pass
>
> If I don't find anything suitable, maybe I will bake my own again,
> this
> time aiming to something that I can reuse ...
>
> Ciao and thanks for any tip/suggestion
> --
> FB

Is assert what you are looking for?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one more question

2009-07-15 Thread koranthala
On Jul 15, 11:13 am, [email protected] wrote:
> Dear all,
>
> Just one more thing i want to ask that suppose i have a file like:---
>
>  47     8   ALA       H     H      7.85     0.02     1
>  48     8   ALA       HA    H      2.98     0.02     1
>  49     8   ALA       HB    H      1.05     0.02     1
>  50     8   ALA       C     C    179.39      0.3     1
>  51     8   ALA       CA    C     54.67      0.3     1
>  52     8   ALA       CB    C     18.85      0.3     1
>  53     8   ALA       N     N    123.95      0.3     1
> 107    15   ALA       H     H      8.05     0.02     1
> 108    15   ALA       HA    H      4.52     0.02     1
>
> now what i want that i will make another file in which first it will write
> the position of ALA lets say 8 then its name ALA and then the chemical
> shift value for only three atoms C,CA and CB.
>
> Means it will be someting like:
>
> 8  ALA  C = 179.39  CA = 54.67  CB = 18.85
>
> I tried but its not coming.
>
> Thanks,
> Amrita Kumari
> Research Fellow
> IISER Mohali
> Chandigarh
> INDIA

This is indeed possible and should be quite easy. One problem is that
I do not exactly understand the problem - how do you decide which all
to join and print? Is it ALA with 4th field as C or 6th field as 0.3?
The issue here is that I am not getting the context of your problem.
And I have *no* idea about the Chemical shift etc which you are
talking about.
If you can explain it a little more, I will try something out.

Just for the scenario you explained, this code will suffice -
f = open('abcd')
d = {}
for line in f:
fields = line.split()
if fields[2] == 'ALA':
d.setdefault('ALA', {'position':fields[1], 'values':[]})
if fields[4] == 'C':
d['ALA']['values'].append({fields[3]:fields[5]})

print d

But i dont think this is what you want
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one more question

2009-07-15 Thread koranthala
On Jul 15, 11:56 am, alex23  wrote:
> On Jul 15, 4:50 pm, alex23  wrote:
>
> > [email protected] wrote:
> > > I tried but its not coming.
>
> > How much are you prepared to pay for help with this? Or are you just
> > asking us to do all the work for you?
>
> Or to be a _little_ less blunt: if you want people here to _assist_
> you with _your_ code, then post what you've tried here, along with
> tracebacks if errors are occurring, or an explanation as to what it
> isn't doing that you require.
>
> Spawning a new thread restating your question every time someone
> suggests you RTFM isn't the best way to show that you're actually
> trying to solve this issue yourself.

Alex,
   I am not sure about it. It doesnt look like she(I guess) is a
programmer. In the last thread, she asked the question and the reply
was to check up the regular expressions. Now, for a non-programmer, re
might be a real confusing and tough subject to grasp.
   I am not saying that what you said was wrong, only that I felt that
she got tense looking up regular expressions. So a python reply which
basically does the basic checking without going to re etc might be
more helpful for her to start her own coding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mail

2009-07-15 Thread koranthala
On Jul 15, 11:46 pm, [email protected] wrote:
> Dear all,
>
> Sorry that I am disturbing you all again and again but this is the way I
> am trying to solve my problem:---
>
> >>> import re
> >>> exp = re.compile("CA")
> >>> infile = open("file1.txt")
> >>> for line in infile:
>
> ...     values = re.split("\s+", line)
> ...     if exp.search(line):
> ...        print ("%s %s CA = %s" %(values[2], values[3], values[6]))
> ...
>  with this it is giving the output like:
>
> 8 ALA CA = 54.67
> 15 ALA CA = 52.18
> 21 ALA CA = 54.33
> 23 ALA CA = 55.84
> 33 ALA CA = 55.58
> 38 ALA CA = 54.33
>
> which is all right but i want CB and C value also in each row and it
> should take value from 5th column infront of them, file is something
> lookin like:-
>
>  47     8   ALA       H     H      7.85     0.02     1
>  48     8   ALA       HA    H      2.98     0.02     1
>  49     8   ALA       HB    H      1.05     0.02     1
>  50     8   ALA       C     C    179.39      0.3     1
>  51     8   ALA       CA    C     54.67      0.3     1
>  52     8   ALA       CB    C     18.85      0.3     1
>  53     8   ALA       N     N    123.95      0.3     1
> 107    15   ALA       H     H      8.05     0.02     1
> 108    15   ALA       HA    H      4.52     0.02     1
> 109    15   ALA       HB    H      1.29     0.02     1
> 110    15   ALA       C     C    177.18      0.3     1
> 111    15   ALA       CA    C     52.18      0.3     1
> 112    15   ALA       CB    C     20.64      0.3     1
> 113    15   ALA       N     N    119.31      0.3     1
> 154    21   ALA       H     H      7.66     0.02     1
> 155    21   ALA       HA    H      4.05     0.02     1
> 156    21   ALA       HB    H      1.39     0.02     1
> 157    21   ALA       C     C    179.35      0.3     1
> 158    21   ALA       CA    C     54.33      0.3     1
> 159    21   ALA       CB    C     17.87      0.3     1
> 160    21   ALA       N     N    123.58      0.3     1
> 169    23   ALA       H     H      8.78     0.02     1
> 170    23   ALA       HA    H      4.14     0.02     1
> 171    23   ALA       HB    H      1.62     0.02     1
> 172    23   ALA       C     C    179.93      0.3     1
> 173    23   ALA       CA    C     55.84      0.3     1
> 174    23   ALA       CB    C     17.55      0.3     1
> 175    23   ALA       N     N    120.16      0.3     1
> 232    33   ALA       H     H      7.57     0.02     1
> 233    33   ALA       HA    H      3.89     0.02     1
> 234    33   ALA       HB    H      1.78     0.02     1
> 235    33   ALA       C     C    179.24      0.3     1
> 236    33   ALA       CA    C     55.58      0.3     1
> 237    33   ALA       CB    C     19.75      0.3     1
> 238    33   ALA       N     N    121.52      0.3     1
> 269    38   ALA       H     H      8.29     0.02     1
> 270    38   ALA       HA    H      4.04     0.02     1
> 271    38   ALA       HB    H      1.35     0.02     1
> 272    38   ALA       C     C    178.95      0.3     1
> 273    38   ALA       CA    C     54.33      0.3     1
> 274    38   ALA       CB    C     18.30      0.3     1
> 275    38   ALA       N     N    120.62      0.3     1
>
> I just want that it will give output something like:-
>
> 8  ALA  C = 179.39  CA = 54.67  CB = 18.85
> 15 ALA  C = 177.18  CA = 52.18  CB = 20.64
> 21 ALA  C = 179.35  CA = 54.33  CB = 17.87.
>
> so first it will write the position of the amino acid(given by second
> column)then amino acid here it is ALA and then the corresponding value of
> C, CA and CB from 5th colum for each position of ALA.
>
> Amrita Kumari
> Research Fellow
> IISER Mohali
> Chandigarh
> INDIA

Hi,
   Can you try using the code which I suggested in the earlier thread?
   If you cannot use it to get the output, just point it out here, and
I will try to solve the issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one more question

2009-07-15 Thread koranthala
On Jul 16, 7:30 am, alex23  wrote:
> On Jul 15, 5:51 pm, koranthala  wrote:
>
> >    I am not saying that what you said was wrong, only that I felt that
> > she got tense looking up regular expressions. So a python reply which
> > basically does the basic checking without going to re etc might be
> > more helpful for her to start her own coding.
>
> Using regexps wasn't the only advice given, and string manipulation is
> covered well in pretty much every tutorial I've taken a look at. The
> issue is that no evidence was shown that the OP was even trying to
> resolve this themself, and the new posting of the question every time
> an unsatisfactory answer was provided doesn't give me any faith they
> were endeavouring to do this at all.
>
> It's annoying seeing these "stone soup" attempts at coding come
> through here, whether its to answer someone's homework or to do
> someone's job for them. If the end result has value to the poster, I
> expect to see either effort on their behalf or at least a nominal
> attempt to reward others for their time.
>
> But if you want to do their work for them, I don't think anyone here
> would object, especially if you both took it to private correspondence.

It is not that I do want to do the work for them. It is just that I
was in the same position just 6 months back. My first pieces of code
were very poor - full of errors and quite horrible indeed. I was even
afraid to post it anywhere. I came here, and I found so much helpful
people who helped me out so much, that I think my coding has improved
a little bit. So, I just thought that we should always give people the
benefit of doubt.

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


Re: Einstein summation notation (was: question of style)

2009-07-16 Thread koranthala
> That test was designed to treat None as a boolean False, without
> noticing that numeric 0 is also treated as False and could make the
> test do the wrong thing.  This is an extremely common type of error.

Actually, I felt that 0 not being considered False would be a better
option.
I had lot of instances where 0 is a valid value and always I had to
put checks specifically for that.
For me, None and False should be equal to False in if checks, every
thing else being considered True.

Can someone let me know why 0 is considered equal to False?
There should be real good reasons for it, only that I cannot think of
one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read webpage

2009-08-01 Thread koranthala
On Aug 1, 6:52 pm, MRAB  wrote:
> tarun wrote:
> > Dear All,
> > I want to read a webpage and copy the contents of it in word file. I
> > tried to write following code:
>
> > import urllib2
> > urllib2.urlopen("http://www.rediff.com/";)
>
> > *Error:-*
>
> >     urllib2.urlopen("http://www.icicibank.com/";)
> >   File "C:\Python25\lib\urllib2.py", line 121, in urlopen
> >     return _opener.open(url, data)
> >   File "C:\Python25\lib\urllib2.py", line 374, in open
> >     response = self._open(req, data)
> >   File "C:\Python25\lib\urllib2.py", line 392, in _open
> >     '_open', req)
> >   File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
> >     result = func(*args)
> >   File "C:\Python25\lib\urllib2.py", line 1100, in http_open
> >     return self.do_open(httplib.HTTPConnection, req)
> >   File "C:\Python25\lib\urllib2.py", line 1075, in do_open
> >     raise URLError(err)
> > urllib2.URLError: 
>
> I've just tried it. I didn't get an exception, so your problem must be
> elsewhere.

Is it that the website expects a valid browser?
In that case, spoof a browser and try to get the site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Which GUI framework to use?

2009-08-03 Thread koranthala
Hi,
   I am creating a very minimal application (a networking app).
   I have written the application using Twisted.
   Now, I need to put a GUI wrapper on the application.
   The application needs a login screen and also it needs to be
minimized to system tray. If I right click the image on system tray, I
should be able to close it.
   It uses some legacy code, so the whole app is written in Python
2.4. Also, my company requires that I use permissive licenses (no GPL
- MIT, BSD, LGPL etc ok)

   Which GUI framework is best for this? I tried using Tkinter, but it
does not support minimize to system tray (or I couldnt find it).

   This is my first foray to GUI programming, so other issues that I
am worried about -
   1. GUI needs a loop, Twisted needs a loop. How can both go ahead
without messing each other?

Thank You very much
K
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which GUI framework to use?

2009-08-04 Thread koranthala
On Aug 4, 11:48 am, "Diez B. Roggisch"  wrote:
> koranthala schrieb:
>
> > Hi,
> >    I am creating a very minimal application (a networking app).
> >    I have written the application using Twisted.
> >    Now, I need to put a GUI wrapper on the application.
> >    The application needs a login screen and also it needs to be
> > minimized to system tray. If I right click the image on system tray, I
> > should be able to close it.
> >    It uses some legacy code, so the whole app is written in Python
> > 2.4. Also, my company requires that I use permissive licenses (no GPL
> > - MIT, BSD, LGPL etc ok)
>
> Google this group. The discussions are abundant about this. Keep in mind
> that while Qt changed licenses to LGPL, PyQt didn't and thus you can't
> use it.
>
> >    Which GUI framework is best for this? I tried using Tkinter, but it
> > does not support minimize to system tray (or I couldnt find it).
>
> >    This is my first foray to GUI programming, so other issues that I
> > am worried about -
> >    1. GUI needs a loop, Twisted needs a loop. How can both go ahead
> > without messing each other?
>
> Google is your friend here, too:
>
> http://twistedmatrix.com/projects/core/documentation/howto/choosing-r...
>
> Diez

Sorry about it.
I should have done the homework better.
-- 
http://mail.python.org/mailman/listinfo/python-list


My first wxPython App with Twisted

2009-08-04 Thread koranthala
Hi,
   I am creating the first GUI app (wxPython based) using Twisted.
   I am facing an issue which I cannot seem to solve/understand due
to lack of trace or anything.

   I had a big app written on twisted and now I am creating a login
screen to the app.
   The app used to work without any issues. I added the login screen
and the login screen comes up.
But then everything freezes up. I have to force quit the python
application to get anything back. Can anyone help me solve it?

   The code is as follows:

import wx
import os
import logging

from twisted.internet import wxreactor
wxreactor.install()
from twisted.internet import reactor #Called only after
wxreactor.install()
from twisted.internet.task import LoopingCall

import clientapp

def opj(path):
   """ Convert paths to the platform-specific separator """
   st = apply(os.path.join, tuple(path.split('/')))
   if path.startswith('/'):
   st = '/' + st
   return st


class APPApp(wx.App):
   def OnInit(self):
   self.frame = APPFrame(None, -1, " APP Login", size=(200, 150))
   self.panel = APPPanel(self.frame,-1)
   #client.run method does the verification etc along with other
items
   client = clientapp.setup_app()
   call = LoopingCall(client.run)
   call.start(.51)
   return True


def main():
   app = APPApp(0)
   reactor.registerWxApp(app)
   try:
   reactor.run()
   except StandardError:
   raise


class APPPanel(wx.Panel):
   """ APP GUI PANEL

   The panel in which the user name and password is typed.
   @var ID_LOGIN: Login buttons id. When this button is clicked, the
data
   is stored for logging.

   """
   ID_LOGIN = wx.NewId()

   def __init__(self, parent, id):
   self.parent = parent
   wx.Panel.__init__(self, parent, id, size=(200,150))
   self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60,
10))
   wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33))
   wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58))
   self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "",
wx.Point(80, 31), wx.Size(100, wx.ID_ANY))
   self.usernameBox.SetFocus()
   self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "",
wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD)
   self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point
(60, 88))
   wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login)

   def on_login(self, event):
   username = self.usernameBox.GetString(0, 128)
   password = self.passwordBox.GetString(0, 128)
   if username and password:
   self.parent.on_login_click(username, password)


class APPTaskBarIcon(wx.TaskBarIcon):
   ''' TaskBar Icon

   So that the application is always alive on the taskbar.
   3 operations are possible, DoubleClick on the taskbar would bring
up the
   window, right click will bring up options to restore or exit the
tool.

   '''
   TBMENU_RESTORE = wx.NewId()
   TBMENU_CLOSE   = wx.NewId()

   def __init__(self, frame):
   wx.TaskBarIcon.__init__(self)
   self.frame = frame
   # Set the image
   icon = self.MakeIcon(self.frame.get_image())
   self.SetIcon(icon, "APP")
   self.imgidx = 1
   # bind some events
   self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
   self.Bind(wx.EVT_MENU, self.OnTaskBarActivate,
id=self.TBMENU_RESTORE)
   self.Bind(wx.EVT_MENU, self.OnTaskBarClose,
id=self.TBMENU_CLOSE)

   def CreatePopupMenu(self):
   """ Right Click Popup Menu

   This method is called by the base class when it needs to popup
   the menu for the default EVT_RIGHT_DOWN event.

   """
   menu = wx.Menu()
   menu.Append(self.TBMENU_RESTORE, "Restore Window")
   menu.Append(self.TBMENU_CLOSE, "Exit APP")
   return menu

   def MakeIcon(self, img):
   """ Return the generated Icon.

   This function is required because various platforms have
different
   requirements for the icon size.

   """
   if "wxMSW" in wx.PlatformInfo:
   img = img.Scale(16, 16)
   elif "wxGTK" in wx.PlatformInfo:
   img = img.Scale(22, 22)
   icon = wx.IconFromBitmap(img.ConvertToBitmap() )
   return icon

   def OnTaskBarActivate(self, evt):
   ''' Activation code - say DoubleClick etc. It raises the window
'''
   if self.frame.IsIconized():
   self.frame.Iconize(False)
   if not self.frame.IsShown():
   self.frame.Show(True)
   self.frame.Raise()

   def OnTaskBarClose(self, evt):
   ''' On right click and close, the frame itself is closed '''
   wx.CallAfter(self.frame.Close)


class APPFrame(wx.Frame):
   def __init__(self, parent, id, title, size=None):
   wx.Frame.__init__(self, parent, id, title,
 size=size, pos=wx.Point(400, 300))
   icon = self.get_icon()
   self.SetIcon(icon)
   self.tbicon = APPTaskBarIcon(self)
   self.Show(True)
   self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  

Re: My first wxPython App with Twisted

2009-08-04 Thread koranthala
On Aug 5, 6:29 am, koranthala  wrote:
> Hi,
>    I am creating the first GUI app (wxPython based) using Twisted.
>    I am facing an issue which I cannot seem to solve/understand due
> to lack of trace or anything.
>
>    I had a big app written on twisted and now I am creating a login
> screen to the app.
>    The app used to work without any issues. I added the login screen
> and the login screen comes up.
>     But then everything freezes up. I have to force quit the python
> application to get anything back. Can anyone help me solve it?
>
>    The code is as follows:
>
> import wx
> import os
> import logging
>
> from twisted.internet import wxreactor
> wxreactor.install()
> from twisted.internet import reactor #Called only after
> wxreactor.install()
> from twisted.internet.task import LoopingCall
>
> import clientapp
>
> def opj(path):
>    """ Convert paths to the platform-specific separator """
>    st = apply(os.path.join, tuple(path.split('/')))
>    if path.startswith('/'):
>        st = '/' + st
>    return st
>
> class APPApp(wx.App):
>    def OnInit(self):
>        self.frame = APPFrame(None, -1, " APP Login", size=(200, 150))
>        self.panel = APPPanel(self.frame,-1)
>        #client.run method does the verification etc along with other
> items
>        client = clientapp.setup_app()
>        call = LoopingCall(client.run)
>        call.start(.51)
>        return True
>
> def main():
>    app = APPApp(0)
>    reactor.registerWxApp(app)
>    try:
>        reactor.run()
>    except StandardError:
>        raise
>
> class APPPanel(wx.Panel):
>    """ APP GUI PANEL
>
>    The panel in which the user name and password is typed.
>   �...@var ID_LOGIN: Login buttons id. When this button is clicked, the
> data
>        is stored for logging.
>
>    """
>    ID_LOGIN = wx.NewId()
>
>    def __init__(self, parent, id):
>        self.parent = parent
>        wx.Panel.__init__(self, parent, id, size=(200,150))
>        self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60,
> 10))
>        wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33))
>        wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58))
>        self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "",
> wx.Point(80, 31), wx.Size(100, wx.ID_ANY))
>        self.usernameBox.SetFocus()
>        self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "",
> wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD)
>        self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point
> (60, 88))
>        wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login)
>
>    def on_login(self, event):
>        username = self.usernameBox.GetString(0, 128)
>        password = self.passwordBox.GetString(0, 128)
>        if username and password:
>            self.parent.on_login_click(username, password)
>
> class APPTaskBarIcon(wx.TaskBarIcon):
>    ''' TaskBar Icon
>
>    So that the application is always alive on the taskbar.
>    3 operations are possible, DoubleClick on the taskbar would bring
> up the
>    window, right click will bring up options to restore or exit the
> tool.
>
>    '''
>    TBMENU_RESTORE = wx.NewId()
>    TBMENU_CLOSE   = wx.NewId()
>
>    def __init__(self, frame):
>        wx.TaskBarIcon.__init__(self)
>        self.frame = frame
>        # Set the image
>        icon = self.MakeIcon(self.frame.get_image())
>        self.SetIcon(icon, "APP")
>        self.imgidx = 1
>        # bind some events
>        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
>        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate,
> id=self.TBMENU_RESTORE)
>        self.Bind(wx.EVT_MENU, self.OnTaskBarClose,
> id=self.TBMENU_CLOSE)
>
>    def CreatePopupMenu(self):
>        """ Right Click Popup Menu
>
>        This method is called by the base class when it needs to popup
>        the menu for the default EVT_RIGHT_DOWN event.
>
>        """
>        menu = wx.Menu()
>        menu.Append(self.TBMENU_RESTORE, "Restore Window")
>        menu.Append(self.TBMENU_CLOSE, "Exit APP")
>        return menu
>
>    def MakeIcon(self, img):
>        """ Return the generated Icon.
>
>        This function is required because various platforms have
> different
>        requirements for the icon size.
>
>        """
>        if "wxMSW" in wx.PlatformInfo

My first wxPython App with Twisted - barebones version

2009-08-04 Thread koranthala
Hi,
   I am creating the first GUI app (wxPython based) using Twisted.
   I am facing an issue which I cannot seem to solve/understand due
to lack of trace or anything.
   I had a big app written on twisted and now I am creating a login
screen to the app.
   The app used to work without any issues. I added the login screen
and the login screen comes up.
But then everything freezes up. I have to force quit the python
application to get anything back. Can anyone help me solve it?
   The code is as follows:

import wx
import os
import logging

from twisted.internet import wxreactor
wxreactor.install()
from twisted.internet import reactor #Called only after
wxreactor.install()
from twisted.internet.task import LoopingCall

import clientapp


def opj(path):
""" Convert paths to the platform-specific separator """
st = apply(os.path.join, tuple(path.split('/')))
if path.startswith('/'):
st = '/' + st
return st


class APPApp(wx.App):
def OnInit(self):
self.frame = APPFrame(None, -1, " APP Login", size=(200, 150))
self.panel = APPPanel(self.frame,-1)
client = clientapp.setup_app()
call = LoopingCall(client.run)
call.start(.51)
return True


def main():
app = APPApp(0)
reactor.registerWxApp(app)
try:
reactor.run()
except StandardError:
raise


class APPFrame(wx.Frame):
def __init__(self, parent, id, title, size=None):
wx.Frame.__init__(self, parent, id, title,
  size=size, pos=wx.Point(400, 300))
icon = self.get_icon()
self.SetIcon(icon)
self.Show(True)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.Bind(wx.EVT_ICONIZE, self.OnIconify)

def on_login_click(self, username, password):
self.Hide()

def OnCloseWindow(self, event):
event.Skip()

def OnIconify(self, event):
self.Hide()

def get_image(self):
img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO)
return img

def get_icon(self):
img = self.get_image()
icon = wx.IconFromBitmap(img.ConvertToBitmap() )
return icon


if __name__ == '__main__':
main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first wxPython App with Twisted - barebones version

2009-08-04 Thread koranthala
On Aug 5, 6:41 am, koranthala  wrote:
> Hi,
>    I am creating the first GUI app (wxPython based) using Twisted.
>    I am facing an issue which I cannot seem to solve/understand due
> to lack of trace or anything.
>    I had a big app written on twisted and now I am creating a login
> screen to the app.
>    The app used to work without any issues. I added the login screen
> and the login screen comes up.
>     But then everything freezes up. I have to force quit the python
> application to get anything back. Can anyone help me solve it?
>    The code is as follows:
>
> import wx
> import os
> import logging
>
> from twisted.internet import wxreactor
> wxreactor.install()
> from twisted.internet import reactor #Called only after
> wxreactor.install()
> from twisted.internet.task import LoopingCall
>
> import clientapp
>
> def opj(path):
>     """ Convert paths to the platform-specific separator """
>     st = apply(os.path.join, tuple(path.split('/')))
>     if path.startswith('/'):
>         st = '/' + st
>     return st
>
> class APPApp(wx.App):
>     def OnInit(self):
>         self.frame = APPFrame(None, -1, " APP Login", size=(200, 150))
>         self.panel = APPPanel(self.frame,-1)
>         client = clientapp.setup_app()
>         call = LoopingCall(client.run)
>         call.start(.51)
>         return True
>
> def main():
>     app = APPApp(0)
>     reactor.registerWxApp(app)
>     try:
>         reactor.run()
>     except StandardError:
>         raise
>
> class APPFrame(wx.Frame):
>     def __init__(self, parent, id, title, size=None):
>         wx.Frame.__init__(self, parent, id, title,
>                           size=size, pos=wx.Point(400, 300))
>         icon = self.get_icon()
>         self.SetIcon(icon)
>         self.Show(True)
>         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
>         self.Bind(wx.EVT_ICONIZE, self.OnIconify)
>
>     def on_login_click(self, username, password):
>         self.Hide()
>
>     def OnCloseWindow(self, event):
>         event.Skip()
>
>     def OnIconify(self, event):
>         self.Hide()
>
>     def get_image(self):
>         img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO)
>         return img
>
>     def get_icon(self):
>         img = self.get_image()
>         icon = wx.IconFromBitmap(img.ConvertToBitmap() )
>         return icon
>
> if __name__ == '__main__':
>     main()

Sorry for spamming this group.
I found that this was due to a interaction with pyHook and the
wxPython GUI.
I havent solved it, but atleast it is not due to twisted and wxPython.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python docs disappointing - group effort to hire writers?

2009-08-08 Thread koranthala
On Aug 7, 5:15 pm, Dave Angel  wrote:
> alex23 wrote:
> > Paul Rubin  wrote:
>
> >> The PHP docs as I remember are sort of regular (non-publically
> >> editable) doc pages, each of which has a public discussion thread
> >> where people can post questions and answers about the topic of that
> >> doc page.  I thought it worked really well.  The main thing is that
> >> the good stuff from the comment section gets folded into the actual
> >> doc now and then.
>
> > I'd still like to see this kept out of the official docs as much as
> > possible, mostly for reasons of brevity & clarity. I think the
> > official docs should be considered definitive and not require a
> > hermeneutic evaluation against user comments to ensure they're still
> > correct...
>
> > How about a secondary site that embeds the docs and provides
> > commenting functionality around it? That's certainly a finitely scoped
> > project that those with issues about the docs could establish and
> > contribute to, with the possibility of it gaining official support
> > later once it gains traction.
>
> I share your concern about unmonitored comments.  However, it seems a
> useful possibility would be for the "official" pages to each have
> specially-marked links that possibly lead to such user comments.  
> Clearly they'd have to marked carefully, so that naive users don't
> confuse the two.  But otherwise, it feels like a good idea.
>
> In my case, I usually access the docs via the Windows help file.  So
> it'd be quite easy for me to recognize that once I've gotten to a
> browser page, I'm not in Kansas any more.  But that could be also
> accomplished by having a very different stylesheet for the user comments
> page.
>
> DaveA

The best example that I have seen is djangobook.
The comment system in it is quite exquisite.
It would be good for the Python docs to have such a mechanism.
-- 
http://mail.python.org/mailman/listinfo/python-list


Twisted - how to get text for HTTP error responses

2009-08-09 Thread koranthala
Hi,
   I am writing a HTTP client in Twisted. The client contacts the
server, and any errors in the sent messages will be returned back to
the client in 400 message. The reason for failure at the server is
sent as the text in the 400 message. I tried the same using the
browser, and I can see the error text (the text might be like - 'Item
X not found in DB').
   The client is supposed to use this text and calculate the next
messages to be sent to the server. But, I cannot seem to find a
mechanism to get the response text from the errback. I went through
failure.py, but I couldnt find a way to do it.
   Ex:
I send a data to the server as so
d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
postdata=form))
yield d
try:
   reply = d.getResult()
   success(reply)
except Error, failure:
   failure(failure)

Now, inside failure method, I was unable to print the text out - say
'Item X not found in DB'.
Is it possible using Twisted? If so, how can it be done?

Thanks in Advance
K

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


Re: can python make web applications?

2009-08-23 Thread koranthala
On Aug 23, 8:12 pm, Deep_Feelings  wrote:
> can python make powerfull database web applications that can replace
> desktop database applications? e.g: entrprise accounting
> programs,enterprise human resource management programs ...etc

Very much so.
The web frameworks, Django & TurboGears are quite powerful and can be
used to do what you just now mentioned.
Check out Django - esp if the application is database centric. It has
very good documentation and a free online book - djangobook.
-- 
http://mail.python.org/mailman/listinfo/python-list


executable path finding

2009-08-31 Thread koranthala
Hi,
I am creating a python application using py2exe. I am facing a
problem which I am not sure how to solve.
The application contains many other files associated with it -
like icons, config files etc. The executable can be in any directory.
If the user creates a shortcut to the executable to run in desktop,
the program fails - saying that the icon image cannot be found. But I
can run the application properly, if I run it from application
directory - where all the other icons, config files etc are kept.
How is such issues usually solved? I do not want to hardcode the
paths of icons and store the icons in those paths. I guess, we can
change the directory to the application directory before running the
application. (in __init__.py ???) But how do we find the current
directory in that case? I am completely at sea in solving this.
This looks to be a very common issue. How is this usually solved?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: executable path finding

2009-08-31 Thread koranthala
On Aug 31, 9:07 pm, "Diez B. Roggisch"  wrote:
> koranthala wrote:
> > Hi,
> >     I am creating a python application using py2exe. I am facing a
> > problem which I am not sure how to solve.
> >     The application contains many other files associated with it -
> > like icons, config files etc. The executable can be in any directory.
> > If the user creates a shortcut to the executable to run in desktop,
> > the program fails - saying that the icon image cannot be found. But I
> > can run the application properly, if I run it from application
> > directory - where all the other icons, config files etc are kept.
> >     How is such issues usually solved? I do not want to hardcode the
> > paths of icons and store the icons in those paths. I guess, we can
> > change the directory to the application directory before running the
> > application. (in __init__.py ???) But how do we find the current
> > directory in that case? I am completely at sea in solving this.
> >     This looks to be a very common issue. How is this usually solved?
>
> You can get the location of a module via
>
>  module.__file__
>
> This can be used to find a file relative to e.g. the toplevel module/package
> of your application.
>
> The pkg_resources-module of setuptools encapsulates that even into a stream
> and file-name api.
>
> Diez

Thank you Diez. It was what I was looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Entry Level Python Jobs

2009-09-03 Thread koranthala
On Sep 3, 9:19 am, steve  wrote:
> On 09/03/2009 09:36 AM, steve wrote:
>
> > Hi Jonathan,
> > [...snip...]
>
> I feel stupid replying to my own post but just one more thing i thought about
> mentioning but forgot to add:
> - Look at your Liberal Arts major as an advantage. Every field has a 
> 'computing
> gap' that needs to be filled but cannot be done because they aren't any too 
> many
> good people who have the relevant cross-domain knowledge. For instance, one of
> the reasons I think this month's sourceforge.net project of the month is 
> really
> great is because the lead dev. has a CS degree and is listed as being a 
> medicine
> student:http://sourceforge.net/community/potm-200909/
>
> So, look for these gaps in your domain which can be filled using your 
> technical
> knowledge.
>
> again, ..
>
>
>
> > Wish you the best,
> > regards,
> > - steve
>
> --
> random non tech spiel:http://lonetwin.blogspot.com/
> tech randomness:http://lonehacks.blogspot.com/
> what i'm stumbling into:http://lonetwin.stumbleupon.com/

Also, I think topcoder.com is a good place for him. I have not used
them much, but their business plan -- of asking medium to difficult
questions every week, and contacting people who solves them with jobs
-- is quite sound.
Try that too.
-- 
http://mail.python.org/mailman/listinfo/python-list


HTTPS on Twisted

2009-09-06 Thread koranthala
Hi,
   For a financial application,  I am creating a python tool which
uses HTTPS to transfer the data from client to server. Now, everything
works perfectly, since the SSL support comes free with Twisted.
   I have one problem though. As an upgrade, now, I have to send many
requests as the same client to the server. Many in the range of >10
msgs every second. Now, I am creating a separate TCP connection for
each and am sending the data. Is it possible to create just one SSL
and TCP connection and send each message over that using Twisted?
   I read through Twisted, but was unable to come up with the answer
though. Even if I have to use multiple TCP connections, is it possible
to have just one SSL connection?

   I think persistent connections should be possible for TCP, but is
it possible is Twisted?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTTPS on Twisted

2009-09-07 Thread koranthala
On Sep 6, 7:53 pm, koranthala  wrote:
> Hi,
>    For a financial application,  I am creating a python tool which
> uses HTTPS to transfer the data from client to server. Now, everything
> works perfectly, since the SSL support comes free with Twisted.
>    I have one problem though. As an upgrade, now, I have to send many
> requests as the same client to the server. Many in the range of >10
> msgs every second. Now, I am creating a separate TCP connection for
> each and am sending the data. Is it possible to create just one SSL
> and TCP connection and send each message over that using Twisted?
>    I read through Twisted, but was unable to come up with the answer
> though. Even if I have to use multiple TCP connections, is it possible
> to have just one SSL connection?
>
>    I think persistent connections should be possible for TCP, but is
> it possible is Twisted?

Any comments on the same?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print without spaces?

2009-09-18 Thread koranthala
On Sep 18, 9:49 pm, "Andreas Tawn"  wrote:
> > Hi,
>
> > I don't want to print the space between 'a' and 'b'. Could somebody
> > let me know how to do it?
>
> > Regards,
> > Peng
>
> > $ python
> > Python 2.5.2 (r252:60911, May 21 2008, 10:08:24)
> > [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> print "a","b"
> > a b
>
> print "a" + "b"
>
> Cheers,
>
> Drea

What if I want to print 1 to 100 in a loop without spaces in between?
I think that is the OPs question.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question, how to double a variable

2009-09-22 Thread koranthala
On Sep 21, 1:27 am, daggerdvm  wrote:
>  Write the definition of a function  twice , that receives an  int
> parameter and returns an  int that is twice the value of the
> parameter.
>
> how can i do this

Please note that most mails here are humorous - as should be expected
for a language named after Monty Python.
So, please do not get angry and do take it the way it was intended.

The main problem that everybody sees is that the code you asked is
extremely simple. This causes others to think that you have not
invested any time in getting a solution yourself. Most of us here are
>30 years old, and we know from experience that if one does not invest
time and energy in solving issues when we are young, it eventually
leads us to a very unrewarding and unhappy life in the end.

So, even though it looks to you that people are mocking you, it is not
exactly the case. If you do try to get a solution and is unable to do
so, then I am 100% sure that many many people would have provided you
the answer or the way to do so.

Also, since you are young (presumably), it would be good to understand
that if you get it into a flamewar (email or in life), it tends to end
bad for you in the end. Esp, MRAB, Carl Banks, Steven D'Aprano, Tim
Chase etc , whom you flamed, are amongst the most respected people in
this group.
-- 
http://mail.python.org/mailman/listinfo/python-list


Screencapture of a video

2009-09-24 Thread koranthala
Hi,
I was trying to capture the video which I was viewing using
Imagegrab module in PIL (windows). But, I found that the video was not
captured at all. A quick googling tells me that it is because the
windows does not have access to the viewing area.
   Is there any way I can capture the video? It will be very helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Screencapture of a video

2009-09-24 Thread koranthala
On Sep 24, 12:38 pm, koranthala  wrote:
> Hi,
>     I was trying to capture the video which I was viewing using
> Imagegrab module in PIL (windows). But, I found that the video was not
> captured at all. A quick googling tells me that it is because the
> windows does not have access to the viewing area.
>    Is there any way I can capture the video? It will be very helpful.

Any solutions? I found that basic printscreen can capture the video in
XP. In that case, it should be possible, I guess. Can anyone give me
some pointers?
-- 
http://mail.python.org/mailman/listinfo/python-list