Re: Using python to deploy software

2005-01-05 Thread Anand
Hmm... did not watch this thread.

Regarding sharing code, well I am sure you will be able to quickly
produce some working client/server using Pyro for doing your task. Pyro
makes it very easy to do RMI due to its network broadcast way of
querying the name server.

If you are not able to make any headway, mail me and I can give you his
email address.

Rgds

-Anand

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


Re: Cookbook 2nd ed Credits

2005-01-06 Thread Anand
Yes, such a list is available.

I have uploaded a tentative list of contributors at
http://harvestman.freezope.org  . The original list is courtesy Alex.

For the impatient, here are the direct links...

List of first authors:
http://harvestman.freezope.org/cookbook/credau.html
List of all authors:
http://harvestman.freezope.org/cookbook/creds.html
Hope this helps!

Regards

-Anand

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


Contributor's List

2005-01-06 Thread Anand
A list of contributors to Python Cookbook (Second Edition) is available
at the following links. Original list courtesy Alex Martelli.

Since the book is not yet in print, the lists are still tentative
because of potential last minute editing changes.

List of first authors
o http://harvestman.freezope.org/cookbook/credau.html

List of all authors
o http://harvestman.freezope.org/cookbook/creds.html   


-Anand

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


Re: Contributor's List

2005-01-06 Thread Anand
Please direct all queries to the Cookbook editors...!

Thanks

-Anand

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


Re: Contributor's List

2005-01-06 Thread Anand
Please direct all queries to the Cookbook editors!

Thanks

-Anand

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


Re: Contributor's List

2005-01-06 Thread Anand
Please direct any query to the Cookbook editors.

Thanks

-Anand

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


Re: Contributor's List

2005-01-06 Thread Anand
I have no idea. I am just another contributor like you. Just doing a
service to the Python community by providing the list at my site.
However, I am not responsible
for its content. Please direct your queries to the editors, if any.
Thanks

-Anand

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


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Anand
How about...

import re
content = re.sub('<([^!(a>)]([^(/a>)]|\n)*)>', '', content)
Seems to work for me.

HTH

-Anand

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


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Anand
I meant
content = re.sub ('<[^!(a>)]([^>]|\n)*[^!(/a)]>', '', content)

Sorry for the mistake.
However this seems to also print tags like ,  etc
also.

-Anand

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


Porting from Python 2.3 to 2.4

2005-07-13 Thread Anand
Hi

   Are there any tools that would help in porting code from
Pyton 2.3 to 2.4 ? I have gone through the whatsnew documents
and created a document comparing Python 2.4 to 2.3. But so far
has not been able to find any tool that will signal code in
Python 2.3 that can cause errors in Python 2.4 .

rgds

-Anand

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


New Meetup Group

2004-12-28 Thread Anand
This is for Python enthusiasts in the city of Bangalore, the "Silicon
Valley of India".

I have started a new meetup group for Python programming enthusiasts in
the city.
The group's home page can be accessed at http://python.meetup.com/158/
.

If you are a Bangalorean and also a Python enthusiast, consider joining
the group. Also, spread the word around.

Happy New Year!

-Anand

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


Re: Using python to deploy software

2004-12-28 Thread Anand
I haven't but one of my friends have used Pyro (Python Remote Objects)
to do so.

You basically need to write a custom Pyro server and run it on a
central machine. Your pyro clients can be installed on the machines
where the software need to be installed.

For more details and similar ideas refer the project page of pyro at
http://pyro.sourceforge.net/projects.html .

-Anand

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


Re: Harvestman install not working

2005-04-06 Thread Anand
Hi

Latest version of py2exe does not support the option
--force-imports anymore I think. You can edit the .bat file to remove
that option. It should work.

-Anand

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


Re: Calling a list of functions

2015-12-13 Thread Anand
On Sunday, December 13, 2015 at 9:26:52 AM UTC-8, Ganesh Pal wrote:
> Hi Team,
> 
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
> 
> 
> Sample code :
> 
> def print1():
> print "one"
> 
> def print2():
> print "two"
> 
> def print3():
> print "three"
> 
> print_test = [print1(),print2(),print3()] //calling the function
> 
> for test in range(len(print_test)):
>   try:
>   print_test[test]
>   except AssertionError as exc:
> 
> 
> Regards,
> Ganesh




def print1(): 
 print "one" 
 
 def print2(): 
> print "two" 
> 
> def print3(): 
> print "three" 
> 
> print_test = [print1(),print2(),print3()] //calling the function 


If the idea is to have a 'pointers to function array' (as in C), you can do 
this:

fun_arr=[print1,print2,print3]
# Execute now
[ f() for f in fun_arr ]


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


Re: Localized Type Inference of Atomic Types in Python

2014-02-15 Thread anand
On Wednesday, May 25, 2005 4:41:34 AM UTC+5:30, Brett C. wrote:
> My thesis, "Localized Type Inference of Atomic Types in Python", was
> successfully defended today for my MS in Computer Science at the California
> Polytechnic State University, San Luis Obispo.  With that stamp of approval I
> am releasing it to the world.  You can grab a copy at
> http://www.drifty.org/thesis.pdf .


Hi,
  This link seems to be down. Can you point us to some current link? Am trying 
to contribute to https://code.google.com/p/py2c/ and reading up on type 
inference for python.

Thanks and Regards,
Anand 

> 
> For those of you who attended my talk at PyCon 2005 this is the thesis that
> stemmed from the presented data.
> 
> As of this exact moment I am not planning to release the source code mainly
> because it's a mess, I am not in the mood to pull the patches together, and 
> the
> last thing I want happening is people finding mistakes in the code.  =)  But 
> if
> enough people request the source I will take the time to generate a tar.bz2
> file of patches against the 2.3.4 source release and put them up somewhere.
> 
> Below is the abstract culled directly from the thesis itself.
> 
> -Brett C.
> 
> -
> ABSTRACT
> 
> Types serve multiple purposes in programming.  One such purpose is in 
> providing
> information to allow for improved performance.  Unfortunately, specifying the
> types of all variables in a program does not always fit within the design of a
> programming language.
> 
> Python is a language where specifying types does not fit within the language
> design.  An open source, dynamic programming language, Python does not support
> type specifications of variables.  This limits the opportunities in Python for
> performance optimizations based on type information  compared to languages 
> that
> do allow or require the specification of types.
> 
> Type inference is a way to derive the needed type information for 
> optimizations
> based on types without requiring type specifications in the source code of a
> program.  By inferring the types of variables based on flow control and other
> hints in a program, the type information can be derived and used in a
> constructive manner.
> 
> This thesis is an exploration of implementing a type inference algorithm for
> Python without changing the semantics of the language.  It also explores the
> benefit of adding type annotations to method calls in order to garner more 
> type
> information.
-- 
https://mail.python.org/mailman/listinfo/python-list


How To Read Excel Files In Python?

2005-12-13 Thread Anand
Hello,

Can I get some help on how to read the excel files using python?

from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open("Read.xls")
xlSht = xlWb.WorkSheets(1)

But sadly, I am unable to proceed further about how to read the cells of the
worksheet of my excel file!

Thanks for your help and cooperation.

Best regards,
Anand


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


Columns and Rows in Excel

2005-12-18 Thread Anand
Greetings,

How can I find the number of active columns and rows used in an excel work
sheet?
What I mean is how can i find the last column and row or cell position,
where the data is stored in an excel sheet?

A code snippet would be of great help.

Thanks for your cooperation and help.

Best regards,
Anand



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


Re: Columns and Rows in Excel

2005-12-19 Thread Anand
Greetings,

The worksheet is currently opened in Excel.
And I want to read the data from the excel worksheet.
Instead of looping through the entire worksheet, I want to limit the looping
to the rows and columns used so far!

Thanks and regards,
Anand

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Anand wrote:
>
> > Greetings,
> >
> > How can I find the number of active columns and rows used in an excel
work
> > sheet?
> > What I mean is how can i find the last column and row or cell position,
> > where the data is stored in an excel sheet?
>
> Is the worksheet currently open in Excel or OpenOffice,
> and you wish to query the application for that information?
>
> Or do you want to read the spreadsheet in from a file?
>
>
>
> -- 
> Steven.
>


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


Re: Guido at Google

2005-12-21 Thread Anand
This is very good news. I wish Guido all the best!

I wonder if this has got to do something with Microsoft developing
IronPython. Incidentellay it is reaching a 1.0 release pretty soon.
Perhaps Google has some cards up their sleeve. What other best way to
counter this than to hire the big fish himself ? :-)

-Anand

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


Re: Guido at Google

2005-12-22 Thread Anand
> It's like having James Bond as your very own personal body guard ;)

That is such a nice quote that I am going to put it in my email
signature ! :)

-Anand

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


Re: import

2006-07-05 Thread Anand

David Jackson wrote:

> Hi all,
>
> I'm a real beginner with python but have what I think is a simple question.
> I am writing some simple modules and would like to place them into a
> subdirectory.  But then I cannot seem to import them.  I have tried the
> following.
>
> I wrote a module called fibo.py with some definitions in it (one called
> fibo).  In the same directory, I wrote another file (test.py) and began with
> import fibo.  This worked fine and I was able to use the function fibo as
> fibo.fibo.  Then, I made a directory called test and placed the file fibo.py
> in this directory.  I also placed a blank file called _init_.py into this
> directory.  I went back to the original directory and tried to import
> test.fibo but this fails.  I get the following error message:
>
> Traceback (innermost last)
>   File "...test.py", line 1, in ?
> import test.fibo
>   File "...test.py", line 1, in ?
> import test.fibo
> ImportError: No module named fibo

python is trying to import fibo from test.py not test directory. since
you have both test.py and test directory, it is using the first one.
try to rename your directory name to something else and try. that
should work.

Also you should do 
   from test import fibo


Anand

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


Re: Generating multiple lists from one list

2006-07-05 Thread Anand
> p_code = ''
> for i,k in enumerate(ks):
> p_code += i*' ' + "for item%s in elts['%s']:\n" %(i,k)
> p_code += len(ks)*' '+'print ['+','.join([ "item%s" %i
> for i,k in enumerate(ks) ])+']'
>
> # print the code
> print p_code
>
> >for item0 in elts['a']:
> > for item1 in elts['b']:
> >  for item2 in elts['c']:
> >   for item3 in elts['d']:
> >print [item0,item1,item2,item3]
>
> # execute this code
> exec p_code

This is not very nice. you can use recursion instead of generating
code.

The following solution first divides the given list into groups based
on the first token and computes their cross product using recursion.

def get_groups(x):
"""Groups the elements of the list x using the first token of the
elment.
All elements are expected of the form "a.n".
for example:
>>> get_groups(["a.1", "b.2", "a.2"])
[["a.1", "a.2"], ["b.1"]]
"""
groups = {}

for item in x:
a, n = item.split('.')

if a not in groups:
groups[a] = []

groups[a].append(item)

keys = groups.keys()
keys.sort()

return [groups[k] for k in keys]

def cross_product(items):
"""
computes cross product of the list of lists.
example:
>>> cross_product([["a", "b"], ["c"]])
[["a", "b"], ["a", "c"]]
"""
if not items:
return [[]]

x = items[-1]
result = cross_product(items[:-1])

return [a + [b] for a in result for b in x]


x = ['a.1','b.3','b.4','c.2','c.6','d.3']

print cross_product(get_groups(x))

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


Re: Python framework questions

2006-07-05 Thread Anand

mp wrote:

> Hello, I have a couple general questions.
>
> First, how do most web frameworks serve html? I'm coding in python and
> I want to keep all my html seperate from my python stuff. I can serve
> these html files from a mysql database or just from the file system, do
> people use both these options? Are there other options?

most web frameworks generate html from some kind of templates.
templates for very much like html but you can substitute some text
dynamically at runtime. you may also be able to do conditionals and
loops inside templates.

if you want to get a feel of it, try web.py (http://webpy.org).  web.py
is a very simple and powerful web framework.

> Second, is a cgi-bin directory really necessary? Are there security
> issues with configuring Apache to allow cgi-bin execution in other
> directories?

i am not an apache expert.

but to the best of my knowledge, there should not be any problems. it
will be slower because for handling each request a new process has to
be created.

Anand

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


Python website bug: Wrong URL in http://www.python.org/download/releases/2.5/highlights/

2006-09-27 Thread Anand
The URL which links to "Whats New in Python 2.5" in the following text
is wrong.

"Here are some of the (subjective) highlights of Python 2.5. More
detail on almost all of the new features can be found in the document
What's New In Python 2.5"

It links to http://docs.python.org/dev/whatsnew/ whereas it should
point to http://docs.python.org/whatsnew/whatsnew25.html instead.

I tried to report the bug in python.org using
http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets but since I
dont have a Trac login there, I am reporting it here. Python.org
webmaster, please consider this a bug report.

Thanks

-Anand

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


How To Call A DLL?

2006-02-13 Thread Anand
Greetings,

Can I get a code snippet of how to call a DLL and it's functionalities from
Python?

Thanks for your help.

Best regards,
Anand


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


File Name Format

2007-05-08 Thread Anand
Greetings,

How do I convert programmatically the file names from WIN32 to UNIX format?

A code snippet would be of great help.
We are new to python! :)

Thanks.
Best regards,
Anand


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


Inserting an element into existing xml file

2007-09-25 Thread Anand
Hi,

I'm new to Python. we are using python2.4.

I wanted to insert an element into an existing xml file. Can anyone
help me with this?
I've seen lxml and elementTree in python2.5 has some API's to insert
into existing xml file.
We cant use python 2.5 due to some limitations. So how can we do it in
2.4?

Thanks in Advance,
Anand

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


Re: Inserting an element into existing xml file

2007-09-25 Thread Anand
On Sep 25, 3:20 pm, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Anand wrote:
> > I'm new to Python. we are using python2.4.
>
> > I wanted to insert an element into an existing xml file. Can anyone
> > help me with this?
> > I've seen lxml and elementTree in python2.5 has some API's to insert
> > into existing xml file.
> > We cant use python 2.5 due to some limitations. So how can we do it in
> > 2.4?
>
> Install lxml and read the tutorial. It should be easy to grasp, as the API is
> very simple.
>
> http://codespeak.net/lxml/tutorial.htmlhttp://codespeak.net/lxml/tutorial.html#elements-are-lists
>
> It's compatible to ElementTree, which you can also install on Python 2.4 (it's
> what later became part of Python 2.5).
>
> Stefan


Hi Stefan,

First of all thanks for your reply.

I'm Afraid to say, I can't use lxml or elementTree as it requires many
legal approvals and there is high chances of not getting it through.
So Do you have any other method / idea just by using plain 2.4 to
accomplish the task

Cheers,
Anand

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


object inheritance

2007-10-26 Thread Anand
I am trying to implement some kind of object inheritance. Just like
one class can extend from another, I want to do the same on objects
dynamically.

I just thought that I can share my excitement here.

Suppose there are classes A and B and their instances a and b.

class A:
def foo(self): self.say('foo')
def say(self, msg):
print 'a.say', msg

class B:
def say(self, msg):
print 'b.say', msg

a = A()
b = B()

I want b to inherit the behavior of a.

>>> b.extend_from(a)
>>> b.foo()
b.say foo

I looked around and found that some people talked about similar ideas,
but didn't find any concrete implementation.

I came up with the following implementation using meta-classes.

class ExtendMetaClass(type):
def __init__(cls, *a, **kw):
# take all attributes except special ones
keys = [k for k in cls.__dict__.keys() if not
k.startswith('__')]
d = [(k, getattr(cls, k)) for k in keys]

# remove those attibutes from class
for k in keys:
delattr(cls, k)

# remember then as dict _d
cls._d = dict(d)

def curry(f, arg1):
def g(*a, **kw):
return f(arg1, *a, **kw)
g.__name__ = f.__name__
return g

def _getattr(self, name):
"""Get value of attribute from self or super."""
if name in self.__dict__:
return self.__dict__[name]
elif name in self._d:
value = self._d[name]
if isinstance(value, types.MethodType):
return curry(value, self)
else:
return value
else:
if self._super != None:
return self._super._getattr(name)
else:
raise AttributeError, name

def __getattr__(self, name):
"""Returns value of the attribute from the sub object.
If there is no sub object, self._getattr is called.
"""
if name.startswith('super_'):
return self._super._getattr(name[len('super_'):])

if self._sub is not None:
return getattr(self._sub, name)
else:
return self._getattr(name)

def extend_from(self, super):
"""Makes self extend from super.
"""
self._super = super
super._sub = self

cls.__getattr__ = __getattr__
cls._getattr = _getattr
cls._super = None
cls._sub = None
cls.extend_from = extend_from

class Extend:
__metaclass__ = ExtendMetaClass
def __init__(self, super=None):
if super:
self.extend_from(super)

And the above example becomes:

class A(Extend):
def foo(self): self.say('foo')
def say(self, msg):
print 'a.say', msg

class B(Extend):
def say(self, msg):
print 'b.say', msg
# self.super_foo calls foo method on the super object
self.super_say('super ' + msg)

a = A()
b = B()

>>> b.extend_from(a)
>>> b.foo()
b.say foo
a.say super foo

There are one issue with this approach. Once b extends from a,
behavior of a also changes, which probably should not. But that
doesn't hurt me much.

Any comments?

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


Re: object inheritance

2007-10-26 Thread Anand
On Oct 26, 5:31 pm, "Pradeep Jindal" <[EMAIL PROTECTED]> wrote:
> Can you tell any specific use case for doing this?

I have many implementaions of a db interface.

SimpleDB - simple implementation
BetterDB - optimized implementation
CachedDB - an implementation with caching of queries
RestrictedDB - implementation with permissions

Now, I want to combine these implementations and use.
Typical use case scenarios are:

db = RestrictedDB(CachedDB(SimpleDB()))
db = RestrictedDB(SimpleDB())
db = RestrictedDB(BetterDB())
db = RestrictedDB(CachedDB(BetterDB())
db = CachedDB(SimpleDB())
etc..



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


Re: python in academics?

2007-10-30 Thread Anand
On Oct 30, 6:22 pm, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
> On Oct 29, 10:39 pm, sandipm <[EMAIL PROTECTED]> wrote:
>
> > seeing posts from students on group. I am curious to know, Do they
> > teach python in academic courses in universities?
>
> This came up a while back. See:
>
> http://tinyurl.com/2pjjua
>
> If that doesn't work, search the Google group for "Python taught in
> schools"
>
> rd

Here is another interesting article "Algorithm Education in Python":

http://www.ece.uci.edu/~chou/py02/python.html


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


Re: object inheritance

2007-10-30 Thread Anand
On Oct 28, 1:16 am, Pradeep Jindal <[EMAIL PROTECTED]> wrote:
> On Friday 26 Oct 2007 6:21:57 pm Anand wrote:
>
>
>
> > On Oct 26, 5:31 pm, "Pradeep Jindal" <[EMAIL PROTECTED]> wrote:
> > > Can you tell any specific use case for doing this?
>
> > I have many implementaions of a db interface.
>
> > SimpleDB - simple implementation
> > BetterDB - optimized implementation
> > CachedDB - an implementation with caching of queries
> > RestrictedDB - implementation with permissions
>
> > Now, I want to combine these implementations and use.
> > Typical use case scenarios are:
>
> > db = RestrictedDB(CachedDB(SimpleDB()))
> > db = RestrictedDB(SimpleDB())
> > db = RestrictedDB(BetterDB())
> > db = RestrictedDB(CachedDB(BetterDB())
> > db = CachedDB(SimpleDB())
> > etc..
>
> I agree with Duncan. According to me, this should be called Delegation rather
> than inheritance. And delegation should work without any conflicts of
> identifier names and all that. I think, it should be all about several
> objects implementing a protocol (interface) and that should work cleanly.

I don't think so. It is not as simple as delegation.

In the example that I gave previously, call to self.say in A.foo
calls B.say not A.say, which I think is not possible with delegation.




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


Re: object inheritance

2007-10-30 Thread Anand

> No, that is an argument for multiple-inheritance, mixin classes etc. You
> know when constructing the object what behaviour you want it to have. It
> isn't an argument for changing the behaviour of an existing object
> dynamically.


Partially true. I don't want to change the behavior of an exiting
object. I know what behavior I want to have at the time of creating.
This can be achieved by creating classes dynamically by parameterizing
the base class, which I thought is ugly.

>
> for an example where it is useful to extend the behaviour of objects have a
> look at Zope3 interfaces and adaptors: an object can be defined to
> implement one or more interfaces, and you can associate additional
> interfaces with objects at runtime. Sometimes an object will implement an
> interface directly, but often the implementation is taken out into a
> separate 'adaptor' class. Whenever you want to use a specified interface on
> an object you simply use the interface class as a constructor on the
> object, and that might find the appropriate adapter or it might just return
> the original object if the interface is provided directly.
>
> e.g. seehttp://plone.org/documentation/tutorial/five-zope3-walkthrough

Interesting!

> Note that this is very different than the forwarding mechanism which
> started this thread: when you use an adaptor you get something which
> implements just the specified interface, you don't have to worry about
> conflicting names for methods or attributes. Also you can have a common
> interface associated with objects which have completely different adapters
> implementing that interface.

It is not a simple one-way forwarding mechanism. It is two-way.

An example:

class SimpleDB(Extend):
def withID(self, id):
# do query

def withIDs(self, ids):
return [self.withID(id) for id in ids]

class CachedDB(Extend):
def withID(self, id):
if id not in self.cache:
self.cache[id] = self.super_withID(id)
return self.cache[id]


db = CachedDB(SimpleDB())

When I call db.withIDs, it should make use of the cache, which I think
is not possible with a simple forwarding mechanism.

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


Re: object inheritance

2007-10-31 Thread Anand
On Oct 31, 9:57 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 31 Oct 2007 00:36:34 -0300, Anand <[EMAIL PROTECTED]> escribió:
>
> >> No, that is an argument for multiple-inheritance, mixin classes etc. You
> >> know when constructing the object what behaviour you want it to have. It
> >> isn't an argument for changing the behaviour of an existing object
> >> dynamically.
> > Partially true. I don't want to change the behavior of an exiting
> > object. I know what behavior I want to have at the time of creating.
> > This can be achieved by creating classes dynamically by parameterizing
> > the base class, which I thought is ugly.
>
> If you know at compile time which features you want, you can use multiple
> inheritance to define the new class.
> If you only know the set of clases to mix at run time, you can dinamically
> create new classes with 'type':
>
> newclass = type('newclass', (CachedDB, SimpleDB), {})
> db = newclass()
> db.withIDs will call CachedDB.withID, as you want.

Interesting.

CachedDB.withID should call withID from its super class (here
SimpleDB), when it is not in cache. How to do that?


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

Re: Method needed for skipping lines

2007-10-31 Thread Anand
On Nov 1, 5:04 am, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 31, 5:02 pm, Gustaf <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > Just for fun, I'm working on a script to count the number of lines in 
> > source files. Some lines are auto-generated (by the IDE) and shouldn't be 
> > counted. The auto-generated part of files start with "Begin VB.Form" and 
> > end with "End" (first thing on the line). The "End" keyword may appear 
> > inside the auto-generated part, but not at the beginning of the line.

I think we can take help of regular expressions.

import re

rx = re.compile('^Begin VB.Form.*^End\n', re.DOTALL|re.MULTILINE)

def count(filename)
text = open(filename).read()
return rx.sub('', text).count('\n')

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


Re: permuting over nested dicts?

2007-11-01 Thread Anand
On Oct 31, 10:21 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
> Hoi,
>
> I have the following data structure (of variable size actually, to make
> things simple, just that one):
> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> This can be read as a dict of possibilities: The entities 'a' and 'b' have
> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> 3. Does anybody know a convenient (and fast) way to permute over all
> possible nested dicts like
> {'a': {'x':1, 'y':4},
>  'b': {'x':7, 'y':10}}
> and
> {'a': {'x':2, 'y':4},
>  'b': {'x':7, 'y':10}}
> and so forth?
>
> Any link or snippet is appreciated.
>

This code works for dictionaries of any nested level.


def combine(key, value, permutations):
"""Adds key-value pair to every dictionary in the permutations.
If value is a list, then every key-element pair is added to every
permutation.
>>> list(combine('a', 1, [{}]))
[{'a': 1}]
>>> list(combine('a', [1, 2], [{}]))
[{'a': 1}, {'a': 2}]
>>> list(combine('a', 1, [{'b': 1}, {'b': 2}]))
[{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]
>>> list(combine('a', [1, 2], [{'b': 1}, {'b': 2}]))
[{'a': 1, 'b': 1}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a':
2, 'b': 2}]
"""
for p in permutations:
if isinstance(value, list):
for v in value:
q = p.copy()
q[key] = v
yield q
else:
p[key] = value
yield p


def permute(d):
"""
>>> list(permute({'x': [1, 2, 3]}))
[{'x': 1}, {'x': 2}, {'x': 3}]
>>> list(permute({'a': [1, 2], 'b': [3, 4]}))
[{'a': 1, 'b': 3}, {'a': 2, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2,
'b': 4}]
>>> list(permute({'a': {'x': [1, 2]}, 'b': [3, 4]}))
[{'a': {'x': 1}, 'b': 3}, {'a': {'x': 2}, 'b': 3}, {'a': {'x': 1},
'b': 4}, {'a': {'x': 2}, 'b': 4}]
"""
if not d:
return [{}]
else:
k, v = d.popitem()
if isinstance(v, dict):
v = list(permute(v))
return combine(k, v, permute(d))



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


Re: permuting over nested dicts?

2007-11-01 Thread Anand
On Nov 1, 2:12 pm, Anand <[EMAIL PROTECTED]> wrote:
> On Oct 31, 10:21 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hoi,
>
> > I have the following data structure (of variable size actually, to make
> > things simple, just that one):
> > d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
> >  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> > This can be read as a dict of possibilities: The entities 'a' and 'b' have
> > the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> > 3. Does anybody know a convenient (and fast) way to permute over all
> > possible nested dicts like
> > {'a': {'x':1, 'y':4},
> >  'b': {'x':7, 'y':10}}
> > and
> > {'a': {'x':2, 'y':4},
> >  'b': {'x':7, 'y':10}}
> > and so forth?
>
> > Any link or snippet is appreciated.
>
> This code works for dictionaries of any nested level.
>
> def combine(key, value, permutations):
> """Adds key-value pair to every dictionary in the permutations.
> If value is a list, then every key-element pair is added to every
> permutation.
> >>> list(combine('a', 1, [{}]))
> [{'a': 1}]
> >>> list(combine('a', [1, 2], [{}]))
> [{'a': 1}, {'a': 2}]
> >>> list(combine('a', 1, [{'b': 1}, {'b': 2}]))
> [{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]
> >>> list(combine('a', [1, 2], [{'b': 1}, {'b': 2}]))
> [{'a': 1, 'b': 1}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a':
> 2, 'b': 2}]
> """
> for p in permutations:
> if isinstance(value, list):
> for v in value:
> q = p.copy()
> q[key] = v
> yield q
> else:
> p[key] = value
> yield p
>
> def permute(d):
> """
> >>> list(permute({'x': [1, 2, 3]}))
> [{'x': 1}, {'x': 2}, {'x': 3}]
> >>> list(permute({'a': [1, 2], 'b': [3, 4]}))
> [{'a': 1, 'b': 3}, {'a': 2, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2,
> 'b': 4}]
> >>> list(permute({'a': {'x': [1, 2]}, 'b': [3, 4]}))
> [{'a': {'x': 1}, 'b': 3}, {'a': {'x': 2}, 'b': 3}, {'a': {'x': 1},
> 'b': 4}, {'a': {'x': 2}, 'b': 4}]
> """
> if not d:
> return [{}]
> else:
> k, v = d.popitem()
> if isinstance(v, dict):
> v = list(permute(v))
> return combine(k, v, permute(d))

better solution:

def permute(d):
def newdict(d, k, v):
d = d.copy()
d[k] = v
return d

permutations = [{}]
for key, value in d.items():
if isinstance(value, dict):
value = list(permute(value))
elif not isinstance(value, list):
value = [value]
permutations = [newdict(p, key, v) for p in permutations for v
in value]
return permutations

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


exec with custom dict

2008-06-21 Thread Anand

Hi,

I am trying to use exec with custom dict.
I am trying to print the value of variable x in 2 places. It is
printing it at the first place and failing at the second place.

class Env(dict):
def __getitem__(self, key):
return self.get(key, key)

code = """
print x
def f(): return x
"""

env = Env()
exec(code, env)
print env['f']()

Here is the output I'm getting.

x
Traceback (most recent call last):
  File "a.py", line 14, in 
print env['f']()
  File "", line 3, in f
NameError: global name 'x' is not defined

Can somebody explain me what is happening?

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


Re: py web-app-frameworks without a rdbms...

2006-03-22 Thread Anand

Try web.py. Very simple and powerful web framework.

http://webpy.org


-anand

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


multiple assignment

2006-03-22 Thread Anand

Suppose i have a big list and i want to take tke the first one and rest
of the list like car/cdr in lisp.
is there any easy way to do this in python?

Only way i know is

a = range(10)
x, y = a[0], a[1:]

In perl, it is possible to do multiple assignment like this

@a = (1, 2, 3);
($x, @y) = @a;

I find this is a good feature and missing in python.
Why can't python support something like this:

x, *y = a

* operator is used in the usual sence here.

This is not really a new concept to python, infact when calling a
function which takes variable  arguments, it is used in a similar way.
for example:

def f(x, *y): print x, y
f(1, 2, 3)

the argument passing here is very similar to the multiple assignment x,
*y = (1, 2, 3)

any comments?

-anand

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


Re: multiple assignment

2006-03-22 Thread Anand
> You're right, that would not be so far off.
> But then, the following should be also supported:
>
> *x, y = a # x, y = a[:-1], y = a[-1]
> x, *y, z = a # x, y, z = a[0], a[1:-1], a[-1]
>
> Of course, there can be only one variable with an asterisk.
> (But note that in the situation of a function taking parameters, that
> variable must always be the last.)

Same argument can be applied for functions also. whats wrong in having
some thing like this?

def f(x, *y, z): pass

I think there is a problem in both these cases.

> But I don't know if this is really useful enough...

I think it is really useful.
One which i encountered was there is a file where each line has tokens
separated by commas. First token is the id and i want to use it in a
special way.

Wouldn't it be nice to say

id, *tokens = line.split(',')

than

tokens = line.split(',')
id = tokens.pop(0)

- anand

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


Re: multiple assignment

2006-03-22 Thread Anand
>> Wouldn't it be nice to say
>> id, *tokens = line.split(',')
>
>
> id, tokens_str = line.split(',', 1)

But then you have to split tokens_str again.

id, tokens_str = line.split(',', 1)
tokens = tokens_str.split(',')

this is too verbose.

anand

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


porting maatkit to python?

2011-06-18 Thread anand jeyahar
Hi all,
   I have tried maatkit and was wondering whether it was worth porting
maatkit to python. I personally find perl clunky and think python codebase
would be easier to maintain, bugfix and enhance.
If there is a reasonable amount of interest i can start with some basic
functionality(will need to brainstorm on that too.).

Thanks and Regards,
==
Anand Jeyahar
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


python overloading

2011-06-24 Thread anand jeyahar
Not sure, this is the right place, redirect me if it's not.

I was curious about the functionoverloading(
http://svn.python.org/view/sandbox/trunk/overload/) and was trying to do a
svn checkout of the branch and failed. Is it restricted access for even
checkout? How do i get read-only access?

==
Anand Jeyahar
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call a function for evry 10 secs

2011-07-02 Thread anand jeyahar
 >
>  > Hi All,
> > I need to call a function for evry 10 secs
> > how can i achieve this in python
>
>
> import time
> while True:
>time.sleep(10)
>function()
>


Please don't reinvent the wheel...
Use the python apscheduler module.
http://packages.python.org/APScheduler/#installing-apscheduler


Thanks and Regards,
==
Anand Jeyahar
https://sites.google.com/site/<
https://sites.google.com/site/aangjie/home/quotes>
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie<https://sites.google.com/site/aangjie/home/quotes>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-16 Thread anand jeyahar
On Sun, Jul 17, 2011 at 08:39, Steven D'Aprano
 wrote:
>
> I have reluctantly come to do the same thing. There is a plethora of broken
> tools out there that don't handle tabs well, and consequently even though
> tabs for indentation are objectively better, I use spaces because it is
> less worse than the alternative.
>
> Victory of worse-is-better.
Here too. I prefer the 8-space tabs for the simplicity of the input
method. (even while deleting 1 keystroke will do)


>
>
> [...]
> > | Some would argue that allowing both tabs and spaces is freedom,
> > | however this line of reasoning is flawed. Allowing a programmer to
> > | format his code in way he pleases is bad, bad, bad. As a member of a
> > | community we must all format our code in the same manner.
> >
> > This leads me to think you're just trolling.
>
> Slow learner, huh? :)
>
> I'm not sure which is worse... that Rick is trolling, and we still give him
> the attention he craves, or that he honestly believes this crap.
>
> I suspect the later. I get the impression that he genuinely has so little
> self-awareness that he doesn't notice that for all his talk about FREEDOM,
> he's constantly trying to deny it to others by forcing them to do what he
> wants them to do.
(denying others freedom) Ha that he is.  But given, i sometimes do go
into these phases (complete and utter lack of self-awareness) i am not
complaining...

Despite all of that, i do believe it will be for the greater good, if
all of us *decide* to use 8-space tabs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Refactor/Rewrite Perl code in Python

2011-07-24 Thread Shashwat Anand
I am working with a huge codebase of Perl.
The code have zero documentation and zero unit-tests.
It seems like a huge hack.

The underlying database schema is horrid.
So I want to rewrite the whole of it in Python.

How do I start ?
The idea is to rewrite module by module.
But how to make sure code doesn't break ?
How can I import perl and python codes in each other ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Refactor/Rewrite Perl code in Python

2011-07-24 Thread Shashwat Anand
Thanks everyone for the insight.
I got the idea as to how and where to start.
Guess I need to work in Perl for now, so as to start the conversion process.
Regarding Tests, I had already started writing tests before posting.
Writing tests for every module will be a pain as well as a nice experience.

Thanks.
~Shashwat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idea for pure-python templates using AST.

2011-08-16 Thread anand jeyahar
Hi all,
   I did it. Finally managed to port mysqltuner.pl to python. Was a
real pain in the butt doing it from bottom up manually, without ever
really learing perl syntax. But i finally got it done. Now i need help
testing it. find it here.
 g...@github.com:anandjeyahar/mysqlDbAdmin-python.git.

Also i never really thought about design. Just blindly/mechanically,
translated from perl to python. So criticize and let me know how i can
improve this.

Thanks and Regards,
==
Anand Jeyahar
https://sites.google.com/site/anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
                  ~Bruce Lee

Love is a trade with lousy accounting policies.
                 ~Aang Jie




On Tue, Aug 16, 2011 at 18:02, aspineux  wrote:
> On Aug 16, 1:33 pm, "Paul Wray"  wrote:
>> Hello all
>>
>> Ive had what I think is a great idea for pure-python templates (I can almost
>> hear the groans, bear with me...)
>>
>> For the impatient, proof of concept is athttp://pastie.org/2379978
>> demonstrating simple substitution, balanced tags using context manager,
>> subtemplates,  and template inheritance.
>
> You code fail, see below for other comment
>
> Traceback (most recent call last):
>  File "Download/pastie-2379978.rb", line 108, in 
>    make_template(template1)
>  File "Download/pastie-2379978.rb", line 60, in make_template
>    ast.fix_missing_locations(astFromSrc)
>  File "/usr/lib/python2.6/ast.py", line 133, in fix_missing_locations
>    _fix(node, 1, 0)
>  File "/usr/lib/python2.6/ast.py", line 132, in _fix
>    _fix(child, lineno, col_offset)
>  File "/usr/lib/python2.6/ast.py", line 132, in _fix
>    _fix(child, lineno, col_offset)
>  File "/usr/lib/python2.6/ast.py", line 121, in _fix
>    if 'lineno' in node._attributes:
> AttributeError: 'arguments' object has no attribute '_attributes'
>
>
>
>
>>
>> I'm posting here to get opinions on:
>> * the merits of the idea, (or otherwise!)
>> * whether there are any established/mature templating systems that use this
>> approach, or whether its come up before,
>> * ideas for improvements and advice on other aspects such as sandboxing
>> * of course, to share the idea in case others want to use it
>
> This is very original ! First time I see it. I like it.
> But how to debug large template ?
> How to find/detect a missing  ?
> This is very important. This is one big advantage of Genshi over Kid
> How to report the correct error at the correct line ?
> How to find/get nice editor to edit large template ?
>
>
>>
>> Background: Ive been working on an application that recursively renders
>> html/xml documents from heterogenoeus trees, with separate classes for each
>> document component. First I built my own renderer but was dissatisfied with
>> the repetitive code. Then looked at Mako and Jinja, and used Jinja but was
>> still disatisfied, because I still needed a render method in each class to
>> do preparation, and also the template which was centrally managed by the
>> Jinja loader and environment. I found a way to call templates recursively
>> via Jinja filters, but was not sure that it wouldnt blow up in my face, so I
>> also had separate calls to render the children of each node, and then feed
>> the value to the parent template. I kept thinking that there must be a way
>> to get the brevity and clarity of declarative templates, plus the simplicity
>> of pure python loops, tests and function calls.
>>
>> The idea:
>> Python syntax allows a statement to be a bare literal or identifier. These
>> have no effect on the program.
>>
>> So the function below is legal python:
>>
>> def myFunc():
>>     'a'
>>     x = 45
>>     'b'; 'c'; x
>>
>> So is this (within the appropriate class context of course):
>>
>> def body(self, r):
>>         ''; self.heading; ''
>>         ''
>>         for itm in self.items:
>>             ''; itm; ''
>>         ''
>>
>> The idea is simply to use python ASTs to transform this code so that it
>> accumulates the values of the bare expressions.
>
> You could call it PHP :-)
>
>>
>> I think this give the best of both worlds - declarative syntax for the
>> template literals, but in a pure python context, giving you all the power of
>> python control statements, classe

python mysqltuner port

2011-08-16 Thread anand jeyahar
Hi all,
   Sorry for the repeat post. Had posted earlier in between an
irrelevant thread by accident.
> Hi all,
>   I did it. Finally managed to port mysqltuner.pl to python. Was a
> real pain in the butt doing it from bottom up manually, without ever
> really learing perl syntax. But i finally got it done. Now i need help
> testing it. find it here.
>  g...@github.com:anandjeyahar/mysqlDbAdmin-python.git.
>
> Also i never really thought about design. Just blindly/mechanically,
> translated from perl to python. So criticize and let me know how i can
> improve this.
>
> Thanks and Regards,
> ======
> Anand Jeyahar
> https://sites.google.com/site/anandjeyahar
> ==
> The man who is really serious,
> with the urge to find out what truth is,
> has no style at all. He lives only in what is.
>                   ~Bruce Lee
>
> Love is a trade with lousy accounting policies.
>                  ~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


PUT with proxy-support

2011-08-25 Thread Shashwat Anand
I want to make a PUT request.
I need some headers of my own ( certificates etc ) and I need to mandatorily
use a proxy.
Also the url is of the form http://www.xyz.com/abc and I don't have
permission to put data
on http://www.xyz.com while I do have permission to put data on
http://www.xyz.com/abc

I tried httplib, httplib2, urllib2 with no avail.
I managed to do this via command line curl:

$ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version:
1.0" -H
"CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
--proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"

Is there a way to do it in python apart from using command line curl in
python.
The machine is RHEL4 and is giving hard time installing pycurl.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 4:48 PM, Thomas Jollans  wrote:

> On 25/08/11 13:07, Shashwat Anand wrote:
> > I want to make a PUT request.
> > I need some headers of my own ( certificates etc ) and I need to
> > mandatorily use a proxy.
> > Also the url is of the form http://www.xyz.com/abc and I don't have
> > permission to put data
> > on http://www.xyz.com while I do have permission to put data
> > on http://www.xyz.com/abc
> >
> > I tried httplib, httplib2, urllib2 with no avail.
>
> What did you try? What problems did you run into?
>
> I'm sure there is a way in Python, and chances are you were already
> close to finding it -- show us what you tried, what actually happened,
> including any error messages in full, and what you wanted to happen.
>
> Thomas
>

Hi Thomas,
so one of my tries was:

import urllib
import urllib2
import httplib
import httplib2

url = 'http://alatheia.zenfs.com/testing/shashwat'
body_content = 'CONTENT GOES HERE'
proxy = 'ca-proxy.corp.xyz.com:3128'

params = {
'x-sws-version' : '1.0',
'x-sws-access' : 'public',
'User-Agent' : 'CacheSystem',
'Cache-Control' : 'public',
'Content-Type' : 'text/plain',
'App-Auth' :
'v=1;a=client.alatheia.prod;h=10.16.19.23;t=1316594650;s=AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--',
   }

httplib2.debuglevel=4
h = httplib2.Http(proxy_info = httplib2.ProxyInfo(3, '
ca-proxy.corp.xyz.com:3128', 3128))
resp, content = h.request(url, "PUT", body=body_content, headers = params)
print resp
print content

Output:

connect: (alatheia.zenfs.com, 80)
Traceback (most recent call last):
  File "test.py", line 29, in 
resp, content = h.request(url, "PUT", body=body_content, headers =
params)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1436, in request
(response, content) = self._request(conn, authority, uri, request_uri,
method, body, headers, redirections, cachekey)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1188, in _request
(response, content) = self._conn_request(conn, request_uri, method,
body, headers)
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line
1123, in _conn_request
conn.connect()
  File "/home/y/lib/python2.6/site-packages/httplib2/__init__.py", line 786,
in connect
self.sock.connect(sa)
  File "/home/y/lib/python2.6/site-packages/httplib2/socks.py", line 381, in
connect
self.__negotiatehttp(destpair[0], destpair[1])
  File "/home/y/lib/python2.6/site-packages/httplib2/socks.py", line 347, in
__negotiatehttp
raise HTTPError((statuscode, statusline[2]))
httplib2.socks.HTTPError: (403, 'Tunnel or SSL Forbidden')

The reason I can trace it is because,
I can use PUT on http://alatheia.zenfs.com/testing/shashwat but not on
http://alatheia.zenfs.com/ however host is resolved.
Again port 80 is used even when I use specific port (3128, in this case).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 4:48 PM, Max Countryman  wrote:

> Check out the python Requests module:
> http://docs.python-requests.org/en/latest/index.html
>
>
Python request module is not documented very well IMHO.
I tried to figure how to make PUT calls, how to add proxy, how to add
certificates in headers.
Did not managed to find all of it.
Am not sure is supports REST calls with proxy support.



> Sent from my iPhone
>
> On Aug 25, 2011, at 7:07, Shashwat Anand  wrote:
>
> I want to make a PUT request.
> I need some headers of my own ( certificates etc ) and I need to
> mandatorily use a proxy.
> Also the url is of the form <http://www.xyz.com/abc>http://www.xyz.com/abcand 
> I don't have permission to put data
> on  <http://www.xyz.com>http://www.xyz.com while I do have permission to
> put data on  <http://www.xyz.com/abc>http://www.xyz.com/abc
>
> I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
>
> $ curl http:/ <http://xyz.com/testing/shashwat/test.txt>
> xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version: 1.0" -H
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
> --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
>
> Is there a way to do it in python apart from using command line curl in
> python.
> The machine is RHEL4 and is giving hard time installing pycurl.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Shashwat Anand
On Thu, Aug 25, 2011 at 5:22 PM, Laszlo Nagy  wrote:

> **
>
>  I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
>
>  $ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H
> "sw-version: 1.0" -H
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
> --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
>
> If you can do it with command line curl then probably you can do it with
> pycurl.
>
> http://pycurl.sourceforge.net/
>

Yeah.
I tried that.
The system is RHEL 4.

So it gave me this error :
src/pycurl.c:42:20: Python.h: No such file or directory
src/pycurl.c:43:22: pythread.h: No such file or directory
src/pycurl.c:58:4: #error "Need Python version 2.2 or greater to compile
pycurl."
src/pycurl.c:61:4: #error "Need libcurl version 7.19.0 or greater to compile
pycurl."

Apparently we need python-devel package.
Following http://fedoraproject.org/wiki/EPEL/FAQ#howtouse I added EPEL
software repository.

sh-3.00$ yum list | grep -i python-dev
sh-3.00$ sudo yum -y install python-dev
Password:
Setting up Install Process
Setting up repositories
epel [1/1]
epel  100% |=| 3.8 kB00:00

Reading repository metadata in from local files
b1f7bfef07466e9561644aba7 100% |=| 841 kB00:06

epel  : ## 2583/2583
Added 2583 new packages, deleted 0 old in 4.51 seconds
Parsing package install arguments
No Match for argument: python-dev
Nothing to do

Turned out that python-curl is the required package which is already
installed.
Still no use.

sh-3.00$ yum list | grep -i python-curl
python-curl.x86_64   7.12.1-1.3.el4.rf  installed

sh-3.00$ python
Python 2.6.4 (r264:75706, Nov  9 2009, 16:32:06)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pycurl
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named pycurl
>>>

Tried installing via easy_install

sh-3.00$ sudo easy_install pycurl

Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir
/tmp/easy_install-2ZCa8v/pycurl-7.19.0/egg-dist-tmp-DyHFls
Using curl-config (libcurl 7.12.1)
src/pycurl.c:42:20: Python.h: No such file or directory
src/pycurl.c:43:22: pythread.h: No such file or directory
src/pycurl.c:58:4: #error "Need Python version 2.2 or greater to compile
pycurl."
src/pycurl.c:61:4: #error "Need libcurl version 7.19.0 or greater to compile
pycurl."
[... Error Clipped]
error: Setup script exited with error: command '/usr/bin/gcc' failed with
exit status 1



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


Re: PUT with proxy-support

2011-08-26 Thread Shashwat Anand
On Fri, Aug 26, 2011 at 3:15 PM, Laszlo Nagy  wrote:

> Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir
> /tmp/easy_install-2ZCa8v/**pycurl-7.19.0/egg-dist-tmp-**DyHFls
>
>> Using curl-config (libcurl 7.12.1)
>> src/pycurl.c:42:20: Python.h: No such file or directory
>> src/pycurl.c:43:22: pythread.h: No such file or directory
>> src/pycurl.c:58:4: #error "Need Python version 2.2 or greater to compile
>> pycurl."
>> src/pycurl.c:61:4: #error "Need libcurl version 7.19.0 or greater to
>> compile pycurl."
>> [... Error Clipped]
>> error: Setup script exited with error: command '/usr/bin/gcc' failed with
>> exit status 1
>>
> I'm not familiar with red hat. But looks like this is now a sysadmin
> problem. I could install pycurl under freebsd and ubuntu too.
>
> I have some code that might be able to PUT through a proxy for you. Please
> look at the attached file.
>
> You can setup a proxy this way:
>
> import MozzillaEmulator
> MozzillaEmulator.DEFAULT_**PROXIES = {
>
> 'http':'http://user:password@**proxy.host.com:3128
> ',
>
> 'https':'http://user:password@**proxy.host.com:3128
> ',
> }
>
> And here is how you use it:
>
> dl = MozillaEmulator.**MozillaEmulator()
> put_url = "http://some_url_to_put_to";
> headers = {'Content-Type':'application/**xml;charset=UTF-8'}
> data = open("some_file","rb").read()
> response =  dl.download(put_url,data,**headers,put_method=True)
>
> If you don't set the put_method flag, then it will POST instead. (But in
> that case, post data must be a valid post data field fields and values.) If
> you don't give post_data then it will GET. The PUT method was tested without
> a proxy, and the GET and POST methods were tested with and without proxy.
>
> Actually I have tried to do PUT through a proxy, but it didn't work. But it
> was a restriction on the proxy side. (As far as I can recall, the error
> message came from the proxy server, something about unsupported request?).
> So it *might* work for you, with the right proxy server that supports PUT
> requests.
>
> Also be aware that this version uses urllib2. Although it can use https
> protocol, it doesn't check the server's certificate.
>
>
>
Mozilla Emulator works like a charm.
Also managed to install pycurl and the same works too.

Thanks. :)


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


Re: packaging a python application

2011-08-28 Thread anand jeyahar
Hi all,
This is interesting. Do we have the distribute/setuptools equivalent of
postinstall (with ncurses interface) from Debian? My limited foray into
setuptools, indicate it doesn't have .
Is it a planned feature either? i would like to contribute in that case.

==
Anand Jeyahar
https://sites.google.com/site/<https://sites.google.com/site/aangjie/home/quotes>
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie<https://sites.google.com/site/aangjie/home/quotes>



On Sun, Aug 28, 2011 at 06:22, suresh  wrote:

> Hi
> I created a python application which consists of multiple python files and
> a configuration file. I am not sure, how can I distribute it.
>
> I read distutils2 documentation and a few blogs on python packaging. But I
> still have the following questions.
>
> 1. My package has a configuration file which has to be edited by the user.
> How do we achieve that?
>
> 2. Should the user directly edit the configuration file, or there would be
> an interface for doing it...?(I remember my sendmail installations in
> Debian/Ubuntu. It would ask a bunch of questions and the cfg file would be
> ready)
>
> I am just confused how to go about...
>
> thanks
> suresh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me understand this logging config

2011-08-30 Thread anand jeyahar
Hi,
   I took a look at the logging source code. getLogger checks for existing
loggers with the given name and if it doesn't creates one.



def getLogger(self, name):
"""
Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar.

If a PlaceHolder existed for the specified name [i.e. the logger
didn't exist but a child of it did], replace it with the created
logger and fix up the parent/child references which pointed to the
placeholder to now point to the logger.
"""
rv = None
_acquireLock()
try:
if name in self.loggerDict:
rv = self.loggerDict[name]
if isinstance(rv, PlaceHolder):
ph = rv
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupChildren(ph, rv)
self._fixupParents(rv)
else:
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupParents(rv)
finally:
_releaseLock()
return rv

==
Anand Jeyahar
https://sites.google.com/site/<https://sites.google.com/site/aangjie/home/quotes>
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie<https://sites.google.com/site/aangjie/home/quotes>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: Ice 2.0 released

2004-11-30 Thread Anand Hariharan
Marc Laukien <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> > I'm sure this is a wonderful thing, but your announcement gives absolutely
> > no clue as to what Ice is or what it is used for.
> > 
> > Please include an executive summary when you make an announcement like
> > this.
> 
> Sorry for the omission. Please see the summary below:
> 
(...)
> 
> Ice is free software, available with full source, and released under the 
> terms of the GNU General Public License (GPL). Commercial licenses are 
> available for customers who wish to use Ice for closed-source software."
> 

Interesting to see this blend of GPL and an alternative for
closed-source software.

Not totally unrelated, I saw this in your web-site (Ice vs CORBA
page):

No "Design by Committee" 
Ice was designed by a small group of dedicated and highly experienced
people.


Am interested to know, what "percentage" (*) of the code in your CVS
repository has been contributed by people other than the group
mentioned in the quote above?  Obviously, you do not allow anonymous
CVS write access.  Perhaps, one wishing to improve Ice (a freedom
granted by GPL) and who does not work for ZeroC has to mail his/her
improvements to your maintainers?

(*):  Percentage is a very nebulous term, I know.  For purposes of
answering the question, maybe you could resort to the
not-highly-meaningful number of LOC, and perhaps a word or two about
how Ice benefited from it.

- Anand

PS:  Please feel free to set FU-Ts as appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: Ice 2.0 released

2004-11-30 Thread Anand Hariharan
Marc Laukien <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> > 
(...)
> > Am interested to know, what "percentage" (*) of the code in your CVS
> > repository has been contributed by people other than the group
> > mentioned in the quote above?  Obviously, you do not allow anonymous
> > CVS write access.  Perhaps, one wishing to improve Ice (a freedom
> > granted by GPL) and who does not work for ZeroC has to mail his/her
> > improvements to your maintainers?
> > 
(...)
> 
> 100% of the Ice source code has been developed by ZeroC employees.
> 
> Note that this does of course not apply for third-party code that is 
> being used by Ice, such as BZIP2, Berkeley DB, OpenSSL, etc.
> 

Consider the *hypothetical* situation where an individual or a group
of people re-write large portions of Ice.  This could enhance the
value of Ice (obviously to some, if not all), or this could conflict
with the ideologies of Ice (again, not in everyone's point of view). 
How will ZeroC react to this?

I believe whichever road you take, ZeroC is going to find itself in
problems.  If ZeroC merges the changes made by this/these person(s),
how can ZeroC now sell it under a commercial license, as closed source
(violation of GPL)?  If you refuse to merge the changes, you have just
given them a strong impetus to fork.  History shows XEmacs and EGCS as
two such examples.

Guess what I am primarily interested in finding out is rooted in what
I said earlier:

> > Interesting to see this blend of GPL and an alternative for
> > closed-source software.

What were the ideas behind going the GPL way?  How did ZeroC plan on
benefiting from it?  Were there any qualms within ZeroC in going GPL?

Note that I am not saying GPL and commercial software don't go
together (I do believe though that LGPL and commercial software don't
go together).  I am well aware of Free software being "Free speech,
not free beer".

What if you did not provide Ice as a free download, but a price based
on your current licensing policy(*).  However, the download would give
one the complete source, and the freedom to modify and redistribute it
(at whatever price so long as the complete source code with the GPL
notice is released).
(*):  All of this is hypothetical.  Am not making a business
proposition here.

You do not, because that would discourage Ice from becoming
ubiquitous, from paving way for becoming a potential de-facto
standard.

Then, why not simply advertise Ice as being commercial (with unlimited
free trial plus source code)?  Doing so, would get you the extensive
peer review that you are currently benefitting from.  What do you gain
by going GPL?  The freedom to modify and/or redistribute is
(apparently) pretty restricted anyway.

> > PS:  Please feel free to set FU-Ts as appropriate.
> 
> What are FU-Ts?
> 

"Follow-up To:".  Most news clients will allow sending a post to
multiple groups, restricting any possible responses to certain groups
alone.  A poster who is replying can over-ride it, of course.

sincerely,
- Anand
-- 
http://mail.python.org/mailman/listinfo/python-list


C extension module causes bus error on Python exit

2007-01-30 Thread Anand Patil
Hi all,

I was referred to this list from python-help. I've written an extension 
module in C which contains several new types. The types can be 
instantiated, used, and deleted under Python 2.4.3  on OS X 10.4 without 
problems.

However, whenever I import the module Python tries to dereference a NULL 
pointer and crashes *at exit*, whether or not I've instantiated any of 
the types. I've searched for memory leaks with gc.get_objects and Mac 
OS's MallocDebug utility, but haven't found any evidence.

Has anyone run into a problem like this? Any help is greatly appreciated.

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


Questions about remembering and caching function arguments

2007-11-11 Thread Anand Patil
Hi all,

I have two questions about a class, which we'll call MyWrapperClass,
in a package to which I'm contributing.


1) MyWrapperClass wraps functions. Each instance has an attribute
called 'value' and a method called 'eval', which calls the wrapped
function. An instance D that depends on instances A, B and C can be
created as follows:

@mywrapperclass
def D(A, B, C):
return foo(A.value, B.value, C.value)

Now that D exists, the call D.eval() will work without any arguments
(D remembers that the arguments are A, B and C and passes their values
to foo). What is the standard terminology for such classes, and does
anyone know of a package that implements them in a nice way? (It's
easy enough to roll our own, but reading about other implementations
might give us good ideas).


2) D.eval() will frequently be called multiple times in succession
before A.value, B.value or C.value has had the chance to change. It
would be _extremely_ helpful to have D detect this situation and skip
recomputation. I'm looking for the fastest safe way to do this.
There's no restriction on what kind of object A.value, etc. are, so
unfortunately they might be mutable.

Our current solution is to have D compare A.value, B.value and C.value
to an internal cache using the 'is' operator (and put a big warning in
the docs about not changing 'value' attributes in-place). Not exactly
safe, but the speed savings over comparison with '==' will be
significant. Is this OK, bad or an abomination?

Again it would be helpful to know the terminology associated with the
behavior I'm looking for and any packages that implement it nicely.


Many thanks in advance and apologies for the long post,
Anand
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Network Graph Library

2007-11-28 Thread Anand Patil
On Nov 28, 2007 2:38 PM, jay graves <[EMAIL PROTECTED]> wrote:

> On Nov 28, 3:15 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> wrote:
> > Hi Folks,
> >
> > I am looking for a network Graph Library with Python bindings (Iron or
> > C!).
> >
> > Just need a simple relationship visualisation - seen a few via google
> > but many seem to be unmaintained.
> >
>
> I've used GraphViz before but never any of the Python bindings.  It's
> always been easy enough to just generate the .dot file that Graphviz
> expects.
> http://www.graphviz.org/
>
> I've also book marked NetworkX but I've never used it.
> https://networkx.lanl.gov/wiki
>
> I'm sure there are others.
>
> HTH.
> Jay Graves
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Try PyDot, http://dkbza.org/pydot.html . I've had good luck with it.

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

XSLT 2 Processor

2007-12-08 Thread anand nalya
Hi,
I wanted to know if there is a XSLT 2 processor for python??
Thanks,
Anand Nalya
-- 
http://mail.python.org/mailman/listinfo/python-list

XSLT 2 Processor

2007-12-08 Thread anand nalya
Hi,
I wanted to know if there is a XSLT 2 processor for python??
Thanks,
Anand Nalya
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: xpath and current python xml libraries

2007-12-11 Thread anand nalya
Is there a package that supports XSLT 2?

On 11/12/2007, Paul Boddie <[EMAIL PROTECTED]> wrote:
>
> On Dec 11, 2:03 am, [EMAIL PROTECTED] wrote:
> > PyXML seems to be long gone. Is lxml the way to go if i want to have
> > xpath supported?
>
> The libxml2dom package (which I maintain) also supports XPath and is
> also based on libxml2. If you want to migrate code from using PyXML
> without too much effort, it might be a solution. See here for details:
>
> http://www.python.org/pypi/libxml2dom
>
> Paul
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Error accessing a java web service

2007-12-11 Thread anand nalya
Hi,

I'm trying to access a web service written in java from python, but it is
returning a NullPointerException. The parameter that I'm passing is somehow
not reaching the server.

Here is the code I'm using for invoking the service

import SOAPpy
from SOAPpy import SOAPProxy
import fpconst
import xml

namespace = 'http://wev.onyomo.com/'
url = 'http://localhost:8176/XSLTTransformerService/XSLTTransformer'
server = SOAPProxy(url,namespace)

server.config.dumpSOAPOut = 1
server.config.dumpSOAPIn = 1

server.convert('');

*** Outgoing SOAP **

http://schemas.xmlsoap.org/soap/encoding/";
  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/";
  xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance";
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/";
  xmlns:xsd="http://www.w3.org/1999/XMLSchema";
>

http://wev.onyomo.com/"; SOAP-ENC:root="1">
<results />




*** Incoming SOAP **
http://schemas.xmlsoap.org/soap/envelope/"; xmlns:xsd="
http://www.w3.org/2001/XMLSchema";
xmlns:ns1="http://wev.onyomo.com/";>http://schemas.xmlsoap.org/soap/envelope/
">soapenv:Server
java.lang.NullPointerException


Traceback (most recent call last):
  File "", line 1, in ?
  File "/home/anand/Desktop/SOAPpy-0.12.0/SOAPpy/Client.py", line 470, in
__call__
  File "/home/anand/Desktop/SOAPpy-0.12.0/SOAPpy/Client.py", line 492, in
__r_call
  File "/home/anand/Desktop/SOAPpy-0.12.0/SOAPpy/Client.py", line 406, in
__call
SOAPpy.Types.faultType: 


When I access the same web service through a java client, it works fine.

Am I missing something here??

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

Permission to use Mac OS 'rocketship' dock icon?

2008-02-28 Thread Anand Patil
Hi all,

The image of a rocket with the Python logo that occasionally shows up
in the dock would make part of a nice logo for PyMC, an open-source
Python Bayesian statistics package. Anyone know who we would have to
ask to get permission to use it?

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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Anand Patil
Not sure if this is common knowledge yet but Sympy,
http://code.google.com/p/sympy, has a rational type.

In [2]: from sympy import *

In [3]: Rational(21,4)
Out[3]: 21/4

In [4]: Rational(21,4)+Rational(3,4)
Out[4]: 6
-- 
http://mail.python.org/mailman/listinfo/python-list


Python code-bloat tool-- warning n00b stuff...

2009-05-16 Thread anand j
Hi,
I am looking for a bunch of rules or a tool that takes the code for my
python class and checks the amount of code bloat and points out where i can
improve. I am a n00b to python and built an application linking wordnet and
graph packages. but somehow have this nagging feeling my code is too bloated
with too many functions. might just be paranoia , but worth an
investigation i guess.

Sorry if this is a repeat/trivial question, I could not find any
comprehensive links on google or the mailing list archive that is within my
gmail. Currently, trying to download the other archives and index using
whoosh and try searching it.

Thanks

==
Anand J
Center for Behaviour and Cognitive Sciences
University of Allahabad
Allahabad-211002
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code of a function

2008-05-29 Thread Anand Patil
On Thu, May 29, 2008 at 9:10 AM, Dark Wind <[EMAIL PROTECTED]> wrote:

> Hi,
>
> Is there any command in Python which gives the code for a function like
> just typing the name of a function (say svd) in R returns its code.
>
> Thank you
>

If you're using IPython, you can type svd?? .
--
http://mail.python.org/mailman/listinfo/python-list

Re: code of a function

2008-05-29 Thread Anand Patil


On May 29, 2008, at 9:38 AM, Gary Herron wrote:

Dark Wind wrote:

Hi,

Is there any command in Python which gives the code for a function  
like just typing the name of a function (say svd) in R returns its  
code.


Thank you


Nope.


If you're using IPython, you can do svd?? .

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


MACOSX_DEPLOYMENT_TARGET mismatch bug on Leopard using system Python

2008-05-29 Thread Anand Patil

Hi all,

I'm getting error messages like

distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET  
mismatch: now "10.3" but "10.5" during configure


on Leopard using system Python when trying to build a third-party  
module. Can this be fixed without installing a different distribution  
of Python? Googling the problem turns up fixes that involve  
configuring source distributions, unless I'm mistaken.


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


python glibc error

2008-09-02 Thread anand nalya
I'm getting the following errors while trying to run a python script:

*** glibc detected *** python: free(): invalid next size (normal):
0x0d2da210 ***

*** glibc detected *** python: malloc(): memory corruption:
0x1b81da60 ***

Is this a bug in my script or python or gllbc?

Relevent version numbers are:
#uname -a
Linux myserver 2.6.18-92.1.10.el5 #1 SMP Tue Aug 5 07:42:41 EDT 2008 x86_64
x86_64 x86_64 GNU/Linux
# python -V
Python 2.4.3
/lib/libc.so.6 | head -1
GNU C Library stable release version 2.5, by Roland McGrath et al.

The same script is running fine of fedora 4:
On Fedora:
uname -a
Linux onyomo.com 2.6.11-1.1369_FC4smp #1 SMP Thu Jun 2 23:08:39 EDT 2005
i686 i686 i386 GNU/Linux
python -V
Python 2.4.1
/lib/libc.so.6 | head -1
GNU C Library development release version 2.3.5, by Roland McGrath et al.

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

Render a xml graph as an image

2009-11-27 Thread anand jeyahar
hi all.
 Am looking to display a graph as an image.. the graph is in the
format of a xml file(basically the output of a python-graph
package).. Is there a package that already does it??
==
Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with no accounting policies.
~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why Can't I Delete a File I Created with Win XP?

2009-12-05 Thread anand jeyahar
simple when the python program ended, the file handle created by it was
still open...
so windows will not allow you to delete it (the standard behaviour, when
a parent process dies, with a sub-process running is to keep the child
running.)
try logging off and back on.it will solve the problem..

==

Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie
- Show quoted text -

==
Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which graph library is best suited for large graphs?

2009-12-11 Thread anand jeyahar

On 12/11/2009 10:27 PM, Neal Becker wrote:

Which library would you choose?
   
Hmm i have tried python-graph and was happy with itbut the most 
use i did was for complete graphs of 60-65 nodes..


Also there is an experimental branch for faster implementations, which 
is under development.


--
==
Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie

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


Re: Graph library for Python

2009-12-13 Thread anand jeyahar
 While I agree, I think it's going to be extremely difficult to get any
> kind of buy in without a great deal of support from within python.
> Any devs willing to throw the time required into this?
>
> Geremy Condra
> --
> http://mail.python.org/mailman/listinfo/python-list
>


yep i am interested.
Currently as am on between jobs can devote most of my time over the next 2
months.. but then am not sure..

I have been happy using python-graph.but recently have grown tired
of the number of implementations (not in small part owing to this thread)...



A crucial element in this hypothetical module would be the main graph
data structure. The simplest approach would be to implement it in pure
python, with lists, dicts and such, as many libraries do. However, this
would rule out its use by high-performance code, which would need a
simpler C-based data structure for direct interaction. On the other
hand, I'm not sure if there is a need for a high performance graph
module in python's standard library...

I disagree...I am not sure of the current need in terms of a precise
survey.But IMO, as bearophile pointed out.networkx is the most
popularand from their claims it is targeted at mathematicians,
physicists, biologists, computer scientists, social scientists.

Given the current trend in the growth of social and professional
networks. and social scientists (Disclaimer: i aspire to be one).. i do
expect a growing demand for graph data structures and high performance ones
soon enough..

 so IMHO if we are going in for it we should go for the high performance
graphs too..

======
Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anybody use web2py?

2009-12-19 Thread Anand Vaidya
On Dec 19, 2:42 pm, AppRe Godeck  wrote:
> Just curious if anybody prefers web2py over django, and visa versa. I
> know it's been discussed on a flame war level a lot. I am looking for a
> more intellectual reasoning behind using one or the other.

Hi,

I am not very familiar with Django, anyway, my reasons for selecting
web2py are:

- I believe Django naturally "fits in" to a publishing type of
application. web2py seems to be more focussed on being a front-end to
"applications" not so much for CMS type or newspaper type publishing.
(There is a web2py based wiki/CMS app, though). Though, I agree either
could fulfil any of these roles.

- Django documentation is vastly superior, including third party books
etc. After the v2 Web2py book, we do have solid documentation, but
web2py evolves so quickly, there are always things that are documented
only on the google groups, slices or wiki.

- Many training courses are available pretty much everywhere for
Django. Web2py needs to catch up - it will, probably.

- Web2py lowers the barrier to entry into python web programming,
since it is well thought out and intuitive. The support on the mailing
list is fantastic, though I have no idea how good the support for
Django is. w2py is easy to pick up for even a python newbie.

- Massimo claims about the backward compatibility. I was surprised
recently when I took an app I deployed several months (and several
versions old) and retested it with the latest SVN code. And it worked
fine! Which means, if my client asks for it, I could swap out old w2py
with the latest code with no problems.

My $0.02
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter import problem

2009-12-19 Thread harish anand
Hi,
I have Mandriva 2010.0 in my laptop.
I installed python3.1 from the repository.
But i am unable to import tkinter in python console.
When I try to import tkinter I get the following error,
`ImportError : No module named _tkinter`

Am I doing something wrong?

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


Re: remote evaluation of Python code typed in html webpage frame

2010-01-16 Thread Anand Vaidya
On Jan 16, 12:26 am, r0g  wrote:
> >> Diez
>
> The Web2py framework works a bit like that, although it's not quite as
> simplistic as what you describe. May be worth a look though.
>
> Roger.


Hi r0g,

web2py is a web-app framework (very similar to django, pylons etc) and
it does not execute user form-submitted python code. It executes
applications written and stored on the server-side only.

You are probably referring to some other project???

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


Generic Python Benchmark suite?

2010-01-18 Thread Anand Vaidya
Is there a generic python benchmark suite in active development? I am
looking forward to comparing some code on various python
implementations (primarily CPython 2.x, CPython 3.x, UnladenSwallow,
Psyco).

I am happy with something that gives me a relative number eg: ULS is
30% faster than CPy2.x etc

I found pybench which is probably not maintained actively.

What do you suggest?

PS: I think a benchmark should cover file / network, database  I/O,
data structures (dict, list etc), object creation/manipulation,
numbers, measure looping inefficiencies, effects of caching (memcache
etc) at the minimum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generic Python Benchmark suite?

2010-01-18 Thread Anand Vaidya
On Jan 19, 5:42 am, Terry Reedy  wrote:
> On 1/18/2010 4:58 AM, Anand Vaidya wrote:
>
> > Is there a generic python benchmark suite in active development? I am
> > looking forward to comparing some code on various python
> > implementations (primarily CPython 2.x, CPython 3.x, UnladenSwallow,
> > Psyco).
>
> You might find this interesting if you have not seen it 
> before:http://code.google.com/p/unladen-swallow/wiki/Benchmarks

@Antoine, Terry,

Thanks for the suggestions.

I will investigate those. I just ran the pybench, doesn't run on 3.x,
2to3 fails. I was hoping to locate something like Phoronix Test Suite
(that is a suite of microbenchmarks for Linux OS)

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


Re: Any elegant way to construct the complete $k$-partite graph in Python?

2009-11-23 Thread anand jeyahar
I am not sure what you mean by complete $k$-
partite graph
There is the python-graph package(http://code.google.com/p/python-graph/)
you might wanna check out.
It does return a complete graph.. may be u can tweak it??
==
Anand J
http://sites.google.com/a/cbcs.ac.in/students/anand
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with no accounting policies.
~Aang Jie



On Tue, Nov 24, 2009 at 05:35, Paul Miller <
paul.w.miller.please.dont.spam...@wmich.edu> wrote:

> I was wondering if there were any neat tools (like for instance,
> something from itertools) that would help me write the following function
> more elegantly.  The return value should, of course, be the complete $k$-
> partite graph $K_{n_1, n_2, \dots, n_k}$:
>
> def completeGraph (*ns):
>'''
>Returns the complete graph $K_{n_1, n_2, \dots, n_k}$ when passed
>the sequence \code {n_1, n_2, \dots, n_k}.
>'''
>if len (ns) == 1:
>return completeGraph ( * ([1] * ns[0]) )
>n = sum (ns)
>vertices = range (n)
>partition_indices = [sum (ns[:i]) for i in range (len (ns))]
>partite_sets = [vertices[partition_indices[i]:partition_indices[i+1]]
> \
>for i in range (len (partition_indices) - 1)]
>partite_sets.append (vertices[partition_indices [-1]:] )
>
>edges = []
>for i in range (len (partite_sets)):
>for j in range (i + 1, len (partite_sets)):
>edges.extend ([ (u, v) for u in partite_sets [i] for v in \
>   partite_sets [j] ])
>
>return graph.Graph (vertices = vertices, edges = edges)
>
> Many thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Common area of circles

2010-02-04 Thread Shashwat Anand
Given 'n' circles and the co-ordinates of their center, and the radius of
all being equal i.e. 'one', How can I take out the intersection of their
area.

hope the picture makes it clear
http://imagebin.us/images/p5qeo7hgc3547pnyrb6.gif
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-04 Thread Shashwat Anand
I wanted some general suggestion/tips only

On Thu, Feb 4, 2010 at 5:11 PM, Chris Rebert  wrote:

> On Thu, Feb 4, 2010 at 2:39 AM, Shashwat Anand 
> wrote:
> > Given 'n' circles and the co-ordinates of their center, and the radius of
> > all being equal i.e. 'one', How can I take out the intersection of their
> > area.
>
> How is this at all specific to Python?
>
> This also sounds suspiciously like homework, which you should know
> this list is unlikely to give direct answers to, though you might be
> able to get a few pointers or some general suggestions.
>
> Cheers,
> Chris
> --
> Back to toiling away on CSE 105 HW#3
> http://blog.rebertia.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-04 Thread Shashwat Anand
I want to calculate areas.
like for two circles (0, 0) and (0, 1) : the output is '1.228370'

similarly my aim is to take 'n' co-ordinates, all of radius '1' and
calculate the area common to all.
The best I got was monte-carlo methods which is inefficient. Is there any
other approach possible.

On Thu, Feb 4, 2010 at 5:24 PM, Xavier Ho  wrote:

> I'm not sure what you're after. Are you after how to calculate the area? Or
> are you trying to graph it? Or an analytical solution?
>
> What do you mean by "take out the intersection"?
>
> -Xav
>
> On Thu, Feb 4, 2010 at 9:47 PM, Shashwat Anand 
> wrote:
>
>> I wanted some general suggestion/tips only
>>
>>
>> On Thu, Feb 4, 2010 at 5:11 PM, Chris Rebert  wrote:
>>
>>> On Thu, Feb 4, 2010 at 2:39 AM, Shashwat Anand 
>>> wrote:
>>> > Given 'n' circles and the co-ordinates of their center, and the radius
>>> of
>>> > all being equal i.e. 'one', How can I take out the intersection of
>>> their
>>> > area.
>>>
>>> How is this at all specific to Python?
>>>
>>> This also sounds suspiciously like homework, which you should know
>>> this list is unlikely to give direct answers to, though you might be
>>> able to get a few pointers or some general suggestions.
>>>
>>> Cheers,
>>> Chris
>>> --
>>> Back to toiling away on CSE 105 HW#3
>>> http://blog.rebertia.com
>>>
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-04 Thread Shashwat Anand
I needed 6 decimal places of accuracy, so first way of solution will not
work for my case. However, your second strategy seems promising. Working on
it. Thanks :D
~l0nwlf

On Thu, Feb 4, 2010 at 5:49 PM, Bearophile  wrote:

> Shashwat Anand:
> > > Given 'n' circles and the co-ordinates of their center, and the radius
> of
> > > all being equal i.e. 'one', How can I take out the intersection of
> their
> > > area.
>
> I can see two possible solutions, both approximate. In both solutions
> you first look if there are a pair of circles that don't intersect, in
> this case the intersect area is zero. You also remove all circles
> fully contained in another circle.
>
> The first strategy is easy to do, but it probably leads to a lower
> precision. Then you can sample randomly many times the rectangular
> area that surely contains all circles. You count how many of those
> random points are inside all circles. This gives you an approximate
> area of their intersection. Increasing the points numbers slowly
> increases the result precision.
>
> The second strategy is more complex. You convert your circles into
> polygons with a fixed number of vertices (like 50 or 100 or 1000 or
> more. This number is constant even if the circles don't have all the
> same radius). So you can turn this circle into a simple mesh of
> triangles (all vertices are on the circumference). Then you "subtract"
> the second polygonalized circle, this can create a hole and split
> triangles in pieces, and so on with successive circles. At the end you
> can compute the total area of the triangles left. This is doable, but
> you need time to do implement this. The advantage is that the
> numerical precision of the result is probably higher. If you implement
> this second solution you can implement the first one too, and use it
> as a test to avoid bugs. Visualizing the triangles with Pygame or
> MatPlotLib can be useful to look for bugs.
>
> Bye,
> bearophile
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-04 Thread Shashwat Anand
thanks, all of you

On Thu, Feb 4, 2010 at 7:31 PM, Terry Reedy  wrote:

> On 2/4/2010 7:05 AM, Shashwat Anand wrote:
>
>> I want to calculate areas.
>> like for two circles (0, 0) and (0, 1) : the output is '1.228370'
>>
>> similarly my aim is to take 'n' co-ordinates, all of radius '1' and
>> calculate the area common to all.
>> The best I got was monte-carlo methods which is inefficient. Is there
>> any other approach possible.
>>
>
> There is a method for calculating the area of a polygon by traversing its
> boundary. I forget the formula, but you should be able to find it. So *if*
> you can find the arcs that bound the area, you can approximate each by a
> series of short lines and apply the polygon method.
>
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-04 Thread Shashwat Anand
maximum number of circles = 10**6
runtime <= 5 sec
center of circles , -1000<=xi,yi<=1000 (float) [for int it was easier]
intersection is there and the area will be non-zero (it can always be
checked if intersection is taking place and if no, then area = 0.00)
This was a programming contest problem, so code will be short
Maths, I'm eager to use. I attempted this problem because I saw scope of
maths in it. (I learnt python while doing ProjectEuler because C/C++ was
cumbersome for PE IMHO). I tried monte-carlo, but the time-limit exceeds if
i go for required accuracy. The same happens with grid approach.


On Fri, Feb 5, 2010 at 12:25 AM, Mark Dickinson  wrote:

> On 2/4/2010 7:05 AM, Shashwat Anand wrote:
> > I want to calculate areas.
> > like for two circles (0, 0) and (0, 1) : the output is '1.228370'
> >
> > similarly my aim is to take 'n' co-ordinates, all of radius '1' and
> > calculate the area common to all.
> > The best I got was monte-carlo methods which is inefficient. Is there
> > any other approach possible.
>
> How much accuracy do you need?  How fast does the algorithm need to
> be?  How many circles are typically involved?  Is the intersection
> necessarily non-empty for the configurations of circles that you use?
> How much code are you prepared to write?  How much mathematics do you
> want to use?
>
> Besides the Monte-Carlo and grid-based approaches already mentioned, I
> see a couple of other possibilities:
>
> (1) It should be entirely possible to do this analytically.  The hard
> part would be identifying the intersection points that form the
> vertices of the intersection (and especially, doing this robustly in
> the face of numerical errors and triple intersections or near-triple
> intersections).  Once you've got the vertices, it should be
> straightforward to compute the area:  compute the area of the polygon
> given by the convex hull of the vertices, then add on the extra areas
> for the segments bounded by the (straight) sides of the polygon and
> the corresponding outer arcs.
>
> (2) For a numerical approach that might be slightly better than the 2d
> brute-force approaches described by others:  make use of the fact that
> the intersection is convex.  Pick a point P in the intersection (if it
> exists:  finding such a point is an issue in itself).  For each angle
> t, 0 <= t <= 2*pi, define f(t) to be the distance from P to the
> boundary of the region, in the direction of the angle t.  We always
> have 0 <= f(t) <= 1, so f(t) can be quickly and accurately computed
> with a bisection search.  Now find the definite integral of 0.5 *
> (f(t))**2, as t goes from 0 to 2*pi, using your favourite quadrature
> method (but avoid methods that would be very sensitive to continuity
> of derivatives:  f(t) will be continuous, but f'(t) will not).
> Simpson's rule is probably good enough.
>
> Good luck!
>
> --
> Mark
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Common area of circles

2010-02-05 Thread Shashwat Anand
Here is my approach:
# input circles, remove duplicates, store them
# check whether all circle intersect:
if no: print '0.0'
if yes:
# calculate intersection points of two circles.
# check if that point lies in rest all circles
if yes: store it as polygon-coordinates (hull)
calculate area of curve from the given two points
# calculate final area : net area of curve + area of polygon
Here is my final code :
It's still Buggy (the logic I believe is correct, The implementation is
Buggy I guess


import math

def catch_point(x, y):
# checks for points which lie inside all the circles
# stores all such point in hull
kount = True
for i in range(n):
if (x - circle[i][0])**2 + (y - circle[i][1])**2 - 1.0 > 0:
kount = False
if kount == True:
hull.append((x, y))

def curve_area(x0, y0, x1, y1, x2, y2):
k = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
area_c = math.pi * (math.degrees(math.acos(1.0 - k*k/2.0))/360) #TODO
Verify
area_t = 0.5 * ( x0*(y1 - y2) - x1*(y0 - y2) + x2*(y0 - y1) )
if area_t < 0:  area_t = -area_t
area = area_c - area_t
#print area
return area

def polygon_area(p):
# calculate area of the polygon given the co-ordinates
return 0.5 * abs(sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in
segments(p)))

def segments(p):
return zip(p, p[1:] + [p[0]])

def intersect_circles(l):
# check whether all circle intersects or not
for i in l:
for j in l:
if (i[0] - j[0])**2 + (i[1] - j[1])**2 >= 4.0:
sol = 0.0
return sol
break
return 1.0

def intersect_coordinates(l):
sol = 0.0   # initialisation of final result
for i in range(n):
for j in range(n):
# find all intersecting co-ordinates for each circle
xa, xb = circle[i][0], circle[j][0]
ya, yb = circle[i][1], circle[j][1]
d = math.sqrt((xa - xb)**2 + (ya - yb)**2)
if d == 0:  continue
x1 = 0.5*(xa + xb) + 0.5*(yb - ya)*math.sqrt(4 - d*d) / d
y1 = 0.5*(yb + ya) - 0.5*(xb - xa)*math.sqrt(4 - d*d) / d
catch_point(x1, y1) # first intersection point
x2 = 0.5*(xa + xb) - 0.5*(yb - ya)*math.sqrt(4 - d*d) / d
y2 = 0.5*(yb + ya) + 0.5*(xb - xa)*math.sqrt(4 - d*d) / d
catch_point(x2, y2) # second intersection point
sol += curve_area(circle[i][0], circle[i][1], hull[-1][0],
hull[-1][1], hull[-2][0], hull[-2][1])
# add up the value of curves
return sol

t = int(raw_input())# total no. of test cases
for test in range(t):
n = int(raw_input())# total no. of circles
circle = [] # a blank list which will contain center of
circles
hull = []   # a blank list which will consist of points on
convex polygon
for i in range(n):
x,y = [float(i) for i in raw_input().split()]
circle.append((x,y))# storing the value

circle = list(set(circle))  # removing duplicates
n = len(circle) # calculating no. of non-duplicate circle
sol = intersect_circles(circle) #intersect_circles() check whether
all circle intersect
if sol == 0.0:  # if sol == 0.0 means all circle do not
intersect
print "0.00"# solution = 0.00 in this case
elif n == 1:# if only 1 circle present, the solution is PI
print "%.6f" %(math.pi)
else:
sol = intersect_coordinates(circle)# for rest cases we need
to calculate intersection co-ordinates of circle
print "%.6f" %(sol + polygon_area(hull))   # final solution



sample output :
4
2
0 0
1 0
1.228370
3
0 0
0 0
0 0
3.141593
3
0 0
0 1
10 12
0.00
3
0 0
1 0
0 1
0.192972

Either there is a redundency or there is some issue with this line : sol +=
curve_area(circle[i][0], circle[i][1], hull[-1][0], hull[-1][1],
hull[-2][0], hull[-2][1])

Still trying to fix it.
~l0nwlf

On Fri, Feb 5, 2010 at 11:48 AM, John Nagle  wrote:

> Chris Rebert wrote:
>
>> On Thu, Feb 4, 2010 at 2:39 AM, Shashwat Anand 
>> wrote:
>>
>>> Given 'n' circles and the co-ordinates of their center, and the radius of
>>> all being equal i.e. 'one', How can I take out the intersection of their
>>> area.
>>>
>>
>> How is this at all specific to Python?
>>
>> This also sounds suspiciously like homework, which you should know
>> this list is unlikely to give direct answers to, though you might be
>> able to get a few pointers or some general suggestions.
>>
>
>Good point.
>
>This is actually a problem in what's called "constructive geometry".
> Usually, this is a 3D problem, for which the term "constructive solid
> geometry", or CSG, is used.  That's where to look for al

how to fix bugs (python)

2010-02-06 Thread Shashwat Anand
I am interested in fixing bugs in python. Are there entry-level bugs in
python which makes me familiarize with the process just like gnome have
gnome-love ? Just a small start-up guidance will be a big favour as I have
never fixed any.

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


Re: how to fix bugs (python)

2010-02-06 Thread Shashwat Anand
Thanks Terry. I am looking on it. :)


On Sun, Feb 7, 2010 at 1:19 AM, Terry Reedy  wrote:

> On 2/6/2010 1:54 PM, Shashwat Anand wrote:
>
>> I am interested in fixing bugs in python. Are there entry-level bugs in
>> python which makes me familiarize with the process just like gnome have
>> gnome-love ? Just a small start-up guidance will be a big favour as I
>> have never fixed any.
>>
>
> Go to
> python.org/dev/
> and look at various pages there. The item tracker is at
> bugs.python.org
> Some items are marked easy. Many items have patches that need review. Help
> is needed both with Python code (modules) and C code (core and modules)
> depending on your abilities and interest. I would start with looking at
> current items on the tracker.
>
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last M digits of expression A^N

2010-02-06 Thread Shashwat Anand
Yes, it can be done. Have a look at :
http://en.wikipedia.org/wiki/Modular_exponentiation
The algorithm is also mentioned in CLRS.I tried writing my own
modular-exponentiation code following CLRS but observed that python pow()
function is much more efficient.
Have a look at this problem : https://www.spoj.pl/problems/LASTDIG/
as you can see ( https://www.spoj.pl/status/LASTDIG,l0nwlf/ )my first
solution used algorithm hard-coded from CLRS which took 0.04 sec however
using pow() function directly improved the efficiency to 0.0 So I would
suggest to go for pow() unless you intend to learn modular exponentiation
algorithm for which hand-coding is a must.

here are my solutions :
first one (hand-coded):


   1. def pow(a, b):
   2. if( not b):
   3.return 1
   4. if( b & 1 ):
   5.return ( pow( a, b - 1 ) * a ) % 10
   6.
   7. tmp = pow( a, b / 2 )
   8. return ( tmp * tmp ) % 10;
   9.
   10. for i in xrange(input()):
   11.  a,b = [ int(x) for x in raw_input().split(' ')]
   12.  print( pow( a % 10, b ) )


second one (pow()):


   1. for i in range(int(raw_input())):
   2. a,b = [int(x) for x in raw_input().split()]
   3. print pow (a,b,10)
   4.


HTH
~l0nwlf

On Sun, Feb 7, 2010 at 2:32 AM, monkeys paw  wrote:

> mukesh tiwari wrote:
>
>> Hello everyone. I am kind of new to python so pardon me if i sound
>> stupid.
>> I have to find out the last M digits of expression.One thing i can do
>> is (A**N)%M but my  A and N are too large (10^100) and M is less than
>> 10^5. The other approach   was  repeated squaring and taking mod of
>> expression. Is there any other way to do this in python more faster
>> than log N.
>>
>
> How do you arrive at log N as the performance number?
>
>
>
>> def power(A,N,M):
>>ret=1
>>while(N):
>>if(N%2!=0):ret=(ret*A)%M
>>A=(A*A)%M
>>N=N//2
>>return ret
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last M digits of expression A^N

2010-02-06 Thread Shashwat Anand
a nice exercise to do can be this problem :
http://www.codechef.com/MARCH09/problems/A4/ , it deals with both cases,
first and last k digits and can be performed within O(log n)

On Sun, Feb 7, 2010 at 3:58 AM, Shashwat Anand wrote:

> Yes, it can be done. Have a look at :
> http://en.wikipedia.org/wiki/Modular_exponentiation
> The algorithm is also mentioned in CLRS.I tried writing my own
> modular-exponentiation code following CLRS but observed that python pow()
> function is much more efficient.
> Have a look at this problem : https://www.spoj.pl/problems/LASTDIG/
> as you can see ( https://www.spoj.pl/status/LASTDIG,l0nwlf/ )my first
> solution used algorithm hard-coded from CLRS which took 0.04 sec however
> using pow() function directly improved the efficiency to 0.0 So I would
> suggest to go for pow() unless you intend to learn modular exponentiation
> algorithm for which hand-coding is a must.
>
> here are my solutions :
> first one (hand-coded):
>
>
>1. def pow(a, b):
>2. if( not b):
>3.  return 1
>4. if( b & 1 ):
>5.  return ( pow( a, b - 1 ) * a ) % 10
>
>6.
>7. tmp = pow( a, b / 2 )
>8. return ( tmp * tmp ) % 10;
>9.
>10. for i in xrange(input()):
>11.  a,b = [ int(x) for x in raw_input().split(' ')]
>
>12.  print( pow( a % 10, b ) )
>
>
> second one (pow()):
>
>
>1. for i in range(int(raw_input())):
>
>2. a,b = [int(x) for x in raw_input().split()]
>
>3. print pow (a,b,10)
>4.
>
>
> HTH
> ~l0nwlf
>
>
> On Sun, Feb 7, 2010 at 2:32 AM, monkeys paw  wrote:
>
>> mukesh tiwari wrote:
>>
>>> Hello everyone. I am kind of new to python so pardon me if i sound
>>> stupid.
>>> I have to find out the last M digits of expression.One thing i can do
>>> is (A**N)%M but my  A and N are too large (10^100) and M is less than
>>> 10^5. The other approach   was  repeated squaring and taking mod of
>>> expression. Is there any other way to do this in python more faster
>>> than log N.
>>>
>>
>> How do you arrive at log N as the performance number?
>>
>>
>>
>>> def power(A,N,M):
>>>ret=1
>>>while(N):
>>>if(N%2!=0):ret=(ret*A)%M
>>>A=(A*A)%M
>>>N=N//2
>>>return ret
>>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: max / min / smallest float value on Python 2.5

2010-02-06 Thread Shashwat Anand
On Sun, Feb 7, 2010 at 6:22 AM, duncan smith
wrote:

> Hello,
>  I'm trying to find a clean and reliable way of uncovering information
> about 'extremal' values for floats on versions of Python earlier than 2.6
> (just 2.5 actually).  I don't want to add a dependence on 3rd party modules
> just for this purpose.  e.g. For the smallest positive float I'm using,
>
>
> import platform
> if platform.architecture()[0].startswith('64'):
>TINY = 2.2250738585072014e-308
> else:
>TINY = 1.1754943508222875e-38
>

The above code is executed on OSX (snow leopard - 64 bit) without any
issue.  Your implementation seems fine to me.

>
>
> where I've extracted the values for TINY from numpy in IDLE,
>
>
> >>> float(numpy.finfo(numpy.float32).tiny)
> 1.1754943508222875e-38
> >>> float(numpy.finfo(numpy.float64).tiny)
> 2.2250738585072014e-308
> >>>
>
>
> I'm not 100% sure how reliable this will be across platforms.  Any ideas
> about the cleanest, reliable way of uncovering this type of information?  (I
> can always invoke numpy, or use Python 2.6, on my home machine and hardcode
> the retrieved values, but I need the code to run on 2.5 without 3rd part
> dependencies.)  Cheers.
>
> Duncan
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with regex search-and-replace (Perl to Python)

2010-02-07 Thread Shashwat Anand
Here is one simple solution :
>>> intext = """Lorem [ipsum] dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor  incididunt ut [labore] et [dolore] magna aliqua."""

>>> intext.replace('[', '{').replace(']',
'}')
'Lorem {ipsum} dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor  incididunt ut {labore} et {dolore} magna aliqua.'

*Some people, when confronted with a problem, think "I know, I’ll use
regular expressions." Now they have two problems.* — Jamie
Zawinskiin comp.lang.emacs.


On Sun, Feb 7, 2010 at 11:15 AM, Schif Schaf  wrote:

> On Feb 7, 12:19 am, "Alf P. Steinbach"  wrote:
>
> >
> > I haven't used regexps in Python before, but what I did was (1) look in
> the
> > documentation,
>
> Hm. I checked in the repl, running `import re; help(re)` and the docs
> on the `sub()` method didn't say anything about using back-refs in the
> replacement string. Neat feature though.
>
> > (2) check that it worked.
> >
> > 
> > import re
> >
> > text = (
> >  "Lorem [ipsum] dolor sit amet, consectetur",
> >  "adipisicing elit, sed do eiusmod tempor",
> >  "incididunt ut [labore] et [dolore] magna aliqua."
> >  )
> >
> > withbracks = re.compile( r'\[(.+?)\]' )
> > for line in text:
> >  print( re.sub( withbracks, r'{\1}', line) )
> > 
> >
>
> Seems like there's magic happening here. There's the `withbracks`
> regex that applies itself to `line`. But then when `re.sub()` does the
> replacement operation, it appears to consult the `withbracks` regex on
> the most recent match it just had.
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python admin abuse complaint

2010-02-07 Thread Shashwat Anand
LOL
pow(funny, sys.maxint)

On Sun, Feb 7, 2010 at 6:27 PM, Daniel Fetchinson  wrote:

> >>> This is a short complaint on admin abuse on #python irc channel on
> >>> freenode.net.
> >>
> >> Let's see, you are complaining about getting banned from #python by
> >> CROSS-POSTING between c.l.py and comp.lang.lisp.  From my POV, that's
> >> grounds for extending the IRC ban permanently.
> >
> > It certainly doesn't inspire any confidence that Xah's next trip to
> > #python is likely to last much longer than the last.
>
> Some humanity, please! If you look at the web page of the guy it
> really strikes me as a poor bastard who deserves more pity than
> bashing. IRC, newsgroups, email, web page, etc, these are the only
> things that this guy is doing, if you take these things away from him
> I don't know what will be left for him. Yes, he is annoying, yes, he
> is trolling, but if this prevents him from jumping under the bus, then
> I'd say let him do it. How many serial trolls are there on c.l.p? Not
> many. The average troll should of course be kicked out from
> everywhere, but guys like Xah are really rare and on humanitarian
> grounds I think should be allowed to do their things. If you really
> think about it the damage is not that great.
>
> In medieval times 99% of crazy people (using a loose definition of
> crazy) were either executed or tortured and executed, however, the one
> lonely village clown or court clown was allowed to be crazy, he even
> had a decent income from the king. I'm not suggesting a stipend for
> Xah from the PSF :) but having a single c.l.p clown is tolerable if it
> makes him happy.
>
> Cheers,
> Daniel
>
>
>
> --
> Psss, psss, put it down! - http://www.cafepress.com/putitdown
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre arithmetic results

2010-02-11 Thread Shashwat Anand
Do you really believe that -0.1 ** 0.1 is a valid computational problem ?
Can you raise a negative number to a fractional power ?
Output on my console (python 2.6)

>>> -.1 ** .1
-0.79432823472428149
>>> a,b = -.1,.1
>>> a**b
Traceback (most recent call last):
  File "", line 1, in 
ValueError: negative number cannot be raised to a fractional power
>>> -abs(a**b)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: negative number cannot be raised to a fractional power

There is a little issue here that '>>> -.1 ** .1' should give you error
message. That is it.


On Thu, Feb 11, 2010 at 6:14 AM, Terrence Cole <
list-s...@trainedmonkeystudios.org> wrote:

> Can someone explain to me what python is doing here?
>
> Python 3.1.1 (r311:74480, Feb  3 2010, 13:36:47)
> [GCC 4.3.4] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> -0.1 ** 0.1
> -0.7943282347242815
> >>> a = -0.1; b = 0.1
> >>> a ** b
> (0.7554510437117542+0.2454609236416552j)
> >>> -abs(a ** b)
> -0.7943282347242815
>
> Why does the literal version return the signed magnitude and the
> variable version return a complex?
>
> Cheers,
> Terrence
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre arithmetic results

2010-02-11 Thread Shashwat Anand
Just realized my flaw

>>> .1**.1
0.79432823472428149
>>> (-.1)**(.1)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: negative number cannot be raised to a fractional power

- a ** b = - (a ** b) and not (-a) ** b, Thats why -.1**.1 giving you
-0.79432823472428149 since .1 ** .1 = 0.79432823472428149 and minus sign is
appended prior to it.

On Thu, Feb 11, 2010 at 6:01 PM, Shashwat Anand wrote:

> Do you really believe that -0.1 ** 0.1 is a valid computational problem ?
> Can you raise a negative number to a fractional power ?
> Output on my console (python 2.6)
>
> >>> -.1 ** .1
> -0.79432823472428149
> >>> a,b = -.1,.1
> >>> a**b
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: negative number cannot be raised to a fractional power
> >>> -abs(a**b)
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: negative number cannot be raised to a fractional power
>
> There is a little issue here that '>>> -.1 ** .1' should give you error
> message. That is it.
>
>
>
> On Thu, Feb 11, 2010 at 6:14 AM, Terrence Cole <
> list-s...@trainedmonkeystudios.org> wrote:
>
>> Can someone explain to me what python is doing here?
>>
>> Python 3.1.1 (r311:74480, Feb  3 2010, 13:36:47)
>> [GCC 4.3.4] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> -0.1 ** 0.1
>> -0.7943282347242815
>> >>> a = -0.1; b = 0.1
>> >>> a ** b
>> (0.7554510437117542+0.2454609236416552j)
>> >>> -abs(a ** b)
>> -0.7943282347242815
>>
>> Why does the literal version return the signed magnitude and the
>> variable version return a complex?
>>
>> Cheers,
>> Terrence
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: working with laptop battery

2010-02-13 Thread Shashwat Anand
I too am interested as to which module should I use. My OS is OS X Snow
Leopard.

On Sun, Feb 14, 2010 at 6:56 AM, Chris Rebert  wrote:

> On Sat, Feb 13, 2010 at 4:48 PM, Daniel Dalton 
> wrote:
> > Hi,
> >
> > I'm constantly working in the command line and need to write a program
> > to give me alerts on my battery. Can someone please tell me what module
> > I should use to access battery information? Looking for something that
> > perhaps makes use of acpi so I can get estimated time left as well as a
> > percentage.
>
> It's probably gonna depend on which OS you're running. Which would be...?
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >