Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Mikael Olofsson

Peter Otten wrote:
I usually use decorator functions, but I think the following should work, 
too:


class deco(object):
def __init__(self, func):
self._func = func
def __call__(self, *args):
print "Decorator:", args
self._func(*args)
def __get__(self, *args):
return deco(self._func.__get__(*args))


This looks like a winner to me. It is elegant, works for functions as 
well as for methods, and does not mess with the internals of the 
decorator which avoids the problems that Duncan pointed out.


Thanks Peter, and thanks everyone else that chimed in and contributed.

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


Re: sqlite single transaction without foreign key or triggers

2009-05-12 Thread Rob Williscroft
Aahz wrote in news:[email protected] in comp.lang.python:

> In article ,
> Rob Williscroft   wrote:
>>
>>db.execute( '''
>> update "sessions" set "uid" = ?
>> where "uid" = ? 
>> and exists(
>>  select * from "users" where "uid" = ?
>>   )
>>''',
>>(v['uid'],s.SID, v['uid']) 
>>  )
> 
> This will be more efficient if you do "select uid from users".

What will be more efficient ?

Do you mean the "select * ..." or do you want to take the exists 
sub-query out and put it in a python if ? 

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Michele Simionato
On May 12, 8:54 am, Mikael Olofsson  wrote:
> Peter Otten wrote:
> > I usually use decorator functions, but I think the following should work,
> > too:
>
> > class deco(object):
> >     def __init__(self, func):
> >         self._func = func
> >     def __call__(self, *args):
> >         print "Decorator:", args
> >         self._func(*args)
> >     def __get__(self, *args):
> >         return deco(self._func.__get__(*args))
>
> This looks like a winner to me. It is elegant, works for functions as
> well as for methods, and does not mess with the internals of the
> decorator which avoids the problems that Duncan pointed out.

Still it turns something which is a function into an object and you
lose the
docstring and the signature. pydoc will not be too happy with this
approach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: piping input to an external script

2009-05-12 Thread Dave Angel

Tim Arnold wrote:
Hi, I have some html files that I want to validate by using an external 
script 'validate'. The html files need a doctype header attached before 
validation. The files are in utf8 encoding. My code:

---
import os,sys
import codecs,subprocess
HEADER = ''

filename  = 'mytest.html'
fd = codecs.open(filename,'rb',encoding='utf8')
s = HEADER + fd.read()
fd.close()

p = subprocess.Popen(['validate'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
validate = p.communicate(unicode(s,encoding='utf8'))
print validate
---

I get lots of lines like this:
Error at line 1, character 66:\tillegal character number 0
etc etc.

But I can give the command in a terminal 'cat mytest.html | validate' and 
get reasonable output. My subprocess code must be wrong, but I could use 
some help to see what the problem is.


python2.5.1, freebsd6
thanks,
--Tim



  
The usual rule in debugging:  split the problem into two parts, and test 
each one separately, starting with the one you think most likely to be 
the culprit


In this case the obvious place to split is with the data you're passing 
to the  communicate call.  I expect it's already wrong, long before you 
hand it to the subprocess.  So write it to a file instead, and inspect 
it with a binary file viewer.  And of course test it manually with your 
validate program.  Is validate really expecting a Unicode stream in stdin ?



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


Re: how to consume .NET webservice

2009-05-12 Thread Diez B. Roggisch

bav schrieb:

question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?


Try accessing the .NET-service using a .NET client, and capture the 
traffic (it speaks volumes that the apache axis project offers a 
HTTP-proxy for exactly that purposes, tcpmon). Then use an 
XML-templating language such as genshi & create the messages yourself.


Sounds awkward and complicated? It is. As I said in another post: the 
"S" stands for simple...


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


Re: how to consume .NET webservice

2009-05-12 Thread Diez B. Roggisch

namekuseijin schrieb:

Diez B. Roggisch wrote:

namekuseijin schrieb:

bav escreveu:

question from a python newbie;

  how can i consume in python language, a .NET web service, passing
  a string array as parameter in some easy steps?


Unless Microsoft extended the standard in any way, then it should be 
just as you consume any web service, I guess. ;)


Microsoft *created* the standard.. 


No:



Yes:

http://webservices.xml.com/pub/a/ws/2001/04/04/soap.html

MS created it. That it *became* a standard of the W3C later - well, they 
did that with OOXML as well...


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


Re: how to consume .NET webservice

2009-05-12 Thread Diez B. Roggisch

namekuseijin schrieb:
> Diez B. Roggisch wrote:
>> namekuseijin schrieb:
>>> bav escreveu:
 question from a python newbie;

   how can i consume in python language, a .NET web service, passing
   a string array as parameter in some easy steps?
>>>
>>> Unless Microsoft extended the standard in any way, then it should 
be just as you consume any web service, I guess. ;)

>>
>> Microsoft *created* the standard..
>
> No:


Yes:

http://webservices.xml.com/pub/a/ws/2001/04/04/soap.html

MS created it. That it *became* a standard of the W3C later - well, they 
did that with OOXML as well...


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


Re: Complete frustration

2009-05-12 Thread Tim Golden

Dave Angel wrote:

[... snip sound advice about file associations etc. ...]

One thing to bear in mind is that any settings, however obtained,
in the User part of the registry (HKCU\Software\) will override
those in the Machine part of the registry (HKLM\Software...). If
you think you've set things correctly and you're still not seeing
the effect, check under HKCU to see if there's something there
which would override things.

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


Re: Fill Javascript form

2009-05-12 Thread Matteo
On 11 Mag, 23:06, Shawn Milochik  wrote:
> How is the form "written in JavaScript"? Is it dynamically generated?
>
> In any case, can you just send a POST request if you know the values required?

The problem is indeed that the form is dynamically generated.
That's the .js file:

if (navigator.appVersion.indexOf("MSIE")!=-1)
document.write("");

if (!window.queryObj) {
window.queryObj = new Object();
window.location.search.replace(new RegExp("([^?=&]+)(=([^&]
*))?","g"), function($0,$1,$2,$3) { queryObj[$1] = $3; });
if (queryObj['uamip'] == null && queryObj['uamport'] == null)
{queryObj['uamip']='10.192.0.1';queryObj['uamport']='3990';}
}

if (queryObj['uamip'] != null && queryObj['uamport'] != null) {
var script = document.getElementById('chillicontroller');
if (script == null) {
  //document.write('manutenzione');
script = document.createElement('script');
script.id = 'chillicontroller';
script.type = 'text/javascript';
script.src = 'http://'+queryObj['uamip']+':3990/www/
chillijs.chi';

var head = document.getElementsByTagName("head")[0];
if (head == null) head = document.body;
head.appendChild(script);
   }
   script=document.getElementById('chillicontroller');
   if(script==null)document.write('manutenzione');
script.src = 'http://'+queryObj['uamip']+':3990/www/chillijs.chi';

} else {
//document.write('manutenzione');
var noLocation = document.getElementById("noLocation");
if (noLocation != null && noLocation.style) {
   noLocation.style.display = 'inline';
}
}

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


Re: Your Favorite Python Book

2009-05-12 Thread Jeremiah Dodds
On Mon, May 11, 2009 at 9:44 PM, Sam Tregar  wrote:

> Greetings.  I'm working on learning Python and I'm looking for good books
> to read.  I'm almost done with Dive into Python and I liked it a lot. I
> found Programming Python a little dry the last time I looked at it, but I'm
> more motivated now so I might return to it.  What's your favorite?  Why?
>
> -sam
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
I've gotten great use out of Programming Python (mainly because it has a lot
of larger full-fledged examples), Python in a Nutshell, and recently Expert
Python Programming. My copy of Python in a Nutshell is particularly
dog-eared now - it is a bit outdated (I've got notes all over the book of
things that have changed...) but it's still a great resource.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-12 Thread Lawrence D'Oliveiro
In message , kj wrote:

> I know about the construct:
> 
> try:
> # do something
> except ...:
> # handle exception
> else:
> # do something else
> 
> ...but I can't come with an example in which the same couldn't be
> accomplished with [no else]

I'd agree. If you have to resort to a "try .. else", then might I 
respectfully suggest that you're using exceptions in a way that's 
complicated enough to get you into trouble.

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


Re: dict would be very slow for big data

2009-05-12 Thread Steven D'Aprano
On Mon, 11 May 2009 20:28:13 -0700, forrest yang wrote:

> hi
> i am trying to insert a lot of data into a dict, which may be 10,000,000
> level.
> after inserting 10 unit, the insert rate become very slow, 50,000/
> s, and the entire time used for this task would be very long,also. would
> anyone know some solution for this case?

You don't give us enough information to answer.


How are you generating the data?

What are the keys and the values?

Are you sure it is slow to insert into the dict, or could some other part 
of your processing be slow?

Does performance change if you turn garbage collection off?

import gc
gc.disable()
# insert your items
gc.enable()


Can you show us a sample of the data, and the code you are using to 
insert it into the dict?

Do you have enough memory? If you run an external process like top, can 
you see memory exhaustion, CPU load or some other problem?




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


Re: dict would be very slow for big data

2009-05-12 Thread Bruno Desthuilliers

forrest yang a écrit :

hi
i am trying to insert a lot of data into a dict, which may be
10,000,000 level.
after inserting 10 unit, the insert rate become very slow, 50,000/
s, and the entire time used for this task would be very long,also.
would anyone know some solution for this case?


Hint : computer's RAM is not an infinite resource.

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


Re: Fill Javascript form

2009-05-12 Thread Jeremiah Dodds
On Tue, May 12, 2009 at 9:15 AM, Matteo  wrote:

> On 11 Mag, 23:06, Shawn Milochik  wrote:
> > How is the form "written in JavaScript"? Is it dynamically generated?
> >
> > In any case, can you just send a POST request if you know the values
> required?
>
> The problem is indeed that the form is dynamically generated.
> That's the .js file:
>
> if (navigator.appVersion.indexOf("MSIE")!=-1)
> document.write("

Is there a GUI for informing a user of missing dependencies?

2009-05-12 Thread Jason
I'm writing a small GUI (Python 2.5/6) using wxPython and pySerial.
Since these are both 3rd party modules, if a user doesn't have them
installed and tries to run the GUI from a file browser, the app will
fail silently. I'm hoping to avoid that.

Sure, I'll have a readme file, but I was wondering if there is an even
more direct way. I was going to roll my own (eg. very simple Tkinter
fallback error dialog if wxPython import fails, wxPython error dialog
if anything else is missing); but I was wondering if such a system
already exists out there.

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


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-12 Thread Lawrence D'Oliveiro
In message , Geoff 
Gardiner wrote:

> Lawrence D'Oliveiro wrote:
>
>> .. I expect an apology.
>> Otherwise, it becomes grounds for an abuse complaint to your ISP.
>>   
> Yes, I do apologize profusely and publicly ...

Thank you.

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


Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Duncan Booth
Michele Simionato  wrote:

> On May 12, 8:54 am, Mikael Olofsson  wrote:
>> Peter Otten wrote:
>> > I usually use decorator functions, but I think the following should
>> > wor 
> k,
>> > too:
>>
>> > class deco(object):
>> >     def __init__(self, func):
>> >         self._func = func
>> >     def __call__(self, *args):
>> >         print "Decorator:", args
>> >         self._func(*args)
>> >     def __get__(self, *args):
>> >         return deco(self._func.__get__(*args))
>>
>> This looks like a winner to me. It is elegant, works for functions as
>> well as for methods, and does not mess with the internals of the
>> decorator which avoids the problems that Duncan pointed out.
> 
> Still it turns something which is a function into an object and you
> lose the
> docstring and the signature. pydoc will not be too happy with this
> approach.

Also it means every time the decorator is invoked 'self' references a 
new instance of deco. I don't know why Mikael wants to use a class 
rather than a function but if he wants to save state between calls this 
isn't going to help.

Something like this may work, and preserves the function name, type and 
docstring:

from functools import wraps
class Decorator(object):
def __init__(self, func):
self._func = func

def __new__(cls, func):
decorator = object.__new__(cls)
decorator.__init__(func)
@wraps(func)
def wrapper(*args, **kwds):
return decorator(*args, **kwds)
return wrapper

class deco(Decorator):
def __init__(self, func):
self.calls = 0
Decorator.__init__(self, func)

def __call__(self, *args):
self.calls += 1
print "Decorator:", args, "called", self.calls, "times"
return self._func(*args)

class C(object):
@deco
def meth(self, arg):
"""meth's docstring"""
print "meth %r %r" % (self, arg)
return arg+1

inst1 = C()
inst2 = C()
print repr(inst1.meth), inst1.meth.__doc__

print inst1.meth(5)
print inst1.meth(inst2.meth(3))

---
Output:
> meth's 
docstring
Decorator: (<__main__.C object at 0x00B45390>, 5) called 1 times
meth <__main__.C object at 0x00B45390> 5
6
Decorator: (<__main__.C object at 0x00B453D0>, 3) called 2 times
meth <__main__.C object at 0x00B453D0> 3
Decorator: (<__main__.C object at 0x00B45390>, 4) called 3 times
meth <__main__.C object at 0x00B45390> 4
5


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-12 Thread Martin Vilcans
On Fri, May 8, 2009 at 5:48 PM, Andreas Rumpf  wrote:
> Dear Python-users,
>
> I invented a new programming language called "Nimrod" that combines Python's 
> readability with C's performance. Please check it out: 
> http://force7.de/nimrod/
> Any feedback is appreciated.

Nice with a language with a new language designed for high
performance. It seems like a direct competitor with D, i.e. a
high-level language with low-level abilities. The Python-like syntax
is a good idea.

There are two showstoppers for me though:

1. Introducing a new programming language where the char type is a
byte is anachronistic. You're saying that programmers don't have to
care about the string encoding and can just treat them as an array of
bytes. That is exactly what causes all the problems with applications
that haven't been designed to handle anything but ASCII. If you're
doing any logic with strings except dumb reading and writing, you
typically *have to* know the encoding. Forcing programmers to be aware
of this problem is a good idea IMO.

You can certainly have a string type that uses byte arrays in UTF-8
encoding internally, but your string functions should be aware of that
and treat it as a unicode string. The len function and index operators
should count characters, not bytes. Add a byte array data type for
byte arrays instead.

2. The dynamic dispatch is messy. I agree that procedural is often
simpler and more efficient than object-oriented programming, but
object-oriented programming is useful just as often and should be made
a simple as possible. Since Nimrod seems flexible, perhaps it would be
possible to implement an object-orientation layer in Nimrod that hides
the dynamic dispatch complexity?

-- 
[email protected]
http://www.librador.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-12 Thread Steven D'Aprano
On Tue, 12 May 2009 20:23:25 +1200, Lawrence D'Oliveiro wrote:

> In message , kj wrote:
> 
>> I know about the construct:
>> 
>> try:
>> # do something
>> except ...:
>> # handle exception
>> else:
>> # do something else
>> 
>> ...but I can't come with an example in which the same couldn't be
>> accomplished with [no else]
> 
> I'd agree. If you have to resort to a "try .. else", then might I
> respectfully suggest that you're using exceptions in a way that's
> complicated enough to get you into trouble.



try:
rsrc = get(resource)
except ResourceError:
log('no more resources available')
raise
else:
do_something_with(rsrc)
finally:
rsrc.close()



is complicated? It seems pretty straightforward to me.



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


Re: What's the use of the else in try/except/else?

2009-05-12 Thread Steven D'Aprano
On Tue, 12 May 2009 09:20:36 +, Steven D'Aprano wrote:

> On Tue, 12 May 2009 20:23:25 +1200, Lawrence D'Oliveiro wrote:
> 
>> In message , kj wrote:
>> 
>>> I know about the construct:
>>> 
>>> try:
>>> # do something
>>> except ...:
>>> # handle exception
>>> else:
>>> # do something else
>>> 
>>> ...but I can't come with an example in which the same couldn't be
>>> accomplished with [no else]
>> 
>> I'd agree. If you have to resort to a "try .. else", then might I
>> respectfully suggest that you're using exceptions in a way that's
>> complicated enough to get you into trouble.
> 
> 
> 
> try:
> rsrc = get(resource)
> except ResourceError:
> log('no more resources available')
> raise
> else:
> do_something_with(rsrc)
> finally:
> rsrc.close()



Except of course such a pattern won't work, because if get(resource) 
fails, rsrc will not exist to be closed. So a better, and simpler, 
example would be to drop the finally clause:

try:
rsrc = get(resource)
except ResourceError:
log('no more resources available')
raise
else:
do_something_with(rsrc)
rsrc.close()


To really be safe, that should become:

try:
rsrc = get(resource)
except ResourceError:
log('no more resources available')
raise
else:
try:
do_something_with(rsrc)
finally:
rsrc.close()


which is now starting to get a bit icky (but only a bit, and only because 
of the nesting, not because of the else).



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


[no subject]

2009-05-12 Thread karlos barlos
hello to all 

i have been using this script to add users to my active directory structure

i wise to make a loop in order for it to run for A large Number of Users 

can anyone give me some advice on the loop ??



import win32com,win32com.client
def add_acct(location,account):
    
  ad_obj=win32com.client.GetObject(location)
  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')
  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  ad_user.setpassword('the password')
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()


location='LDAP://OU=sales,DC=shay,DC=com'
user={'first':'shay','last':'smith','login':'shay123'}
add_acct(location,user)


location='LDAP://OU=sales,DC=shay,DC=com'
user={'first':'ron','last':'smith','login':'ron1267'}
add_acct(location,user)




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


Re: Decorating methods - where do my arguments go?

2009-05-12 Thread Mikael Olofsson

Michele Simionato wrote:
> Still it turns something which is a function into an object and
> you lose the docstring and the signature. pydoc will not be too
> happy with this approach.

Duncan Booth wrote:

I don't know why Mikael wants to use a class rather than a function
but if he wants to save state between calls this isn't going to help.


I've never used decorators before, and that's the main reason for my 
confusion. I have found myself in a situation where I think that 
decorators is the way to go. So I tried to find information about how to 
write them the usual way: Googling and browsing documentation. I found 
examples using both functions and classes, but not much explanation of 
what's going on, especially not in the class case. I didn't find any 
arguments for favouring any of those alternatives. Actually, most 
examples I found did not even include the definition of the actual 
decorator or any information about where they might come from, only the 
@-row.


Based on the above observations, I assumed that both alternatives were 
equally possible. The first answers I got here also led me to believe 
that that was the case. My understanding is that in most cases, you can 
use a callable object instead of a function with little or no practical 
difference, except the syntax of its definition. In my eyes, a class 
definition looks nicer and is more readable than a nested function. 
Therefore, I tend to define a class with a __call__ method and helper 
methods instead of nested functions, if I find the need.


Practicality beats purity, and it seem like using a class for decoration 
is a lot more hassle than using a function. I fold.


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


Re: dict would be very slow for big data

2009-05-12 Thread Tim Chase

i am trying to insert a lot of data into a dict, which may be
10,000,000 level.
after inserting 10 unit, the insert rate become very slow, 50,000/
s, and the entire time used for this task would be very long,also.
would anyone know some solution for this case?


As others have mentioned, you've likely run out of RAM and the 
slowness you feel is your OS swapping your process to disk.


If you need fast dict-like access to your data, I'd recommend 
shifting to a database -- perhaps the stock "anydbm" module[1]. 
The only catch is that it only supports strings as keys/values. 
But Python makes it fairly easy to marshal objects in/out of 
strings.  Alternatively, you could use the built-in (as of 
Python2.5) sqlite3 module to preserve your datatypes and query 
your dataset with the power of SQL.


-tkc


[1]
http://docs.python.org/library/anydbm.html





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


Re: Is there a GUI for informing a user of missing dependencies?

2009-05-12 Thread Javier Collado
Hello,

I'm not an expert, but if you use setuptools for your application,
then a 'install_requires' argument would do the job. For more
information, please take a look at:
http://peak.telecommunity.com/DevCenter/setuptools

Best regards,
Javier

2009/5/12 Jason :
> I'm writing a small GUI (Python 2.5/6) using wxPython and pySerial.
> Since these are both 3rd party modules, if a user doesn't have them
> installed and tries to run the GUI from a file browser, the app will
> fail silently. I'm hoping to avoid that.
>
> Sure, I'll have a readme file, but I was wondering if there is an even
> more direct way. I was going to roll my own (eg. very simple Tkinter
> fallback error dialog if wxPython import fails, wxPython error dialog
> if anything else is missing); but I was wondering if such a system
> already exists out there.
>
> — Jason
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping comments

2009-05-12 Thread Lawrence D'Oliveiro
In message , Tobias Weber 
wrote:

> In article <[email protected]>,
>  Steven D'Aprano  wrote:
> 
>> Maybe in another 20 years, nobody will care about low-level details like
>> the characters used to write code. Only the tokens really matter.
> 
> You could have that ten years ago with AppleScript. Gets annoying
> quickly...

To me, the annoying thing about the AppleScript Script Editor wasn't the 
tokenization, it was its insistence on overriding my decisions about where 
to continue a line.

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


Re: Wrapping comments

2009-05-12 Thread Lawrence D'Oliveiro
In message , Tobias Weber 
wrote:

> (still not gonna use software that doesn't let me type # because it's
> alt+3 on a UK layout; having to re-learn or configure that is just sick)

Tried typing compose-plus-plus?

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


Re: Nimrod programming language

2009-05-12 Thread bearophileHUGS
Martin Vilcans:
> Nice with a language with a new language designed for high
> performance. It seems like a direct competitor with D, i.e. a
> high-level language with low-level abilities.
> The Python-like syntax is a good idea.

There is Delight too:
http://delight.sourceforge.net/

But I agree, one disadvantage (and one advantage) the D language is
its significant syntactic and semantic compatibility with C.
I like the syntax of Nimrod, but I think Nimrod designer has to work
more on data parallelism and higher level forms of parallelism.
At the moment D language has not enough data parallelism features for
scientific programming purposes.

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


Re: Wrapping comments

2009-05-12 Thread Lawrence D'Oliveiro
In message , Nick Craig-
Wood wrote:

> Rhodri James  wrote:
>
>>  Emacs is my editor of choice ...
> 
> You probably haven't used MAC OS X then!

I tried using Emacs via SSH from a Mac once. Made me run screaming for the 
nearest Windows box 
.

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


Switchover: mail.python.org

2009-05-12 Thread Aahz
On Monday 2009-05-11, mail.python.org will be switched to another machine
starting roughly at 14:00 UTC.  This should be invisible (expected
downtime is less than ten minutes).
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pycon Tre, grazie!

2009-05-12 Thread Marco Mariani

daniele wrote:


Si è concluso ieri la pycon tre, è stata molto interessante, un bel
evento per una bella comunità.


Sempre meglio.. anche se mi preoccupa un po' un eventuale cambio di location


Ho visto con grande piacere, oltre all'incremento dei partecipanti,
anche un sensibile incremento delle partecipanti!


Si'... in particolare durante il talk di Raymond :)
--
http://mail.python.org/mailman/listinfo/python-list


ANN: Demo online shop for LFS

2009-05-12 Thread Kai Diefenbach
Hi,

I'm pleased to announce that there is new demo shop for LFS:
http://demo.getlfs.com

LFS is an online shop based on Django and distributed  under the BSD-
License

For more information please visit http://www.getlfs.com, subscribe to
our feed http://www.getlfs.com/feeds/news or follow us on Twitter
http://twitter.com/lfsproject.

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


ANNOUNCE: libmsgque 3.1

2009-05-12 Thread Andreas Otto
ANNOUNCE a major feature improvement of libmsgque ...


What is LibMsgque
=

LibMsgque is an OS independent, Programming Language independent and
Hardware independent solution to link applications together to act like a
single application. Or with other words, LibMsgque is an Application-Server
toolkit.


Highlights of the current Release:
=

This release introduce a couple of highlights into the LibMsgque World
including the Python 3.01 support and a brand new Tcl/Java interface

As bonus an C/Tcl/Java/Python performance test was added using the
following conditions:

  1. same basic native library -> libmsgque (written in C)
  2. same user -> me
  3. same performance management tool
  4. same code workflow using the native language interface
to link libmsgque with a language specific service
handler
  5. testing the following aspects:
a) application startup/shutdown performance
b) synchronous and asynchronous transaction performance
c) spawn, fork and thread process creation performance

  -> results: http://libmsgque.sourceforge.net/performance.htm


Programmer-Visible-Changes:
===

Add Python 3.01 support
  This is the next step to provide an OS and programming language
  independent solution

New Tcl and Java Library binding
  Now Tcl, Java and Python using the same function namespace
  to improve the cross language code readability

C library improvement including better error checking support
  Add more error-case checking

Add new test hardware, apple iBook (ppc) running Debian 5
  Put my old iBook back to live

Re-Add big/little endian support
  Now be able to test endianness

Improve 32Bit/64Bit support
  Code Cleanup

Add new documentation
  Entire new documentation and examples were added


The Web-Site was updated:
=

   -> http://libmsgque.sourceforge.net

  For a fast introduction use the following URL:

   -> http://libmsgque.sourceforge.net/features.htm



mfg

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


Re: creating classes with mix-ins

2009-05-12 Thread samwyse
On May 11, 9:01 pm, Carl Banks  wrote:
> On May 11, 11:16 am, samwyse  wrote:
>
> > Should I use a class decorator, or a metaclass?
>
> Here's the thing: unless you have advance knowledge of the methods
> defined by self.blog, you can't get the attr_list at class definition
> time, which means neither the metaclass nor the decorator would be a
> good approach.  If that's the case, you should define newPost,
> editPost, and whatever other methods of self.blog as ordinary
> attributes of self, within the init function.  boilerplate would be
> the same except you would pass self to it and allow template to use it
> from its nested scope (it would no longer be an instance method since
> it's an ordinary attribute).
>
> If you do know what the methods of self.blog will be, then that's
> where you get attr_list from.  So, for instance, if blogHandler always
> returns an object of type Blog, then you could inspect Blog's type
> dict to see what methods are defined in it; in fact you probably want
> to check the whole MRO for Blog, like this (untested):
>
> attr_list = []
> for cls in Blog.__mro__:
>     for value in cls.__dict__:
>         if is_wrapped_method(value):
>             attr_list.append(value)
>
> A metaclass is probably overkill to assign the wrapped blog methods.
> I probably wouldn't even bother with the decorator, and just write the
> loop after the class definition.  Then you can use MetaBlog directly
> for klass.
>
> class MetaBlog(object):
>     ...
>
> for what in attr_list:
>     setattr(MetaBlog, what, boilerplate(what))
>
> If it were the kind of thing I found myself doing often I'd refactor
> into a decorator.

Unfortunately, 'boilerplate()' uses the handlers that I provide when
MetaBlog is instantiated.  I tried the following, but it didn't work
(for reasons that were obvious in retrospect).

def instantiate_template(m_name, instance):
isAuthorised = instance.security.isAuthorised
method_to_wrap = getattr(instance.blog, m_name)
def template(self, which, username, password, *args):
if not isAuthorised(username, password, which, m_name):
raise Exception('Unauthorised access')
return method_to_wrap(which, *args)
template.__name__ = method_to_wrap.__name__
template.__doc__ = method_to_wrap.__doc__
return template

class MetaWeblog(object):
def __init__(self,
 securityHandler=SimpleSecurityHandler,
 blogHandler=SimpleBlogHandler):
self.security = securityHandler()
self.blog = blogHandler()
# from http://www.xmlrpc.com/metaWeblogApi
m_prefix = 'metaWeblog.'
m_list = ('newPost', 'editPost', 'getPost', 'newMediaObject',
  'getCategories', 'getRecentPosts', )

# Here's where things fell apart
for m_name in m_list:
dotted_name = m_prefix + m_name
method = instantiate_template(m_name, self)
setattr(self, dotted_name, method)

So, I replaced that last for-loop with this:

# Since we're about to monkey-patch the class, we should
# make certain that all instances use the same handlers.
handlers = (self.security, self.blog)
try:
assert getattr(self.__class__, '_handlers') == handlers
except AttributeError:
for m_name in m_list:
dotted_name = m_prefix + m_name
method = instantiate_template(m_name, self)
setattr(self.__class__, dotted_name, method)
setattr(self.__class__, '_handlers', handlers)

This is good enough for now, since I can't conceive of a reason why
MetaBlog would be instantiated more than once.  If it were, on the
other hand, it would probably be because you wanted to use different
handlers.  In that case, I think I'd want to use a class factory,
something like this:
server.register_instance(
MetaWeblogFactory(securityHandler, blogHandler)()
)

Anyway, thanks for getting me over a conceptual hump.
-- 
http://mail.python.org/mailman/listinfo/python-list


Sorting a dictionary

2009-05-12 Thread Ronn Ross
I'm attempting to sort for the results of a dictionary. I would like to
short by the 'key' in ascending order. I have already made several attempts
using: sorted() and .sort().
Here is my loop:
for key,value in word_count.items():
print sorted(key), "=", value

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


Python API Functions equivalent to ruby's rb_big2str() and rb_str2cstr()

2009-05-12 Thread rahul
Is functions equivalent to ruby's  rb_big2str() and rb_str2cstr()
available in Python.
I had search a lot in google but not able to find that.
If anybody know than please give me the name of those functions of
Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling Python on Windows : how to deal with modules ?

2009-05-12 Thread r2d3
Hi all,

after some investigation, I managed to find how to do this "manually".
I post it here if it could help others...

1) on windows, mostly all the dynamic libraries (time, socket, ...)
are statically linked into python26.dll
2) all the modules are located in lib/ and some .pyd (in fact renamed
dll files) live in PCbuild
3) "PCBuild\python -m compileall lib" will compile all the .py under
lib which then could by zipped into a single python26.zip

So I will just need to distribute python26.dll and python26.zip with
my app and set sys.path (using PySys_SetPath) to point to python26.zip
+ the place where I store the .pyd.

I will solve the "user want to add other module" later using
PYTHONPATH or allowing the user to add python path through our GUI.

Best regards.

On 11 mai, 10:49, r2d3  wrote:
> I am using Python embedded in my application (OSX,Windows) and I need
> to distribute Python as part of my application.
>
> On OSX, no problem, I got a self contained framework (with dynamic
> library and all the modules).
>
> On Windows, I manage to compile Python 2.6.2 with PCbuild\build.bat
> and I get python26.dll/python26_d.dll.
>
> But the readme gives no clue about how to deal with the module
> "compilation"/installation.
>
> So how do I "compile"/package all the modules that comes with Python
> source distribution on Windows ? To embed it in my distribution, I
> just copy the whole Modules tree (only pyc/pyo/pyd files ?) ? and set
> the right sys.path from my C code (using PySys_SetPath) ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread noydb
On May 11, 11:30 pm, Paul Rubin  wrote:
> noydb  writes:
> > Anyone have any good ideas?  I was curious to see what people came up
> > with.
>
> Is this a homework assignment?  Some hints:
>
> 1) figure out how to compare two month names for chronological order,
>    leaving out the issue of the starting month not being january.
> 2) figure out how to adjust for the starting month.  The exact
>    semantics of the "%" operator might help do this concisely.

Ha!  No, this is not a homework assignment.  I just find myself to be
not the most eloquent and efficient scripter and wanted to see how
others would approach it.

I'm not sure how I follow your suggestion.  I have not worked with the
%.  Can you provide a snippet of your idea in code form?

I thought about assigning a number string (like 'x_1') to any string
containing 'jan' -- so x_jan would become x_1, and so on.  Then I
could loop through with a counter on the position of the number (which
is something i will need to do, comparing one month to the next
chronological month, then that next month to its next month, and so
on).  And as for the starting postion, the user could declare, ie, aug
the start month.  aug is position 8.  therefore subtract 7 from each
value, thus aug becomes 1 but then I guess early months would have
to be add 5, such that july would become 12.  Ugh, seems sloppy to me.

Something like that   seems poor to me.  Anybody have a bteer
idea, existing code???
-- 
http://mail.python.org/mailman/listinfo/python-list


EURO NEWS FINALLY LAUNCHED THEIR BLOG

2009-05-12 Thread Aqeel Ahmed Rajpar
TO SUBSCRIBE THE BLOG VIA EMAIL VISIT

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


Re: Sorting a dictionary

2009-05-12 Thread Jaime Fernandez del Rio
This one I think I know... Try with:

for k in sorted(word_count) :
print k,"=",word_count[k]

You need to do the sorting before iterating over the keys...

Jaime

On Tue, May 12, 2009 at 1:54 PM, Ronn Ross  wrote:
> I'm attempting to sort for the results of a dictionary. I would like to
> short by the 'key' in ascending order. I have already made several attempts
> using: sorted() and .sort().
> Here is my loop:
>     for key,value in word_count.items():
>         print sorted(key), "=", value
>
> Thanks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python API Functions equivalent to ruby's rb_big2str() and rb_str2cstr()

2009-05-12 Thread Christian Heimes
rahul schrieb:
> Is functions equivalent to ruby's  rb_big2str() and rb_str2cstr()
> available in Python.
> I had search a lot in google but not able to find that.
> If anybody know than please give me the name of those functions of
> Python.

Please don't assume that we know what the Ruby functions are doing. You
need to explain them or at least provide a link to some docs.

Christian

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


Re: Sorting a dictionary

2009-05-12 Thread Andre Engels
On Tue, May 12, 2009 at 1:54 PM, Ronn Ross  wrote:
> I'm attempting to sort for the results of a dictionary. I would like to
> short by the 'key' in ascending order. I have already made several attempts
> using: sorted() and .sort().
> Here is my loop:
>     for key,value in word_count.items():
>         print sorted(key), "=", value

That won't work. "key" will each time be the specific key, which you
then try to sort. Instead you want to sort the _set_ of pairs by their
first element. Luckily the default sort order of a tuple is by the value
of its first element, so you can do:

for key,value in sorted(word_count.items()):
   print key, "=", value





-- 
André Engels, [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread bearophileHUGS
noydb:

> I have not worked with the %.
> Can you provide a snippet of your idea in code form?

Then it's a very good moment to learn using it:
http://en.wikipedia.org/wiki/Modulo_operator

>>> 10 % 3
1
>>> 10 % 20
10
>>> -10 % 3
2
>>> -10 % -3
-1


>Something like that<

Implement your first version, run it, and show us its output. Then I/
we can try to give you suggestions to improve your code.


>existing code???<

Sometimes you have to write code... that's life.

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


Re: putting date strings in order

2009-05-12 Thread Jaime Fernandez del Rio
If you simply want to generate an ordered list of months, start with
it in order:

dates = ["x_jan",...,"x_dec"]

and if the desired starting month is

start = 6 # i.e. x_jun

dates = dates[start - 1:] + dates[:start - 1]

If you have to sort the list itself, I would use an intermediate
dictionary to hold the positions, as in:

months = {"x_jan" : 1, ..., "x_dec" : 12}

You can then sort the list with :

dates.sort(None,lambda x : months[x])

and then do the

dates = dates[start - 1:] + dates[:start - 1]

or alternatively you can get the sorting directly as you want it with:

dates.sort(None,lambda x : (months[x] - start + 1) % 12)


Jaime



On Tue, May 12, 2009 at 1:58 PM, noydb  wrote:
> On May 11, 11:30 pm, Paul Rubin  wrote:
>> noydb  writes:
>> > Anyone have any good ideas?  I was curious to see what people came up
>> > with.
>>
>> Is this a homework assignment?  Some hints:
>>
>> 1) figure out how to compare two month names for chronological order,
>>    leaving out the issue of the starting month not being january.
>> 2) figure out how to adjust for the starting month.  The exact
>>    semantics of the "%" operator might help do this concisely.
>
> Ha!  No, this is not a homework assignment.  I just find myself to be
> not the most eloquent and efficient scripter and wanted to see how
> others would approach it.
>
> I'm not sure how I follow your suggestion.  I have not worked with the
> %.  Can you provide a snippet of your idea in code form?
>
> I thought about assigning a number string (like 'x_1') to any string
> containing 'jan' -- so x_jan would become x_1, and so on.  Then I
> could loop through with a counter on the position of the number (which
> is something i will need to do, comparing one month to the next
> chronological month, then that next month to its next month, and so
> on).  And as for the starting postion, the user could declare, ie, aug
> the start month.  aug is position 8.  therefore subtract 7 from each
> value, thus aug becomes 1 but then I guess early months would have
> to be add 5, such that july would become 12.  Ugh, seems sloppy to me.
>
> Something like that   seems poor to me.  Anybody have a bteer
> idea, existing code???
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.
-- 
http://mail.python.org/mailman/listinfo/python-list


About progress bar in glade

2009-05-12 Thread shruti surve
hi

i am using progress bar in glade and python file. When i clicked on menu
item, open office spreadsheet will be opened. but it takes some time to open
up, so i want to add progress bar. Now, when i clicked on menu item,dialog
with progress bar is coming and progress bar is pulsating but xml_rpc calls
running at back end stopped working. Once i close the dialog box,rpc start
working. But both should work simultaneously. What should i do for this??


regards

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


multithreading in python

2009-05-12 Thread shruti surve
hi,
 how to do multithreading in python??? Like running dialog box and running
xml rpc calls simultaneously???


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


Re: putting date strings in order

2009-05-12 Thread MRAB

noydb wrote:

On May 11, 11:30 pm, Paul Rubin  wrote:

noydb  writes:

Anyone have any good ideas?  I was curious to see what people came up
with.

Is this a homework assignment?  Some hints:

1) figure out how to compare two month names for chronological order,
   leaving out the issue of the starting month not being january.
2) figure out how to adjust for the starting month.  The exact
   semantics of the "%" operator might help do this concisely.


Ha!  No, this is not a homework assignment.  I just find myself to be
not the most eloquent and efficient scripter and wanted to see how
others would approach it.

I'm not sure how I follow your suggestion.  I have not worked with the
%.  Can you provide a snippet of your idea in code form?

I thought about assigning a number string (like 'x_1') to any string
containing 'jan' -- so x_jan would become x_1, and so on.  Then I
could loop through with a counter on the position of the number (which
is something i will need to do, comparing one month to the next
chronological month, then that next month to its next month, and so
on).  And as for the starting postion, the user could declare, ie, aug
the start month.  aug is position 8.  therefore subtract 7 from each
value, thus aug becomes 1 but then I guess early months would have
to be add 5, such that july would become 12.  Ugh, seems sloppy to me.

Something like that   seems poor to me.  Anybody have a bteer
idea, existing code???


Sort the list, passing a function as the 'key' argument. The function
should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
you want to have a different start month then add the appropriate
integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
to make it wrap around (there are only 12 months in a year), returning
the result.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python API Functions equivalent to ruby's rb_big2str() and rb_str2cstr()

2009-05-12 Thread rahul
On May 12, 5:25 pm, Christian Heimes  wrote:
> rahul schrieb:
>
> > Is functions equivalent to ruby's  rb_big2str() and rb_str2cstr()
> > available in Python.
> > I had search a lot in google but not able to find that.
> > If anybody know than please give me the name of those functions of
> > Python.
>
> Please don't assume that we know what the Ruby functions are doing. You
> need to explain them or at least provide a link to some docs.
>
> Christian

Hi Christian,
  rb_big2str(Big-Integer, base) of ruby returns string representation
of big-Integer. now, i am able to find equivalent python API function
of rb_str2cstr() of ruby.
so , please help me about rb_big2str(Big-Integer, base) equivalent of
Python API function which i can use in extended module in c.

---
 rahul

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


Re: multithreading in python

2009-05-12 Thread Almar Klein
See the standard help on the threading and thread module.

Almar

2009/5/12 shruti surve :
> hi,
>  how to do multithreading in python??? Like running dialog box and running
> xml rpc calls simultaneously???
>
>
> regards
> shruti
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-12 Thread rumpf_a
> There are two showstoppers for me though:
>
> 1. Introducing a new programming language where the char type is a
> byte is anachronistic. You're saying that programmers don't have to
> care about the string encoding and can just treat them as an array of
> bytes. That is exactly what causes all the problems with applications
> that haven't been designed to handle anything but ASCII. If you're
> doing any logic with strings except dumb reading and writing, you
> typically *have to* know the encoding. Forcing programmers to be aware
> of this problem is a good idea IMO.
>
> You can certainly have a string type that uses byte arrays in UTF-8
> encoding internally, but your string functions should be aware of that
> and treat it as a unicode string. The len function and index operators
> should count characters, not bytes. Add a byte array data type for
> byte arrays instead.
>
It's not easy. I think Python3's byte arrays have an "upper" method
(and a string literal syntax b"abc") which is quite alarming to me
that they chose the wrong default.

Eventually the "rope" data structure (that the compiler uses heavily)
will become a proper part of the library: By "rope" I mean an
immutable string implemented as a tree, so concatenation is O(1). For
immutable strings there is no ``[]=`` operation, so using UTF-8 and
converting it to a 32bit char works better.

> 2. The dynamic dispatch is messy. I agree that procedural is often
> simpler and more efficient than object-oriented programming, but
> object-oriented programming is useful just as often and should be made
> a simple as possible. Since Nimrod seems flexible, perhaps it would be
> possible to implement an object-orientation layer in Nimrod that hides
> the dynamic dispatch complexity?
>
Yes, I already have an idea how to improve it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a GUI for informing a user of missing dependencies?

2009-05-12 Thread Dave Angel



Jason wrote:

I'm writing a small GUI (Python 2.5/6) using wxPython and pySerial.
Since these are both 3rd party modules, if a user doesn't have them
installed and tries to run the GUI from a file browser, the app will
fail silently. I'm hoping to avoid that.

Sure, I'll have a readme file, but I was wondering if there is an even
more direct way. I was going to roll my own (eg. very simple Tkinter
fallback error dialog if wxPython import fails, wxPython error dialog
if anything else is missing); but I was wondering if such a system
already exists out there.

— Jason

  

One approach is something like:

import subprocess

errorstring = "echo XXX error occurred in my code. type 'exit' to close 
this shell window "

parms = ["cmd.exe", "/k"]
parms.append( errorstring )
subprocess.call(parms)

Any message can be built as long as it fits on one "line". And if more 
is needed, a batch file can be run instead of just "echo" at the 
beginning of the errorstring.


The user gets a command shell that he can then use to investigate 
various things, such as environment variables. And the shell goes away 
when he types the command "exit". The python program doesn't terminate 
till the user does so.


This is Windows specific, so certainly your Tkinter approach is more 
general. On the other hand, the user might have a subset of the standard 
Python installed, and Tkinter might have been deleted from his system.


If it has to work on older Python versions, you might go with 
os.system() or other similar things.


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


AssertionError - help me to solve this in a programme with Queue

2009-05-12 Thread gganesh
Hi all,
I'm just learning python ,the code below is found in one of the
sites ,it produces an error like
Traceback (most recent call last):
  File "queue.py", line 34, in 
main()
  File "queue.py", line 28, in main
t=MyThread(q)
  File "/usr/lib/python2.5/threading.py", line 398, in __init__
assert group is None, "group argument must be None for now"
AssertionError: group argument must be None for now

can any one help me to find the reason

the code I wrote is


hosts =["http://yahoo.com";, "http://google.com";]

# create a queue class
q=Queue.Queue()

#Thread class
class MyThread(threading.Thread):
# define __int__ method acting like constructor
def __int__(self,q):
threading.Thread.__init__(self)
self.q=q
def run(self):
h=self.q.get()
opens=urllib2.urlopen(h)
print opens.read(100)

# signal the queue to say job is done
self.q.task_done()
a=time.time()
def main():
# create a pool of thread
for i in range(5):
t=MyThread(q)
t.setDaemon(True)
t.start()
for h in hosts:
queue.put(h)
q.join()
main()
print "Time elasped : %s "%(time.time()-a)


The problem may be silly ,hence I'm every new to python i need your
guidance .


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


Re: putting date strings in order

2009-05-12 Thread John Machin
MRAB  mrabarnett.plus.com> writes:
> 
> Sort the list, passing a function as the 'key' argument. The function
> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> you want to have a different start month then add

and if you don't like what that produces, try subtract :-)

> the appropriate
> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> to make it wrap around (there are only 12 months in a year), returning
> the result.

HTH,
John


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


Re: Nimrod programming language

2009-05-12 Thread rumpf_a
> > > The language and library are missing arbitrary precision integer
> > > arithmetic, using GMP or something like that.
>
> > True, but currently not a high priority for me.
>
> Too bad. That makes Nimrod officially "worthless", i.e., of no
> value to me.
>
Well, you could write a wrapper for GMP (and contribute to the
project ;-)).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write loop (was "no subject")

2009-05-12 Thread Dave Angel

karlos barlos wrote:
hello to all 


i have been using this script to add users to my active directory structure

i wise to make a loop in order for it to run for A large Number of Users 


can anyone give me some advice on the loop ??



import win32com,win32com.client
def add_acct(location,account):

  ad_obj=win32com.client.GetObject(location)

  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')

  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  ad_user.setpassword('the password')
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()


location='LDAP://OU=sales,DC=shay,DC=com'
user={'first':'shay','last':'smith','login':'shay123'}
add_acct(location,user)


location='LDAP://OU=sales,DC=shay,DC=com'
user={'first':'ron','last':'smith','login':'ron1267'}
add_acct(location,user)



  

Your formal parameter "account" needs to be "user" to match the references.

What could be a loop?  You have two users added at the bottom which 
could be done as a loop, but only if you have some structure to loop 
over.  So before you make it a loop, you have to decide what that 
structure is, and whether creating it is more work than just continuing 
with your present model of an unrolled loop.


Examples of structures might be:
   a list of user information.  But building that list would be as much 
work as you have now.
   a text file.  Good idea.  It might be populated with Excel, or any 
other program that can produce a csv file, or a formatted text file.  Or 
it might be populated with a text editor, with verification.
   an interactive session.  The user types in the information one user 
at  a time, into a form.  You just loop through, presenting the form, 
and processing the information entered.
an existing user database.  This might be  a loop that transfers 
information from one format to another.


Decide the structure, and you can readily write the loop.

  
  

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


Re: AssertionError - help me to solve this in a programme with Queue

2009-05-12 Thread MRAB

gganesh wrote:

Hi all,
I'm just learning python ,the code below is found in one of the
sites ,it produces an error like
Traceback (most recent call last):
  File "queue.py", line 34, in 
main()
  File "queue.py", line 28, in main
t=MyThread(q)
  File "/usr/lib/python2.5/threading.py", line 398, in __init__
assert group is None, "group argument must be None for now"
AssertionError: group argument must be None for now

can any one help me to find the reason

the code I wrote is


hosts =["http://yahoo.com";, "http://google.com";]

# create a queue class
q=Queue.Queue()

#Thread class
class MyThread(threading.Thread):
# define __int__ method acting like constructor
def __int__(self,q):

  ^^^
  Should be __init__.


threading.Thread.__init__(self)
self.q=q
def run(self):
h=self.q.get()
opens=urllib2.urlopen(h)
print opens.read(100)

# signal the queue to say job is done
self.q.task_done()
a=time.time()
def main():
# create a pool of thread
for i in range(5):
t=MyThread(q)
t.setDaemon(True)
t.start()
for h in hosts:
queue.put(h)
q.join()
main()
print "Time elasped : %s "%(time.time()-a)


The problem may be silly ,hence I'm every new to python i need your
guidance .




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


Re: About progress bar in glade

2009-05-12 Thread shruti surve
On Tue, May 12, 2009 at 6:19 PM, shruti surve  wrote:

> hi
>
> i am using progress bar in glade and python file. When i clicked on menu
> item, open office spreadsheet will be opened. but it takes some time to open
> up, so i want to add progress bar. Now, when i clicked on menu item,dialog
> with progress bar is coming and progress bar is pulsating but other
> processes at front end  stopped working. So,its  blocking all other
> processes. But both should work simultaneously. What should i do for this??
>
>
> regards
>
> shruti
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nimrod programming language

2009-05-12 Thread rumpf_a
> > That is already the case: The Pascal version is translated to Nimrod
> > and than compiles itself. Bootstrapping works.
>
> I meant why not get rid of the translation step and implement the
> compiler in idiomatic Nimrod.
>
Not until version 1.0 is out. This way the language can evolve more
easily.

> > The plan is to use LLVM as a backend and perhaps
> >http://tinystm.org/. Of course, this is only wishful thinking. ;-)
>
> Oh cool, I didn't know about tinystm.  But, my question about
> mutability is how you protect STM transactions when other threads can
> have references into shared mutable structures and clobber the
> referents.  GHC uses its type system to prevent that, but I don't see
> how Nimrod can really do the same, especially without GHC's rich set
> of immutable types including stuff like immutable maps.
>
Well STM transactions in an imperative context are still being
actively researched. Sorry I have no better answer.

> Have you ever looked at Tim Sweeney's presentation "The Next
> Mainstream Programming Language"?
Yes. It's awsome. But the next mainstream programming language also
needs a massive amount of money to take off, so I don't think it will
be Nimrod. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AssertionError - help me to solve this in a programme with Queue

2009-05-12 Thread gganesh
On May 12, 6:34 pm, MRAB  wrote:
> gganesh wrote:
> > Hi all,
> > I'm just learning python ,the code below is found in one of the
> > sites ,it produces an error like
> > Traceback (most recent call last):
> >   File "queue.py", line 34, in 
> >     main()
> >   File "queue.py", line 28, in main
> >     t=MyThread(q)
> >   File "/usr/lib/python2.5/threading.py", line 398, in __init__
> >     assert group is None, "group argument must be None for now"
> > AssertionError: group argument must be None for now
>
> > can any one help me to find the reason
>
> > the code I wrote is
>
> > hosts =["http://yahoo.com";, "http://google.com";]
>
> > # create a queue class
> > q=Queue.Queue()
>
> > #Thread class
> > class MyThread(threading.Thread):
> >    # define __int__ method acting like constructor
> >    def __int__(self,q):
>
>                ^^^
>                Should be __init__.
>
> >            threading.Thread.__init__(self)
> >            self.q=q
> >    def run(self):
> >            h=self.q.get()
> >            opens=urllib2.urlopen(h)
> >            print opens.read(100)
>
> >            # signal the queue to say job is done
> >            self.q.task_done()
> > a=time.time()
> > def main():
> >    # create a pool of thread
> >    for i in range(5):
> >            t=MyThread(q)
> >            t.setDaemon(True)
> >            t.start()
> >    for h in hosts:
> >            queue.put(h)
> >    q.join()
> > main()
> > print "Time elasped : %s "%(time.time()-a)
>
> > The problem may be silly ,hence I'm every new to python i need your
> > guidance .
>
>

hi
It did work that way

File "queue.py", line 15
threading.Thread__init__.(self)
 ^
SyntaxError: invalid syntax


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


Re: Python API Functions equivalent to ruby's rb_big2str() and rb_str2cstr()

2009-05-12 Thread Hrvoje Niksic
rahul  writes:

> Hi Christian,
>   rb_big2str(Big-Integer, base) of ruby returns string representation
> of big-Integer. now, i am able to find equivalent python API function
> of rb_str2cstr() of ruby.

That would be PyLong_FromString, for the sake of later searches.

> so , please help me about rb_big2str(Big-Integer, base) equivalent of
> Python API function which i can use in extended module in c.

You can use PyObject_Str(long_object) to convert long to string.  No
special function is needed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AssertionError - help me to solve this in a programme with Queue

2009-05-12 Thread Diez B. Roggisch
gganesh wrote:

> On May 12, 6:34 pm, MRAB  wrote:
>> gganesh wrote:
>> > Hi all,
>> > I'm just learning python ,the code below is found in one of the
>> > sites ,it produces an error like
>> > Traceback (most recent call last):
>> > File "queue.py", line 34, in 
>> > main()
>> > File "queue.py", line 28, in main
>> > t=MyThread(q)
>> > File "/usr/lib/python2.5/threading.py", line 398, in __init__
>> > assert group is None, "group argument must be None for now"
>> > AssertionError: group argument must be None for now
>>
>> > can any one help me to find the reason
>>
>> > the code I wrote is
>>
>> > hosts =["http://yahoo.com";, "http://google.com";]
>>
>> > # create a queue class
>> > q=Queue.Queue()
>>
>> > #Thread class
>> > class MyThread(threading.Thread):
>> > # define __int__ method acting like constructor
>> > def __int__(self,q):
>>
>> ^^^
>> Should be __init__.
>>
>> > threading.Thread.__init__(self)
>> > self.q=q
>> > def run(self):
>> > h=self.q.get()
>> > opens=urllib2.urlopen(h)
>> > print opens.read(100)
>>
>> > # signal the queue to say job is done
>> > self.q.task_done()
>> > a=time.time()
>> > def main():
>> > # create a pool of thread
>> > for i in range(5):
>> > t=MyThread(q)
>> > t.setDaemon(True)
>> > t.start()
>> > for h in hosts:
>> > queue.put(h)
>> > q.join()
>> > main()
>> > print "Time elasped : %s "%(time.time()-a)
>>
>> > The problem may be silly ,hence I'm every new to python i need your
>> > guidance .
>>
>>
> 
> hi
> It did work that way
> 
> File "queue.py", line 15
> threading.Thread__init__.(self)
>  ^
> SyntaxError: invalid syntax

Because you messed up the .

threading.THread.__init__(self)

Please spend at least a couple of hours with the tutorial.

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


Re: AssertionError - help me to solve this in a programme with Queue

2009-05-12 Thread maxim

> hi
> It did work that way
>
> File "queue.py", line 15
>     threading.Thread__init__.(self)
>                              ^
> SyntaxError: invalid syntax

You've wrote right first time "threading.Thread.__init__(slef)", but
misprinted in your code "def _int_(self,q)" instead of "def __init__
(self,q)".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread MRAB

John Machin wrote:

MRAB  mrabarnett.plus.com> writes:

Sort the list, passing a function as the 'key' argument. The function
should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
you want to have a different start month then add


and if you don't like what that produces, try subtract :-)


Oops!


the appropriate
integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
to make it wrap around (there are only 12 months in a year), returning
the result.



Actually, subtract the start month, add 12, and then modulo 12.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-12 Thread Peter Pearson
On 12 May 2009 09:35:36 GMT, Steven D'Aprano wrote:
[snip]
> To really be safe, that should become:
>
> try:
> rsrc = get(resource)
> except ResourceError:
> log('no more resources available')
> raise
> else:
> try:
> do_something_with(rsrc)
> finally:
> rsrc.close()

Thanks, Steven.  I find these examples illuminating.

Not trying to be dense, but given that the "except" block
re-raises the exception, isn't the above the same as . . .?

try:
rsrc = get(resource)
except ResourceError:
log('no more resources available')
raise
try:
do_something_with(rsrc)
finally:
rsrc.close()

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread Jaime Fernandez del Rio
On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:
> John Machin wrote:
>>
>> MRAB  mrabarnett.plus.com> writes:
>>>
>>> Sort the list, passing a function as the 'key' argument. The function
>>> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
>>> you want to have a different start month then add
>>
>> and if you don't like what that produces, try subtract :-)
>>
> Oops!
>
>>> the appropriate
>>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
>>> to make it wrap around (there are only 12 months in a year), returning
>>> the result.
>>
> Actually, subtract the start month, add 12, and then modulo 12.

Both on my Linux and my Windows pythons, modulos of negative numbers
are properly taken, returning always the correct positive number
between 0 and 11. I seem to recall, from my distant past, that Perl
took pride on this being a language feature. Anyone knows if that is
not the case with python, and so not adding 12 before taking the
modulo could result in wrong results in some implementations?

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



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread John Machin
On May 13, 1:02 am, MRAB  wrote:
> John Machin wrote:
> > MRAB  mrabarnett.plus.com> writes:
> >> Sort the list, passing a function as the 'key' argument. The function
> >> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> >> you want to have a different start month then add
>
> > and if you don't like what that produces, try subtract :-)
>
> Oops!
>
> >> the appropriate
> >> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> >> to make it wrap around (there are only 12 months in a year), returning
> >> the result.
>
> Actually, subtract the start month, add 12, and then modulo 12.

Ummm ... 12 modulo 12 is a big fat zero, and Python's % is a genuine
modulo operator; unlike that of K&R C, it's defined not to go wobbly
on negatives.

| >>> [(i - 8 + 12) % 12 for i in range(12)]
| [4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3]

| >>> [(i - 8 ) % 12 for i in range(12)]
| [4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3]
-- 
http://mail.python.org/mailman/listinfo/python-list


Call Web Service using proxy and http authentication

2009-05-12 Thread wdveloper
Hi everyone,

I am trying to call a webservice which requires an http
authentication.
To reach the ws, I must pass from a proxy http. So in the whole I need
go through two authentications before getting the ws working. I am
using SOAPpy and I'm getting quite crazy.
I am able to arrange this problem with simple http calls using urllib2
but for the ws i dont see any way out.

Does anyone knows how I can manage this stuff? Is there any better
solution or example code?

Thanks very much for your help,
totobe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python API Functions equivalent to ruby's rb_big2str() and rb_str2cstr()

2009-05-12 Thread John Machin
On May 12, 11:48 pm, Hrvoje Niksic  wrote:
> rahul  writes:
> > Hi Christian,
> >   rb_big2str(Big-Integer, base) of ruby returns string

*base*

>representation
> > of big-Integer. now, i am able to find equivalent python API function
> > of rb_str2cstr() of ruby.
>
> That would be PyLong_FromString, for the sake of later searches.
>
> > so , please help me about rb_big2str(Big-Integer, base)

*base*

> equivalent of
> > Python API function which i can use in extended module in c.
>
> You can use PyObject_Str(long_object) to convert long to string.  No
> special function is needed.

ALL of your base are want to be convert by us -- not merely 10.

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


Re: putting date strings in order

2009-05-12 Thread MRAB

Jaime Fernandez del Rio wrote:

On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:

John Machin wrote:

MRAB  mrabarnett.plus.com> writes:

Sort the list, passing a function as the 'key' argument. The function
should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
you want to have a different start month then add

and if you don't like what that produces, try subtract :-)


Oops!


the appropriate
integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
to make it wrap around (there are only 12 months in a year), returning
the result.

Actually, subtract the start month, add 12, and then modulo 12.


Both on my Linux and my Windows pythons, modulos of negative numbers
are properly taken, returning always the correct positive number
between 0 and 11. I seem to recall, from my distant past, that Perl
took pride on this being a language feature. Anyone knows if that is
not the case with python, and so not adding 12 before taking the
modulo could result in wrong results in some implementations?


Ah, yes, it's a true modulo! Nice to see that Python gets it right! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread John Machin
On May 13, 1:58 am, Jaime Fernandez del Rio 
wrote:
> On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:
> > John Machin wrote:
>
> >> MRAB  mrabarnett.plus.com> writes:
>
> >>> Sort the list, passing a function as the 'key' argument. The function
> >>> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> >>> you want to have a different start month then add
>
> >> and if you don't like what that produces, try subtract :-)
>
> > Oops!
>
> >>> the appropriate
> >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> >>> to make it wrap around (there are only 12 months in a year), returning
> >>> the result.
>
> > Actually, subtract the start month, add 12, and then modulo 12.
>
> Both on my Linux and my Windows pythons, modulos of negative numbers
> are properly taken, returning always the correct positive number
> between 0 and 11. I seem to recall, from my distant past, that Perl
> took pride on this being a language feature. Anyone knows if that is
> not the case with python, and so not adding 12 before taking the
> modulo could result in wrong results in some implementations?

If that happens, it's a bug.
http://docs.python.org/reference/expressions.html#binary-arithmetic-operations

If you look at function i_divmod() in the 2.x branch's Objects/
intobject.c, you'll be reassured to see that it doesn't just take
whatever C serves up :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: piping input to an external script

2009-05-12 Thread norseman

Steve Howell wrote:

On May 11, 11:31 pm, norseman  wrote:

Steve Howell wrote:

On May 11, 10:16 pm, norseman  wrote:

Tim Arnold wrote:

Hi, I have some html files that I want to validate by using an external
script 'validate'. The html files need a doctype header attached before
validation. The files are in utf8 encoding. My code:
---
import os,sys
import codecs,subprocess
HEADER = ''
filename  = 'mytest.html'
fd = codecs.open(filename,'rb',encoding='utf8')
s = HEADER + fd.read()
fd.close()
p = subprocess.Popen(['validate'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
validate = p.communicate(unicode(s,encoding='utf8'))
print validate
---
I get lots of lines like this:
Error at line 1, character 66:\tillegal character number 0
etc etc.
But I can give the command in a terminal 'cat mytest.html | validate' and
get reasonable output. My subprocess code must be wrong, but I could use
some help to see what the problem is.
python2.5.1, freebsd6
thanks,
--Tim


If you search through the recent Python-List for UTF-8 things you might
get the same understanding I have come to.
the problem is the use of python's 'print' subcommand or what ever it
is. It 'cooks' things and someone decided that it would only handle 1/2
of a byte (in the x'00 to x'7f' range) and ignore or send error messages
against anything else. I guess the person doing the deciding read the
part that says ASCII printables are in the 7 bit range and chose to
ignore the part about the rest of the byte being undefined. That is
undefined, not disallowed.  Means the high bit half can be used as
wanted since it isn't already taken. Nor did whoever it was take a look
around the computer world and realize the conflict that was going to be
generated by using only 1/2 of a byte in a 1byte+ world.
If you can modify your code to use read and write you can bypass print
and be OK.  Or just have python do the 'cat mytest.html | validate' for
you. (Apply a var for html and let python accomplish the the equivalent
of Unix's:
for f in *.html; do cat $f | validate; done
 or
 for f in *.html; do validate $f; done  #file name available this way
If you still have problems, take a look at os.POPEN2 (and its popen3)
Also take look at os.spawn.. et al

Wow.  Unicode and subprocessing and printing can have dark corners,
but common sense does apply in MOST situations.
If you send the header, add the newline.
But you do not need the header if you can cat the input file sans
header and get sensible input.

Yep!  The problem is with 'print'



Huh?  Print is printing exactly what you expect it to print.


===
My apologies.

Tim: Using what you posted;
Is the third char of the first line read from file a TAB?

Just curious.  len(HEADER) is 63, error at 66  char number 0, doesn't 
seem quite consistent math wise.

63 + cr + lf gives 65.  But, as another noted, you don't have those.
"...66:\tillegal..."  is '\t' a tab on screen or byte 1 or 3 of file?
If you have mc available, in it - highlight file and press Shift-F3 then 
F4.  09 is TAB


 is closing, should not exist as opener
   can be opener, did the h somehow become a '\'
 (still - that would put x'09' at byte 2 of file)

Most validate programs I have used will let me know the header is 
missing if in fact it is and give me a choice of how to process (XML, 
XHTML, HTML 1.1, ...) or quit.


is HEADER ('') itself already in utf-8?
Or are you mixing things?

Last but not least - if you have source of validate process, check that 
over carefully.  The numbers don't work for me.


Just thinking on paper. No need to respond.

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


Re: Nimrod programming language

2009-05-12 Thread Mensanator
On May 12, 8:27 am, [email protected] wrote:
> > > > The language and library are missing arbitrary precision integer
> > > > arithmetic, using GMP or something like that.
>
> > > True, but currently not a high priority for me.
>
> > Too bad. That makes Nimrod officially "worthless", i.e., of no
> > value to me.
>
> Well, you could write a wrapper for GMP (and contribute to the
> project ;-)).

But such a thing already exists in Python. And I spend my time
USING arbitrary precision numbers to do math research.

Just thought you'ld like to be aware that some people actually
make their language choices based on the availability (and
performance)
of arbitrary precision numbers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re:

2009-05-12 Thread norseman

karlos barlos wrote:
hello to all 


i have been using this script to add users to my active directory structure

i wise to make a loop in order for it to run for A large Number of Users 


can anyone give me some advice on the loop ??



import win32com,win32com.client
def add_acct(location,account):

  ad_obj=win32com.client.GetObject(location)

  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')

  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  ad_user.setpassword('the password')
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()


location='LDAP://OU=sales,DC=shay,DC=com'
user={'first':'shay','last':'smith','login':'shay123'}
add_acct(location,user)


location='LDAP://OU=sales,DC=shay,DC=com'

DC=ron  yes?

user={'first':'ron','last':'smith','login':'ron1267'}
add_acct(location,user)




  


===
.
.
def add_acct(location,account):
 OK



presumably you are reading from a list of names in a file
names= open(..)
Now you need a loop
for name in names:
  the location=  needs a variable in place of shay ('name' in this case)
  user=  this needs more explanation from you
 seems to be an attempt at alphabetizing
 if so:  presort the file with list of names
   or better yet
 just read them in and sort entire list afterwards to
 final file or python list (see python index)
  add name to listTemp
for user in list already existing:
  add user to listTemp
for user in list.Temp.index():
  copy to ListSorted
  reset first/last as needed
for user in ListSorted:
  store it someplace  (like your data file)


I suspect some of the add_.. function will need some mods, but maybe not
If 'shay123' is line number, track it in 'copy to ListSorted' section.
If the number is user id, assign it in source file.
(name id 1 pair per line, adjust read,etc to accommodate)

Today is: 20090512
no code this section

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


Re: piping input to an external script

2009-05-12 Thread Steve Howell
See suggested debugging tip inline of your program

On May 11, 11:04 am, "Tim Arnold"  wrote:
> Hi, I have some html files that I want to validate by using an external
> script 'validate'. The html files need a doctype header attached before
> validation. The files are in utf8 encoding. My code:
> ---
> import os,sys
> import codecs,subprocess
> HEADER = ''
>
> filename  = 'mytest.html'
> fd = codecs.open(filename,'rb',encoding='utf8')
> s = HEADER + fd.read()

# Try inserting lines like below, to see what characters are actually
near char 66.
print '---'
print repr(s[65])
print repr(s[66])
print repr(s[:70])
print repr(unicode(s,encoding='utf8')[:70])
print '---'

> fd.close()
>
> p = subprocess.Popen(['validate'],
>                     stdin=subprocess.PIPE,
>                     stdout=subprocess.PIPE,
>                     stderr=subprocess.STDOUT)
> validate = p.communicate(unicode(s,encoding='utf8'))
> print validate
> ---
>
> I get lots of lines like this:
> Error at line 1, character 66:\tillegal character number 0
> etc etc.
>

See above, it's pretty easy to see what the 66th character of "s" is.

> But I can give the command in a terminal 'cat mytest.html | validate' and
> get reasonable output. My subprocess code must be wrong, but I could use
> some help to see what the problem is.
>

Your disconnect is that in your program you are NOT actually
simulating the sending of mytest.html to the validate program, so you
are comparing apples and oranges.

The fact that you can send mytest.html to the validate program without
a header from the shell suggest to me that it is equally unnecessary
in your Python program, or maybe you just haven't thought through what
you're really trying to accomplish here.

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


Re: Nimrod programming language

2009-05-12 Thread George Sakkis
On May 12, 12:49 pm, Mensanator  wrote:
> On May 12, 8:27 am, [email protected] wrote:
>
> > > > > The language and library are missing arbitrary precision integer
> > > > > arithmetic, using GMP or something like that.
>
> > > > True, but currently not a high priority for me.
>
> > > Too bad. That makes Nimrod officially "worthless", i.e., of no
> > > value to me.
>
> > Well, you could write a wrapper for GMP (and contribute to the
> > project ;-)).
>
> But such a thing already exists in Python. And I spend my time
> USING arbitrary precision numbers to do math research.
>
> Just thought you'ld like to be aware that some people actually
> make their language choices based on the availability (and
> performance)
> of arbitrary precision numbers.

I'm sure developers of a new language have to deal with much more
pressing issues before accommodating each and every self important
niche.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to consume .NET webservice

2009-05-12 Thread namekuseijin
On May 12, 4:12 am, "Diez B. Roggisch"  wrote:
> namekuseijin schrieb:
>  > Diez B. Roggisch wrote:
>  >> namekuseijin schrieb:
>  >>> bav escreveu:
>   question from a python newbie;
>  
>     how can i consume in python language, a .NET web service, passing
>     a string array as parameter in some easy steps?
>  >>>
>  >>> Unless Microsoft extended the standard in any way, then it should
> be just as you consume any web service, I guess. ;)
>  >>
>  >> Microsoft *created* the standard..
>  >
>  > No:
>
> Yes:
>
> http://webservices.xml.com/pub/a/ws/2001/04/04/soap.html

You are right, sorry.

> MS created it. That it *became* a standard of the W3C later - well, they
> did that with OOXML as well...

OpenOfficeXML document format AKA ODF? ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to consume .NET webservice

2009-05-12 Thread Mike Driscoll
On May 12, 12:54 pm, namekuseijin  wrote:
> On May 12, 4:12 am, "Diez B. Roggisch"  wrote:
>
>
>
> > namekuseijin schrieb:
> >  > Diez B. Roggisch wrote:
> >  >> namekuseijin schrieb:
> >  >>> bav escreveu:
> >   question from a python newbie;
> >  
> >     how can i consume in python language, a .NET web service, passing
> >     a string array as parameter in some easy steps?
> >  >>>
> >  >>> Unless Microsoft extended the standard in any way, then it should
> > be just as you consume any web service, I guess. ;)
> >  >>
> >  >> Microsoft *created* the standard..
> >  >
> >  > No:
>
> > Yes:
>
> >http://webservices.xml.com/pub/a/ws/2001/04/04/soap.html
>
> You are right, sorry.
>
> > MS created it. That it *became* a standard of the W3C later - well, they
> > did that with OOXML as well...
>
> OpenOfficeXML document format AKA ODF? ;)

No...Office Open XML, which is used in Microsoft Office 2007 and which
Microsoft rammed through the ISO: http://en.wikipedia.org/wiki/Office_Open_XML

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


How to abort module evaluation?

2009-05-12 Thread mrstevegross
I have a python script that is pretty simple: when executed, it
imports a bunch of stuff and then runs some logic. When *imported*, it
defines some variables and exits. Here's what it looks like:

=== foo.py ===
if __name__ != '__main__':
  x = 1
  exit_somehow

import bar
do_some_stuff...
=== EOF ===

There's a problem, though. On line 3, I wrote "exit_somehow".
Actually, I have no idea how to do that part. Is there some way I can
get python to abandon processing the rest of the script at that point?
I know goto doesn't exist, so that's not an option... sys.exit() won't
work, because that will abort the entire python interpreter, rather
than just the evaluation of the module.

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


Re: Call Web Service using proxy and http authentication

2009-05-12 Thread Steve Howell
On May 12, 8:59 am, wdveloper  wrote:
> Hi everyone,
>
> I am trying to call a webservice which requires an http
> authentication.
> To reach the ws, I must pass from a proxy http. So in the whole I need
> go through two authentications before getting the ws working. I am
> using SOAPpy and I'm getting quite crazy.
> I am able to arrange this problem with simple http calls using urllib2
> but for the ws i dont see any way out.
>
> Does anyone knows how I can manage this stuff? Is there any better
> solution or example code?
>

Your high level description of the problem is good, but I think you'll
get more help if you provide a little more detail.

For something like this you may want to try to do more at the HTTP
level, where you have a little more control over the authentication,
and then find a way to hook into SOAPpy just to build and parse the
payloads.

How good is your understanding of HTTP?  Do you know the basics of how
headers work?  You might want to brush up a little on HTTP just to
help understand what's going on; it will almost certainly be valuable
for future projects as well.

To understand how the proxy works in particular, if you can use the
proxy to access a normal html-serving website, you can use the "Live
HTTP Headers" tool under Firefox to see what's going on.

But before all that, I would maybe just post a little more detail on
the problem.  Maybe show code you've written so far, and any error
messages/tracebacks, to better indicate where you are stuck.

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


Re: Nimrod programming language

2009-05-12 Thread namekuseijin
On May 8, 12:48 pm, Andreas Rumpf  wrote:
> Dear Python-users,
>
> I invented a new programming language called "Nimrod" that combines Python's 
> readability with C's performance. Please check it out:http://force7.de/nimrod/
> Any feedback is appreciated.

heh, looks more like a streamlined Object Pascal (i.e class
declarations) than Python.  And indeed I see that it has a nice bridge
to old Object Pascal code.

OTOH, Python always felt to me very close to Pascal in the choice of
syntax keywords and readability.  Some people of late have been
comparing Python to Basic, but I guess that's only to widespread it
more among the american public, where Pascal as foreign tech never
quite grasped foot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping comments

2009-05-12 Thread Piet van Oostrum
> Lawrence D'Oliveiro  (LD) wrote:

>LD> In message , Nick Craig-
>LD> Wood wrote:

>>> Rhodri James  wrote:
>>> 
 Emacs is my editor of choice ...
>>> 
>>> You probably haven't used MAC OS X then!

>LD> I tried using Emacs via SSH from a Mac once. Made me run screaming for the 
>LD> nearest Windows box 

The standard Windows box doesn't even have SSH AFAIK.

I edit remote files on my local Emacs on Mac OS X with tramp,
certainly when they are on a SSH-accessible machine.
Works like a charm.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: confused with subprocess.Popen

2009-05-12 Thread Roy Hyunjin Han
There's a great article by Doug Hellmann on subprocess.
http://www.doughellmann.com/PyMOTW/subprocess/

On Sun, May 10, 2009 at 1:37 AM, Soumen banerjee  wrote:
> Thanks!, i have found that alternately setting shell=True also works
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Language detector using N-grams

2009-05-12 Thread Cesar D. Rodas
Hello Pythoners!

I just finished my first useful project in Python, It is a language
detector using N-grams. I hope this can be useful for someone,

http://github.com/crodas/py-languess/tree/master

The License of the project is BSD

Best regards

-- 
Cesar D. Rodas
http://cesar.la/
Phone: +595-961-974165
Jay Leno  - "Don't forget Mother's Day. Or as they call it in Beverly
Hills, Dad's Third Wife Day." -
http://www.brainyquote.com/quotes/authors/j/jay_leno.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue with twisted and reactor. Can't stop reactor

2009-05-12 Thread Nick Craig-Wood
Gabriel  wrote:
>  Jean-Paul Calderone escribió:
>  > None of the reactors in Twisted are restartable.  You can run and
>  stop them
> > once.  After you've stopped a reactor, you cannot run it again.  This is
> > the
> > cause of your problem.
> > 
> > Jean-Paul
> 
>  I see.
>  Is it possible to do what I want using twisted? or
>  I should found another way?

You have to go twisted...

Your program should call reactor.run() once and everything you need
your program to do should be started off from twisted callbacks (eg
timer callbacks or deferred objects).

To get your program to do something immediately after it is started,
use reactor.callLater() before calling reactor.run().

You can't mix and match programming styles with twisted - it is all
asynchronous callbacks or nothing in my experience!  That takes a bit
of getting your head round at first.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to abort module evaluation?

2009-05-12 Thread Mike Driscoll
On May 12, 1:33 pm, mrstevegross  wrote:
> I have a python script that is pretty simple: when executed, it
> imports a bunch of stuff and then runs some logic. When *imported*, it
> defines some variables and exits. Here's what it looks like:
>
> === foo.py ===
> if __name__ != '__main__':
>   x = 1
>   exit_somehow
>
> import bar
> do_some_stuff...
> === EOF ===
>
> There's a problem, though. On line 3, I wrote "exit_somehow".
> Actually, I have no idea how to do that part. Is there some way I can
> get python to abandon processing the rest of the script at that point?
> I know goto doesn't exist, so that's not an option... sys.exit() won't
> work, because that will abort the entire python interpreter, rather
> than just the evaluation of the module.
>
> Thanks,
> --Steve

Isn't abandoning the processing of the rest of the script exiting the
script? You could use "return" or wrap the offending code in a try/
except block and do something on an exception...

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


Re: Call Web Service using proxy and http authentication

2009-05-12 Thread wdveloper
On May 12, 8:38 pm, Steve Howell  wrote:
> On May 12, 8:59 am, wdveloper  wrote:
>
> > Hi everyone,
>
> > I am trying to call a webservice which requires an http
> > authentication.
> > To reach the ws, I must pass from a proxy http. So in the whole I need
> > go through two authentications before getting the ws working. I am
> > using SOAPpy and I'm getting quite crazy.
> > I am able to arrange this problem with simple http calls using urllib2
> > but for the ws i dont see any way out.
>
> > Does anyone knows how I can manage this stuff? Is there any better
> > solution or example code?
>
> Your high level description of the problem is good, but I think you'll
> get more help if you provide a little more detail.
>
> For something like this you may want to try to do more at the HTTP
> level, where you have a little more control over the authentication,
> and then find a way to hook into SOAPpy just to build and parse the
> payloads.
>
> How good is your understanding of HTTP?  Do you know the basics of how
> headers work?  You might want to brush up a little on HTTP just to
> help understand what's going on; it will almost certainly be valuable
> for future projects as well.
>
> To understand how the proxy works in particular, if you can use the
> proxy to access a normal html-serving website, you can use the "Live
> HTTP Headers" tool under Firefox to see what's going on.
>
> But before all that, I would maybe just post a little more detail on
> the problem.  Maybe show code you've written so far, and any error
> messages/tracebacks, to better indicate where you are stuck.

Thank you very much Steve,

I do have a good understanding of http and its headers rules, and of
course I can work on that.
On the other hand, I am new to python and SOAPpy toolkit and I dont
have much of an experience working with ws in general.

When it comes of working with simple call to WS, everything is
successfull; problems start cause I dont know how to use the toolkit
to compose the http request. I should code it in the way that it
connects to my proper proxy and it gets authenticated in the server
exposing the service.

What I have is something like:
from SOAPpy import WSDL

wsdl = 'http://myws?wsdl'
my_http_proxy = '10.x.x.x:8080'
proxy = WSDL.Proxy(wsdl, http_proxy=my_http_proxy)
res = proxy.myService( myparam='...' )

What I get is that connection reaches timeout since the server doesnt
see me coming from the right proxy.
First problem, I can't see where I can put my proxy authentication
username and password.
Second, when I will be able to pass through the right proxy, I need to
authenticate on the server via http through my credential.

I am starting wondering whether python+SOAPpy is the right solution or
I need to switch to other solutions (zsi?).

I hope I've been more detailed now and my situation sounds little more
clear.
Thanks again for your precious help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fill Javascript form

2009-05-12 Thread Aahz
In article <3f9c74cf-72f4-45e2-8724-3939366d1...@e24g2000vbe.googlegroups.com>,
Matteo   wrote:
>
>I have to fill a web form to authenticate and connect to the internet.
>I thought it would have been easy to make a script to do that
>automatically on startup.
>
>Unfortunately, it turned out that the form is written in JavaScript,
>and urllib2 therefore fails to even fetch the form.

Depending on whether you can reverse-engineer the form, you can either
just POST data to the webserver or you need to access a JavaScript
library.  Selenium might be an answer to the latter problem; you could
also look into using WebKit.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for teacher in New York

2009-05-12 Thread dervonb
I live in brooklyn i'm looking for someone who can help a group of two
or three learn how to use python.
to create games useful softwares and very high level coding
eventually.
in other words how to abuse it's talents for our greater good.

Please respond if you can meet in the brooklyn, manhattan, queens
area.
Please respond if you have info about cheap classes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue with twisted and reactor. Can't stop reactor

2009-05-12 Thread Jean-Paul Calderone

On Tue, 12 May 2009 14:30:04 -0500, Nick Craig-Wood  wrote:

Gabriel  wrote:

 Jean-Paul Calderone escribió:
 > None of the reactors in Twisted are restartable.  You can run and
 stop them
> once.  After you've stopped a reactor, you cannot run it again.  This is
> the
> cause of your problem.
>
> Jean-Paul

 I see.
 Is it possible to do what I want using twisted? or
 I should found another way?


You have to go twisted...

Your program should call reactor.run() once and everything you need
your program to do should be started off from twisted callbacks (eg
timer callbacks or deferred objects).

To get your program to do something immediately after it is started,
use reactor.callLater() before calling reactor.run().


reactor.callWhenRunning can also be used (instead of callLater with a very
short delay).

You can also set stuff up first, /then/ call reactor.run().  eg, it is
completely fine to write:

   reactor.connectTCP(...)
   reactor.run()

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


Convert UNIX formated text files to DOS formated?

2009-05-12 Thread walterbyrd
I have about 150 unix formated text files that I would like to convert
to dos formated.

I am guessing that I loop though each file in the directory, read each
line and conver the last character, then save to a file with the same
name in another directory.

I am not really sure what I convert the last charactor to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert UNIX formated text files to DOS formated?

2009-05-12 Thread Diez B. Roggisch

walterbyrd schrieb:

I have about 150 unix formated text files that I would like to convert
to dos formated.

I am guessing that I loop though each file in the directory, read each
line and conver the last character, then save to a file with the same
name in another directory.

I am not really sure what I convert the last charactor to.


Use recode.

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


Re: Convert UNIX formated text files to DOS formated?

2009-05-12 Thread MRAB

walterbyrd wrote:

I have about 150 unix formated text files that I would like to convert
to dos formated.

I am guessing that I loop though each file in the directory, read each
line and conver the last character, then save to a file with the same
name in another directory.

I am not really sure what I convert the last charactor to.


The quickest and OS-agnostic way would be:

text = open(path, "U").read()
text = text.replace("\n", "\r\n")
open(path, "wb").write(text)

That way it doesn't matter if the text file is already dos formatted.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the use of the else in try/except/else?

2009-05-12 Thread Carl Banks
On May 12, 2:35 am, Steven D'Aprano
 wrote:
> On Tue, 12 May 2009 09:20:36 +, Steven D'Aprano wrote:
> > On Tue, 12 May 2009 20:23:25 +1200, Lawrence D'Oliveiro wrote:
>
> >> In message , kj wrote:
>
> >>> I know about the construct:
>
> >>> try:
> >>>     # do something
> >>> except ...:
> >>>     # handle exception
> >>> else:
> >>>     # do something else
>
> >>> ...but I can't come with an example in which the same couldn't be
> >>> accomplished with [no else]
>
> >> I'd agree. If you have to resort to a "try .. else", then might I
> >> respectfully suggest that you're using exceptions in a way that's
> >> complicated enough to get you into trouble.
>
> > try:
> >     rsrc = get(resource)
> > except ResourceError:
> >     log('no more resources available')
> >     raise
> > else:
> >     do_something_with(rsrc)
> > finally:
> >     rsrc.close()
>
> Except of course such a pattern won't work, because if get(resource)
> fails, rsrc will not exist to be closed. So a better, and simpler,
> example would be to drop the finally clause:

Resource acquisition goes outside the try block.  If you want to log
an error, then get() goes inside its own try block.

try:
rsrc = get(resource)
except ResourceError:
log('no more resources available')
raise
try:
do_something_with(rsrc)
finally:
rsrc.close()


If you hadn't reraised the exception, then the else clause would have
been useful as follows:

try:
rsrc = get(resource)
except ResourceError:
proceed_without_resource()
else:
try:
proceed_with_resource()
# Note: proceed_with_resource() can possibly raise
# ResourceError itself
finally:
rsrc.close()

The main reason for the else clause on try blocks is so that you don't
risk catching spurrious exceptions.  You could stick
proceed_with_resource() in the try clause, but then if
proceed_with_resource() throws ResourceError because it tries to
acquire a different resource and fails, then it'd be caught and
proceed_without_resource() would be called, which is a mistake.

In general, you want to limit the contents of a try clause to code
that throws an exception you want to catch (if you're trying to catch
an exception); everything else should go into the else clause.

Incidentally, I can't think of any realistic use cases for using all
four of try...except...else...finally.


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


Re: Convert UNIX formated text files to DOS formated?

2009-05-12 Thread walterbyrd
On May 12, 2:53 pm, MRAB  wrote:
> walterbyrd wrote:
> > I have about 150 unix formated text files that I would like to convert
> > to dos formated.
>
> > I am guessing that I loop though each file in the directory, read each
> > line and conver the last character, then save to a file with the same
> > name in another directory.
>
> > I am not really sure what I convert the last charactor to.
>
> The quickest and OS-agnostic way would be:
>
>      text = open(path, "U").read()
>      text = text.replace("\n", "\r\n")
>      open(path, "wb").write(text)
>
> That way it doesn't matter if the text file is already dos formatted.


Thanks, I am not familiar with the "U" here is how I did it:


import os

for file in os.listdir('.'):
infile = open(file,'r')
outfile = open( 'new_' + file, 'w')
for line in infile:
line = line.rstrip() + '\r\n'
outfile.write(line)
infile.close()
outfile.close()


More code, probably slower, but it worked.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fill Javascript form

2009-05-12 Thread Дамјан Георгиевски


> On 11 Mag, 23:06, Shawn Milochik  wrote:
>> How is the form "written in JavaScript"? Is it dynamically generated?
>>
>> In any case, can you just send a POST request if you know the values
>> required?
> 
> The problem is indeed that the form is dynamically generated.
> That's the .js file:


This seems to be generated by ChiliSpot (the most recent code is from 
http://coova.org/wiki/index.php/CoovaChilli), which also has a 
non-interactive or non-browser-based API/Interface. 

They even have custom application for mobile phones, and a 
Firefox extension for using that API.


> if (navigator.appVersion.indexOf("MSIE")!=-1)
> document.write(" id='chillicontroller'>");
> 
> if (!window.queryObj) {
> window.queryObj = new Object();
> window.location.search.replace(new RegExp("([^?=&]+)(=([^&]
> *))?","g"), function($0,$1,$2,$3) { queryObj[$1] = $3; });
> if (queryObj['uamip'] == null && queryObj['uamport'] == null)
> {queryObj['uamip']='10.192.0.1';queryObj['uamport']='3990';}
> }
> 
> if (queryObj['uamip'] != null && queryObj['uamport'] != null) {
> var script = document.getElementById('chillicontroller');
> if (script == null) {
>   //  document.write('manutenzione');
> script = document.createElement('script');
> script.id = 'chillicontroller';
> script.type = 'text/javascript';
> script.src = 'http://'+queryObj['uamip']+':3990/www/
> chillijs.chi';
> 
> var head = document.getElementsByTagName("head")[0];
> if (head == null) head = document.body;
> head.appendChild(script);
>}
>script=document.getElementById('chillicontroller');
>if(script==null)document.write('manutenzione');
> script.src = 'http://'+queryObj['uamip']+':3990/www/chillijs.chi';
> 
> } else {
> //document.write('manutenzione');
> var noLocation = document.getElementById("noLocation");
> if (noLocation != null && noLocation.style) {
>noLocation.style.display = 'inline';
> }
> }

-- 
дамјан ( http://softver.org.mk/damjan/ )

Well when _I_ was in school, I had to run Netscape on HP/UX, displayed on my 
local X Server running on a Windows 3.1 box. Displayed over a 2400 baud 
modem. Uphill. Both ways. In the rain. With NOBODY to hold my hands. Because 
the life of the geek is a lonely life.
- aclarke on /.

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


Re: How to abort module evaluation?

2009-05-12 Thread Dave Angel

mrstevegross wrote:

I have a python script that is pretty simple: when executed, it
imports a bunch of stuff and then runs some logic. When *imported*, it
defines some variables and exits. Here's what it looks like:

=== foo.py ===
if __name__ != '__main__':
  x = 1
  exit_somehow

import bar
do_some_stuff...
=== EOF ===

There's a problem, though. On line 3, I wrote "exit_somehow".
Actually, I have no idea how to do that part. Is there some way I can
get python to abandon processing the rest of the script at that point?
I know goto doesn't exist, so that's not an option... sys.exit() won't
work, because that will abort the entire python interpreter, rather
than just the evaluation of the module.

Thanks,
--Steve

  

use "else" :

=== foo.py ===
if __name__ != '__main__':
 x = 1
 
else:

 import bar
 do_some_stuff...
=== EOF ===


This is rather unconventional usage, however.  In fact, Mike missed the 
!= in your comparison, perhaps because the other way is so common.  The 
usual idiom is:


import some stuff
define some globals, like  x=1
def some functions, classes etc.

if __name__ == "__main__":
   maybe import some extra stuff
   do_some_stuff

In this case, no else is needed,

Notice also that in your case, the x=1 doesn't take effect when you use 
it as a script, but only when it's being imported.  Usually, this is a 
mistake.


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


Váš příspěvek do konference Python če ká na schválení moderátorem

2009-05-12 Thread python-bounces
Vaše zpráva pro konferenci 'Python' ve věci

RE: SALE 79% 0FF on Pfizer!

Nebyla rozeslána. Pro její distribuci je nutný souhlas moderátora.

Důvod pozdržení distribuce zprávy je:

Příspěvek od nečlena do konference s přispíváním omezeným pouze na
členy.

Vaše zpráva buď bude rozeslána nebo dostanete zprávu o rozhodnutí
moderátora.

Pokud si zprávu nepřejete rozeslat, můžete si stornovat na této
adrese:


http://www.py.cz/mailman/confirm/python/fb63a3e8cb9c55286879670152dbda09df3b83bc

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


Re: Convert UNIX formated text files to DOS formated?

2009-05-12 Thread MRAB

walterbyrd wrote:

On May 12, 2:53 pm, MRAB  wrote:

walterbyrd wrote:

I have about 150 unix formated text files that I would like to convert
to dos formated.
I am guessing that I loop though each file in the directory, read each
line and conver the last character, then save to a file with the same
name in another directory.
I am not really sure what I convert the last charactor to.

The quickest and OS-agnostic way would be:

 text = open(path, "U").read()
 text = text.replace("\n", "\r\n")
 open(path, "wb").write(text)

That way it doesn't matter if the text file is already dos formatted.



Thanks, I am not familiar with the "U" here is how I did it:


import os

for file in os.listdir('.'):
infile = open(file,'r')
outfile = open( 'new_' + file, 'w')
for line in infile:
line = line.rstrip() + '\r\n'
outfile.write(line)
infile.close()
outfile.close()


More code, probably slower, but it worked.


That will also strip any whitespace off the end of the lines.

FYI, if you run it on Windows then the resulting lines will end with
"\r\n\n" because the output file is opened in text mode, which will
write any "\n" as "\r\n".
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating classes with mix-ins

2009-05-12 Thread Carl Banks
On May 12, 4:45 am, samwyse  wrote:
> Unfortunately, 'boilerplate()' uses the handlers that I provide when
> MetaBlog is instantiated.

In that case, the handler functions should be attributes of the
instance, not of the class.  Do something like this:

class MetaBlog(object):
def __init__(self):
self.blog = blogHander()
for name in self.blog.get_methods():
setattr(self,name,self.boilerplate(name))

def boilerplate(self,name):
method = getattr(self.blog,name)
def template(*args):
self.do_verification_here()
method(*args)
return template


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


Re: Nimrod programming language

2009-05-12 Thread Mensanator
On May 12, 12:54 pm, George Sakkis  wrote:
> On May 12, 12:49 pm, Mensanator  wrote:
>
>
>
>
>
> > On May 12, 8:27 am, [email protected] wrote:
>
> > > > > > The language and library are missing arbitrary precision integer
> > > > > > arithmetic, using GMP or something like that.
>
> > > > > True, but currently not a high priority for me.
>
> > > > Too bad. That makes Nimrod officially "worthless", i.e., of no
> > > > value to me.
>
> > > Well, you could write a wrapper for GMP (and contribute to the
> > > project ;-)).
>
> > But such a thing already exists in Python. And I spend my time
> > USING arbitrary precision numbers to do math research.
>
> > Just thought you'ld like to be aware that some people actually
> > make their language choices based on the availability (and
> > performance)
> > of arbitrary precision numbers.
>
> I'm sure developers of a new language have to deal with much more
> pressing issues before accommodating each and every self important
> niche.

If he gets enough feedback, won't he learn which niches are important
enought to accommodate? Such feedback was solicited, was it not? If
he
has more pressing issues to deal with, why is he trolling here?

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


Re: Fwd: Re: Unable to install Pywin32 for Python 2.6.2

2009-05-12 Thread David Lees

Mark Hammond wrote:
Probably some import statement is finding a .pyd module built against 
Python 2.5 instead of Python 2.6; it might be that PYTHONPATH points 
somewhere wrong, or the registry for Python 2.6 is setup wrong, or 
something else entirely...


Cheers,

Mark

On 12/05/2009 3:13 PM, David Lyon wrote:

Hi,

hmmm... that's annoying..

Whilst I don't have an exact answer I have a few hunches...

Perphaps what has happened is that the windows installer between
the versions of pywin32 has installed newer versions of the same
dlls over the top of older ones.

Or, possibly, the installer hasn't wanted to replace older dll's
because they already exist on the system.

This would result in a mismatch.

You may be lucky and find an install log. This might tell you which
files were actually installed. And you could play around with
moving them around.

Good luck with your night vision task

David


On Tue, 12 May 2009 02:22:56 GMT, David Lees
wrote:

I have no problem installing Python 2.6.2 for windows under XP SP3 and
IDLE and the command line versions work fine.  When I run the pywin32
installer downloaded from sourceforge (pywin32-212.win32-py2.6.exe) I
get the following error message:

Traceback (most recent call last):
File "", line 565, in
File "", line 291, in install
ImportError: Module use of python25.dll conflicts with this version of
Python.
*** run_installscript: internal error 0x ***

I have tried uninstalling Python 2.6 and reinstalling, but still get the
same message.  I do have Python 2.5.4 and its associated Pywin32 on the
same machine, but I have a laptop with pywin32 installed for both python
2.5 and 2.6.

TIA

David Lees



Mark and David,

Thanks for the help.  I just got it to install for Python 2.6.  All I 
did was change PYTHONPATH (as suggested by Mark) from 
C:\Python25\Lib\site-packages to C:\Python26\Lib\site-packages


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


  1   2   >