Re: Help me understand this

2007-01-29 Thread Steven D'Aprano
On Mon, 29 Jan 2007 23:05:37 -0800, ArdPy wrote:

> Hi,
> 
> Pls tell me whats going on in the code snippet below:
> 
 n = 10
 statstr = "N = ",n
 type(statstr) #case1
> 
 print statstr
> ('N = ', 10)
 print "N = ",n   #case 2
> N =  10
> 
> In the first case the result is printed as a tuple and in the second 
> it appears as an ordinary string.


The print statement takes one or more comma-delimited objects, and prints
each one separated with a space, and then finally prints a newline. If you
end the list with a comma, no newline is printed. So when you execute the
line:

print "N = ", n

Python prints "N = ", then a space, then 10, then a newline.


Outside of a print statement (and also an "except" statement), commas
create tuples. So when you execute the line:

statstr = "N = ", n

the right-hand side is a tuple with two items. The first item is the
string "N = " and the second item is the integer currently named n (in
your case, 10).

Do not be fooled that brackets make tuples -- they don't. With the
exception of the empty tuple () which is a special case, it is commas that
make tuples. So these two lines have identical effects:

t = 1, 2, 3
t = (1, 2, 3)

That is why these two statements print something different:

print 1,2,3
print (1,2,3)

In the second case, the brackets force the expression "1,2,3" to be
evaluated before the print statement sees it, so the print statement sees
a single argument which is a tuple, instead of three int arguments.

(But notice that the brackets still aren't creating the tuple, the commas
are. The brackets just change the order of evaluation.)



-- 
Steven D'Aprano 

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


Re: Data structure and algorithms

2007-01-29 Thread Beej
On Jan 29, 10:15 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> The instructor learned his lesson: no more assignments
> done in "any language I  can understand"

Without naming names, there was a person at my university who gained a 
certain amount of notoriety by implementing a file system for OS class 
in Bourne Shell.

That prof also changed the rule the very next semester. :-)

-Beej

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


Re: Data structure and algorithms

2007-01-29 Thread Beej
On Jan 29, 1:50 pm, "azrael" <[EMAIL PROTECTED]> wrote:
> thanks guys. i see that there is no way then to go back to C to
> satisfy my prof and get a grade

Seconding what Dennis says below, it is totally possible to use Python 
for this.

I didn't mean to discourage you from using Python--I just wanted to 
discourage you from trying to do it using the Python built-in list [].

In fact, given the time constraints and your dislike of structs, 
you're likely going to rip your hair out trying to get it going in C.

-Beej

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


Help me understand this

2007-01-29 Thread ArdPy
Hi,

Pls tell me whats going on in the code snippet below:

>>> n = 10
>>> statstr = "N = ",n
>>> type(statstr) #case1

>>> print statstr
('N = ', 10)
>>> print "N = ",n   #case 2
N =  10

In the first case the result is printed as a tuple and in the second 
it appears as an ordinary string.

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


Re: parent-child object design question

2007-01-29 Thread Ben Finney
"manstey" <[EMAIL PROTECTED]> writes:

> I have two classes. The first one wraps around an old-style class
> called oref
>
> Class CacheClass(object):
> def __init__(self, obj):
> self.__data = obj
> def __getattr__(self, attr):
> return getattr(self.__data, attr)

I presume the 'obj' argument to this class's __init__ method contains
the 'oref' instance.

It's a little confusing to call the argument to __getattr__ "attr",
since it's actually the *name* of the attribute to be accessed, not
the attribute itself.

> The second class is much the same, also wrapping, but has some
> attributes.
>
> class CacheProperty(object):
> def __init__(self, obj, dicProperties={}):

Setting a container class as a default argument is prone to error; the
default argument gets created once, when the 'def' statement is
executed. Better to default to None, and trigger on that inside the
function.

> self.__data = obj
> lisProperties=[]
> for key, val in dicProperties.iteritems():
> setattr(self, key, val)
> lisProperties.append(key)
> self.Properties = lisProperties

The name of this class doesn't really tell me what an instance of the
class *is*. Is it a "cache property", as the name seems to indicate?
If so, why does a "cache property" instance itself contain a list of
properties?

> def __getattr__(self, attr):
> return getattr(self.__data, attr)
>
> Here is my code:
>
> >>> MyClass = CacheClass(oref)

This is a confusing example; MyClass implies that the object is a
class, but this is now an instance of CacheClass, not a class.

Also, it's conventional in Python to name classes in TitleCase, but to
name instances (and functions) starting with lowercase.

> >>> MyProperty = CacheProperty(oref2,{'Name':'Surname', 'Value':'Peter'})
> >>> setattr(MyClass,MyProperty.Name,MyProperty)

This might be a good approach if you didn't know you were going to
associate the object MyClass with the object MyProperty at the
creation of MyProperty. However:

> Now, the problem is that I want a method MyClass.MyProperty.Save()
> to save the value of MyClass.MyProperty to the database backend on
> disk, but the code for this is part of the wrapped oref code, and
> thus is invoked only by
> MyClass.set(MyProperty.Name,MyProperty.Value).

This implies that there's a definite "each CacheProperty instance is
associated with exactly one CacheClass instance" invariant.

If that's true, the best thing to do is to pass MyClass to the
constructor for the CacheProperty class, and have each instance set
the relationship in the __init__ method.

I don't know what a descriptive term for the relationship between the
CacheClass instance and the CacheProperty instance is, so I'm going to
use "parent"; you should choose something more descriptive.

class CacheProperty(object):
def __init__(self, obj, parent, properties=None):
self.__data = obj
self._bind_to_parent(parent)
if properties is None:
properties = {}
self._accumulate_properties(properties)

def _bind_to_parent(self, parent):
setattr(parent, self.Name, self)

def _accumulate_properties(self, properties):
self.properties = []
for key, val in properties.iteritems():
setattr(self, key, val)
self.properties.append(key)

def __getattr__(self, name):
return getattr(self.__data, name)

-- 
 \ "Marriage is a wonderful institution, but who would want to |
  `\ live in an institution."  -- Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: List Behavior when inserting new items

2007-01-29 Thread André Malo
* Paul McGuire wrote:

>> py>def __init__(self, arg = []):
>> py>self.__list = arg
> 
> Please don't perpetuate this bad habit!!!  "arg=[]" is evaluated at
> compile time, not runtime, and will give all default-inited llists the
> same underlying list.

While this actually might be bad habit, the default arguments are *not*
eval'd at compile time. This seems to be a common mistake. They are
evaluated at runtime as everything else. The difference to other local
variables is, that the objects they're referring to are just initalized
once instead of each time they're taken into account.

nd
-- 
die (eval q-qq[Just Another Perl Hacker
]
;-)
# André Malo,  #
-- 
http://mail.python.org/mailman/listinfo/python-list

emulate a serial port in windows (create a virtual 'com' port)

2007-01-29 Thread Pom
Hello


how can I emulate a serial port in windows?  I want to intercept data 
sent to a 'com'port by a proprietary program.  It sends statistics to a 
serial display, and I want that data in my python program (that display 
isn't needed).

Is this possible?

I've seen this kind of serial ports being created when using USB and 
bleutooth adapters, so i guess it's possible ???


Thanks in advance


Greets


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


parent-child object design question

2007-01-29 Thread manstey
Hi,

I am having trouble designing my classes.

I have two classes. The first one wraps around an old-style class 
called oref


Class CacheClass(object):
def __init__(self, obj):
self.__data = obj
def __getattr__(self, attr):
return getattr(self.__data, attr)

The second class is much the same, also wrapping, but has some 
attributes.

class CacheProperty(object):
def __init__(self, obj, dicProperties={}):
self.__data = obj
lisProperties=[]
for key, val in dicProperties.iteritems():
setattr(self, key, val)
lisProperties.append(key)
self.Properties = lisProperties
def __getattr__(self, attr):
return getattr(self.__data, attr)

Here is my code:

>>> MyClass = CacheClass(oref)
>>> MyProperty = CacheProperty(oref2,{'Name':'Surname', 'Value':'Peter'})
>>> setattr(MyClass,MyProperty.Name,MyProperty)

Now, the problem is that I want a method MyClass.MyProperty.Save() to 
save the value of MyClass.MyProperty to the database backend on disk, 
but the code for this is part of the wrapped oref code, and thus is 
invoked only by MyClass.set(MyProperty.Name,MyProperty.Value).

How can I access this method inside the MyProperty class?

I hope this is clear!

regard,s
matthew

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


Re: Ip address

2007-01-29 Thread Steve Holden
Toby A Inkster wrote:
> Steve Holden wrote:
> 
>> There is absolutely no need to know the IP address of "your router" to 
>> communicate with Internet devices. Either your IP layer is configured to 
>> know the addresses of one or more routers, or it has discovered those 
>> address by dynamic means, or you can't get off-net because there aren't 
>> any routers.
> 
> ... or you can't get off-net because you don't *know* the routers.
> 
What I know or don't know makes absolutely no difference to whether my 
computer can reach the Internet, it's a matter of whether the IP layes 
is configured to know the appropriate address to which it can hand off 
non-local traffic.

If you are trying to say that it's necessary to know the IP address of 
the routers in order to select a specific interface address from the 
available choices as "the Internet interface" then kindly say so and 
stop wallowing in semantic obscurity.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: pdf to text

2007-01-29 Thread Steve Holden
tubby wrote:
> Dieter Deyke wrote:
>>> sout = os.popen('pdftotext "%s" - ' %f)
> 
>> Your program above should read:
>>
>>sout = os.popen('pdftotext "%s" - ' % (f,))
> 
> What is the significance of doing it this way?

It's actually just nit-picking - as long as you know f is never going to 
  be a tuple then it's perfectly acceptable to use a single value as the 
right-hand operand.

Of course, if f ever *is* a tuple (with more than one element) then you 
will get an error:

  >>> for f in ['string',
('one-element tuple', ),
("two-element", "tuple")]:
  ...   print 'Nit: pdftotext "%s" - ' % (f,)
  ...   print 'You: pdftotext "%s" - ' %f
  ...
Nit: pdftotext "string" -
You: pdftotext "string" -
Nit: pdftotext "('one-element tuple',)" -
You: pdftotext "one-element tuple" -
Nit: pdftotext "('two-element', 'tuple')" -
Traceback (most recent call last):
   File "", line 3, in 
TypeError: not all arguments converted during string formatting
  >>>

So there is potentially some value to it. But we often don't bother.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: creating a dictionary

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 23:45:40 -0300, mark <[EMAIL PROTECTED]> escribió:

> i have few variables and i want to create a dictionary with these  
> variables
> such that the keys are the variable names and the corresponding values
> are the variable values.how do i do this easily?
> for ex:
> var1='mark'
> var2=['1','2','3']
> my_dict = create_my_dictionary(var1, var2)
>
> and my_dict is {'var1':'mark', 'var2':['1','2','3']}
>
> is there a function for create_my_dictionary?

var1='mark'
var2=['1','2','3']
my_dict = dict(var1=var1, var2=var2)

In addition, if you are inside a function, and these are the only  
variables, using locals() may be useful too:

def f():
   a = 1
   b = 2
   c = locals()
   print c
   d = 3

prints {'a': 1, 'b': 2}

-- 
Gabriel Genellina

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


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 01:58:39 -0300, NoName <[EMAIL PROTECTED]> escribió:

> Perl:
> @char=("A".."Z","a".."z",0..9);
> do{print join("",@char[map{rand @char}(1..8)])}while(<>);
>
> !!generate passwords untill U press ctrl-z
>
>
>
> Python (from CookBook):
>
> from random import choice
> import string
> print ''.join([choice(string.letters+string.digits) for i in
> range(1,8)])
>
> !!generate password once :(
>
> who can write this smaller or without 'import'?
>

Isn't it small enough? What's the point on being shorter?
I think you could avoid importing string (building the set of characters  
like the Perl code) but anyway you will end importing random, or os.urandom
Do you want more than one password? Wrap the print inside a while True:  
statement.
-- 
Gabriel Genellina

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


Re: log parser design question

2007-01-29 Thread avidfan
On 28 Jan 2007 21:20:47 -0800, "Paul McGuire" <[EMAIL PROTECTED]>
wrote:

>On Jan 27, 10:43 pm, avidfan <[EMAIL PROTECTED]> wrote:
>> I need to parse a log file using python and I need some advice/wisdom
>> on the best way to go about it:
>>
>> The log file entries will consist of something like this:
>>
>> ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled
>> locked working.lock
>> status running
>> status complete
>>
>> ID=9009 IID=87234785 execute wait - 01.21.2007 status wait
>> waiting to lock
>> status wait
>> waiting on ID=8688
>>
>> and so on...
>>
>For the parsing of this data, here is a pyparsing approach.  Once 
>parse, the pyparsing ParseResults data structures can be massaged into 
>a queryable list.  See the examples at the end for accessing the 
>individual parsed fields.
>
>-- Paul
>
>data = """
>ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled
>locked working.lock
>status running
>status complete
>
>
>ID=9009 IID=87234785 execute wait - 01.21.2007 status wait
>waiting to lock
>status wait
>waiting on ID=8688
>
>"""
>from pyparsing import *
>
>integer=Word(nums)
>idref = "ID=" + integer.setResultsName("id")
>iidref = "IID=" + integer.setResultsName("iid")
>date = Regex(r"\d\d\.\d\d\.\d{4}")
>
>logLabel = Group("execute" + oneOf("begin wait"))
>logStatus = Group("status" + oneOf("enabled wait"))
>lockQual = Group("locked" + Word(alphanums+"."))
>waitingOnQual = Group("waiting on" + idref)
>statusQual = Group("status" + oneOf("running complete wait"))
>waitingToLockQual = Group(Literal("waiting to lock"))
>statusQualifier = statusQual | waitingOnQual | waitingToLockQual | 
>lockQual
>logEntry = idref + iidref + logLabel.setResultsName("logtype") + "-" \
>+ date + logStatus.setResultsName("status") \
>+ ZeroOrMore(statusQualifier).setResultsName("quals")
>
>for tokens in logEntry.searchString(data):
>print tokens
>print tokens.dump()
>print tokens.id
>print tokens.iid
>print tokens.status
>print tokens.quals
>print
>
>prints:
>
>['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', 
>'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], 
>['status', 'running'], ['status', 'complete']]
>['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', 
>'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], 
>['status', 'running'], ['status', 'complete']]
>- id: 8688
>- iid: 98889998
>- logtype: ['execute', 'begin']
>- quals: [['locked', 'working.lock'], ['status', 'running'], 
>['status', 'complete']]
>- status: ['status', 'enabled']
>8688
>98889998
>['status', 'enabled']
>[['locked', 'working.lock'], ['status', 'running'], ['status', 
>'complete']]
>
>['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', 
>'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', 
>'wait'], ['waiting on', 'ID=', '8688']]
>['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', 
>'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', 
>'wait'], ['waiting on', 'ID=', '8688']]
>- id: 9009
>- iid: 87234785
>- logtype: ['execute', 'wait']
>- quals: [['waiting to lock'], ['status', 'wait'], ['waiting on', 
>'ID=', '8688']]
>- status: ['status', 'wait']
>9009
>87234785
>['status', 'wait']
>[['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', 
>'8688']]

Paul,

Thanks!  That's a great module.  I've been going through the docs and
it seems to do exactly what I need...

I appreciate your help!

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


Re: The reliability of python threads

2007-01-29 Thread Steve Holden
Carl J. Van Arsdall wrote:
> Aahz wrote:
>> [snip]
>>
>> My response is that you're asking the wrong questions here.  Our database
>> server locked up hard Sunday morning, and we still have no idea why (the
>> machine itself, not just the database app).  I think it's more important
>> to focus on whether you have done all that is reasonable to make your
>> application reliable -- and then put your efforts into making your app
>> recoverable.
>>   
> Well, I assume that I have done all I can to make it reliable.  This 
> list is usually my last resort, or a place where I come hoping to find 
> ideas that aren't coming to me naturally.  The only other thing I 
> thought to come up with was that there might be network errors.  But 
> i've gone back and forth on that, because TCP should handle that for me 
> and I shouldn't have to deal with it directly in pyro, although I've 
> added (and continue to add) checks in places that appear appropriate 
> (and in some cases, checks because I prefer to be paranoid about errors).
> 
> 
>> I'm particularly making this comment in the context of your later point
>> about the bug showing up only every three or four months.
>>
>> Side note: without knowing what error messages you're getting, there's
>> not much anybody can say about your programs or the reliability of
>> threads for your application.
>>   
> Right, I wasn't coming here to get someone to debug my app, I'm just 
> looking for ideas.  I constantly am trying to find new ways to improve 
> my software and new ways to reduce bugs, and when i get really stuck, 
> new ways to track bugs down.  The exception won't mean much, but I can 
> say that the error appears to me as bad data.  I do checks prior to 
> performing actions on any data, if the data doesn't look like what it 
> should look like, then the system flags an exception.
> 
> The problem I'm having is determining how the data went bad.  In 
> tracking down the problem a couple guys mentioned that problems like 
> that usually are a race condition.  From here I examined my code, 
> checked out all the locking stuff, made sure it was good, and wasn't 
> able to find anything.  Being that there's one lock and the critical 
> sections are well defined, I'm having difficulty.  One idea I have to 
> try and get a better understanding might be to check data before its 
> stored.  Again, I still don't know how it would get messed up nor can I 
> reproduce the error on my own. 
> 
> Do any of you think that would be a good practice for trying to track 
> this down? (Check the data after reading it, check the data before 
> saving it)
> 
Are you using memory with built-in error detection and correction?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: deepcopy alternative?

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 20:17:11 -0300, <"none <"@bag.python.org> escribió:

> I have a very complex data structure which is basically a class object
> containing (sometimes many) other class objects,

What are "class objects"? instances of a given class, or a class itself?

> function references,
> ints, floats, etc.  The man for the copy module states pretty clearly
> that it will not copy methods or functions. I've looked around for a
> while (prob just using the wrong keywords) and haven't found a good
> solution.  As a workaround I've been using cPickle, loads(dumps(obj))
> which is incredibly slow (~8 sec for a 1000 elem list).
>
> I believe the only thing stopping me from doing a deepcopy is the
> function references, but I'm not sure.  If so is there any way to
> transform a string into a function reference(w/o eval or exec)?

What do you mean by "function reference"? A module-level function works  
fine both with pickle and copy. Methods do not; but it's not common to  
take methods out of a class and put them inside a tuple, by example...

>
> Example
> from copy import deepcopy
> a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj[funcRef])
> b = deepcopy(a)
> TypeError: function() takes at least 2 arguments (0 given)

Please provide a *running* example. I've added some definitions, corrected  
some syntax errors, and this full example works for me:

--- cut ---
 from copy import deepcopy

class ClassObj(object):
   def __init__(self, args):
 self.data = args

def funcRef(x):
 print x

a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj([funcRef])])
b = deepcopy(a)
print a is b
a.data.append('hello')
print len(a.data), len(b.data)
--- cut ---

> PS: If the answer to this is in __getstate__() or __setstate__() is
> there some reference to how these should be implemented besides the
> library reference?

Until you provide more info on your problem it's hard to tell.


-- 
Gabriel Genellina

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


Re: Off-Topic Posts

2007-01-29 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Jan 27, 1:31 pm, Jim Klein <[EMAIL PROTECTED]> wrote:
>> I'm not one of the conquered races, I'm Swiss. We are the bankers to
>> the conquerers. :-)
> 
> Exactly, Honorable J Klein, (although my reference was a general one, 
> you have entered the thread, so I will pick the swiss case) more like 
> tributaries to the conquerers ... I

I suppose I'd be a fascist if I suggested that you are posting this crap 
inappropriately and you should piss off to where you were appreciated 
(if any such cyber-place exists)? sigh ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: Convert raw data to XML

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 23:42:07 -0300, <[EMAIL PROTECTED]> escribió:

> For example the raw data is as follows
>
> SomeText  Description>PassorFail
>
> without spaces or new lines. I need this to be written into an XML
> file as
> [same content but nicely indented]

Is the file supposed to be processed by humans? If not, just write it as  
you receive it.
Spaces and newlines and indentation are mostly irrelevant on an xml file.

-- 
Gabriel Genellina

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


Re: interactive prompt in IDLE

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 10:16:32 -0300, Jan Kanis  
<[EMAIL PROTECTED]> escribió:

> Hello everyone,
>
> I'm trying to change the interactive python prompt. According to the docs
> this is done by changing sys.ps1 and sys.ps2 . That works fine when
> running python interactively from a command line, but when running in  
> IDLE
> the .ps1 and .ps2 don't seem to exist.
>
> I suppose this has something to do with Idle and the python shell in it
> both running in different processes, with the prompts generated by the
> Idle process?
>
> Does anyone know if and how to change the prompts in IDLE's interactive
> python?

I'm using Python 2.5 on Windows XP.
I change ps1 and ps2 in sitecustomize.py, and both pythonwin and  
python.exe work fine.
I don't usually open IDLE, but ps1 was changed, altough it does not appear  
to use ps2 (it was replaced by "   ")

-- 
Gabriel Genellina

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


Re: sending a class as an argument

2007-01-29 Thread Gabriel Genellina
En Mon, 29 Jan 2007 01:24:23 -0300, manstey <[EMAIL PROTECTED]> escribió:

>
> Our class has its attributes set as classes, as in
>
> MyClass.Phone.Value='34562346'
> MyClass.Phone.Private=True
>
> Inside the MyClass definition we have a function like this:
>
> def MyFunc(self,clsProperty):
>if clsProperty.Private:
> print 'Private property'
>else:
> print ClsProperty.Value

This method does not use `self` at all, and that's rather suspicious for  
an instance method.
And you set properties on the class itself? So you never create instances  
of that class?

> In our code, we then call
 MyClass.MyFunc(MyClass.Phone)
>
> We want to be able in our code instead simply to call:
 MyClass.MyFunc(Phone) or MyClass.MyFunc('Phone')
>
> But we can't get it to work. If we rewrite the function as follows:
>
> def MyFunc(self,attr):
>if self.attr.Private:
>   print 'Private'
>else:
>   print self.attr.Value
>
> we get an error.

Surely an AttributeError, because you dont have any attribute named "attr".
Notice that on this version you are using `self`, but on the above version  
you didnt use it.
There are easy ways in Python to access an attribute by name, but I think  
that this would just add more noise to your code. Please tell us about  
your design, or rethink it. Do actually exist instances of MyClass, or  
not? I can imagine "Phone" being an attribute of a certain instance of  
Person, by example, but not a class attribute.

> Is there a better way to do this? Thanks
Surely, but we need to know your goal, what do you really want to do, not  
how do you think you should do that.

-- 
Gabriel Genellina

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


Re: Getting the output from a console command while it's been generated!

2007-01-29 Thread Gabriel Genellina
En Sun, 28 Jan 2007 23:54:03 -0300, Raúl Gómez C. <[EMAIL PROTECTED]>  
escribió:

> I can't use the subprocess module because my app needs to be compatible  
> with
> Python 2.3 so, is there another approach to this problem???

Any variant of popen; see the popen2 module (but read the last notes on  
flow control issues).

-- 
Gabriel Genellina

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


Python 2.5 Tkinter not configured

2007-01-29 Thread Jim
I compiled Python 2.5 from python.org and I get an error message when I try
to import the Tkinter module. Python reports that there is no such module.
It says my Python isn't configured for Tkinter. How do I configure it? I'm
using GCC 4.1.1 to compile the tarball. Thanks for any help with this.

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


Secret Technology of THERMATE and 911 Crime

2007-01-29 Thread thermate
Excellent Technology, and photos:

http://stj911.org/jones/focus_on_goal.html

As scientists, we look at the evidence, perform experiments, and apply 
the Scientific Method. The Greek method was to look at the evidence 
(superficially) and then try to explain things through logic and 
debate. The Greeks came up with various ideas in this way -- such as 
the geocentric theory in which the Earth was at the center of the 
universe, and all the stars and planets revolved around the earth. 
There were problems with this geocentric explanation, but Plato 
insisted that they must "save the hypothesis," and plausible 
explanations were found to account for anomalies -- i such as the 
retrograde motion of Mars. The philosophical debates and discussions 
were seemingly endless; the Dark Ages ensued.

Along came Copernicus, Galileo, Newton and others with their 
experiments and observations, and the centuries-old Greek philosophy-
based notions began to crumble. Galileo observed through a telescope 
that Jupiter had moons -- which revolved around Jupiter (not the 
Earth). He was threatened with torture if he did not recant his 
explanation (that the Earth was not at the center). He suffered house 
arrest but not torture as he quietly continued his experiments.

In the lifetime of Newton, another experimenter who challenged the 
Greek approach, the scientific community worked out a system whereby 
scientific studies would be published after review by peers -- 
qualified experts who could judge the quality of the research. Peer-
reviewed technical journals arose and the peer-review process brought 
order to the relative chaos of work up to that time. Now experiments 
could be done and written up, then peer-reviewed and published. Peer-
reviewed papers would draw the attention of others. To give an example 
of using the modern scientific method, a few colleagues and I are 
doing experiments and making observations in a scientific approach to 
what really happened at the World Trade Center. It is NOT merely a 
plausible explanation or debates about "possibilities" that we seek. 
Rather, having seen strong indications of foul play (see 
journalof911studies.com/Intersecting_facts_and_Theories_on_911.pdf ) 
we are looking for hard evidence that would clearly verify an 
intentional crime beyond that of 19 hijackers. Ours is a forensic 
investigation, looking for a "smoking gun," which would then lead to a 
serious criminal investigation.

I do not plan to make a career out of 9/11 research, and I am not 
making money from my investigations anyway. We need a formal, solid 
investigation of the 9/11 crimes committed, not a long-term study 
which endlessly debates all alternatives. I seek such solid evidence 
of an insider crime (beyond a reasonable doubt) that some of us will 
successfully demand a criminal investigation to confront key 
individuals who may have insider information -- within one year, if 
possible-- not many.

So what evidence is likely to lead to such a criminal investigation?

As identified in my talk at the University of California at Berkeley, 
there are four areas of 9/11 research that are so compelling that they 
may quickly lead to the goal of a solid investigation of 9/11 as an un-
solved crime scene. These four areas are:

   1. Fall time for WTC 7.
   2. Fall times for the Towers.
   3. Challenging the NIST report and Fact Sheet.
   4. Evidence for use of Thermate reactions: What the WTC dust and 
solidified metal reveal.

* Please note that I do not focus only on the thermate-hypothesis, 
and I do research in all four areas above. Details are given in my 
talk, available here: www.911blogger.com/node/4622 Also: 
video.google.com/videoplay?docid=9210704017463126290 )

There are other lines that may compel a criminal investigation even 
before one of the above "hard science" research lines bears fruit:

   5. Whistleblower statements -- including some individuals yet to 
emerge.
   6. Who made the stock-market "put-option" trades on American and 
United Air Lines in the week before 9/11, indicating clear 
foreknowledge of the attacks coupled with greed?
   7. The fact that the WTC dust was declared quite safe by the EPA/
National Security Council when it fact scientists had proven it to be 
toxic, and the many people now clamoring for justice after being hurt 
and misled.
   8. Calls for impeachment for war issues, e.g., from a state 
legislature or Congress, which scrutinizes the "Bush Doctrine," then 
opens the 9/11 question.
   9. Pressure from 9/11 Family members, firemen and others for 
answers.
  10. Direct appeals to Senators and Congresspersons -- who are 
charged with an oversight role. I initiated a Petition to this effect, 
demanding release of government-held information related to 9/11, 
which has since been signed by over 10,000 people. And I am in contact 
now with the Congressman from my state, seeking information and 
remedy.

We have found evidence for thermates in the molten met

Re: Convert raw data to XML

2007-01-29 Thread Justin Ezequiel
On Jan 30, 10:42 am, [EMAIL PROTECTED] wrote:
> For example the raw data is as follows
>
> SomeText  Description>PassorFail
>
> without spaces or new lines. I need this to be written into an XML
> file as
>
> 
> 
>
>   
>   
>  SomeText
>   
>   
>  PassorFail
>   
>   
> 
>

raw = r'SomeText PassorFail'
import xml.dom.ext
import xml.dom.minidom
doc = xml.dom.minidom.parseString(raw)
xml.dom.ext.PrettyPrint(doc)


  

SomeText 
PassorFail
  



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


Re: error messages containing unicode

2007-01-29 Thread Steven D'Aprano
On Mon, 29 Jan 2007 18:01:56 -0800, Jim wrote:

> Hello,
> 
> I'm trying to write exception-handling code that is OK in the 
> presence
> of unicode error messages.  I seem to have gotten all mixed up and 
> I'd
> appreciate any un-mixing that anyone can give me.

[snip]

>>> class MyException(Exception): pass
...
>>> fn = u'a\N{LATIN SMALL LETTER O WITH DIAERESIS}k'
>>> raise MyException("hello")
Traceback (most recent call last):
  File "", line 1, in ?
__main__.MyException: hello
>>> 

Works fine with an ASCII argument, but not with Unicode:

>>> raise MyException(fn)
Traceback (most recent call last):
  File "", line 1, in ?
__main__.MyException>>>

Notice the terminal problem? (The error message doesn't print, and the
prompt ends up stuck after the exception.)

Let's capture the exception and dissect it:

>>> try: raise MyException(fn)
... except Exception, err:
... print type(err)
... print err
...

Traceback (most recent call last):
  File "", line 4, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in
position 1: ordinal not in range(128)

Now we have the answer: your exception (which just sub-classes Exception)
does the simplest conversion of Unicode to ASCII possible, and when it
hits a character it can't deal with, it barfs. That doesn't happen
until you try to print the exception, not when you create it. 

The easiest ways to fix that are:

(1) subclass an exception that already knows about Unicode; 

(2) convert the file name to ASCII before you store it; or 

(3) add a __str__ method to your exception that is Unicode aware.

I'm going to be lazy and do a real simple-minded version of (2):

>>> class MyBetterException(Exception):
... def __init__(self, arg):
... self.args = arg.encode('ascii', 'replace')
... self.unicode_arg = arg  # save the original in case



>>> raise MyBetterException(fn)
Traceback (most recent call last):
  File "", line 1, in ?
__main__.MyBetterException: a?k


And now it works.



-- 
Steven D'Aprano 

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


creating a dictionary

2007-01-29 Thread mark

i have few variables and i want to create a dictionary with these variables
such that the keys are the variable names and the corresponding values
are the variable values.how do i do this easily?
for ex:
var1='mark'
var2=['1','2','3']
my_dict = create_my_dictionary(var1, var2)

and my_dict is {'var1':'mark', 'var2':['1','2','3']}

is there a function for create_my_dictionary?
-- 
http://mail.python.org/mailman/listinfo/python-list

Convert raw data to XML

2007-01-29 Thread elrondrules
Hi

I am running a HTTP server which receives post from a process.
In my do_POST method am receiving raw data.

I know that this raw data has a valid XML content and I need to 
convert this into an XML file.

Are there any routines to do this.. if not how to write one..

For example the raw data is as follows

SomeText PassorFail

without spaces or new lines. I need this to be written into an XML 
file as



   
  
  
 SomeText
  
  
 PassorFail
  
  


The tags in the raw data are not the same alaways.. Hence I need a 
generic routine that does the trick

Any pointers for this issue would help

Thanks

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


Re: Excellent Interview with Dennis D'Souza, full of laughs

2007-01-29 Thread Hampton Din


still a stupid troll. 


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


error messages containing unicode

2007-01-29 Thread Jim
Hello,

I'm trying to write exception-handling code that is OK in the 
presence
of unicode error messages.  I seem to have gotten all mixed up and 
I'd
appreciate any un-mixing that anyone can give me.

I'm used to writing code like this.

  class myException(Exception):
  pass

  fn='README'
  try:
  f=open(fn,'r')
  except Exception, err:
  mesg='unable to open file'+fn+': '+str(err)
  raise myException, mesg

But what if fn is non-ascii?  The following code raises the
dreaded (to me) UnicodeEncodeError.

  class myException(Exception):
  pass

  def fcnCall():
  fn=u'a\N{LATIN SMALL LETTER O WITH DIAERESIS}k'
  try:
  # was: f=open(fn,'r')
  2/0  #  just substitute something that will raise an 
exception
  except Exception, err:
  mesg='unable to open file '+fn+': '+str(err)
  raise myException, mesg

  try:
  fcnCall()
  except Exception, err:
  print 'trouble calling fcnCall: '+str(err)

Maybe my trouble is the "str()", which is supposed to return a 
regular
string?  (BTW, unicode() makes no difference, and help(BaseException)
didn't give me any inspirations.)  So I looked for an end-around past 
the
str() call.

As I understand lib/module-exceptions.html, "For class
exceptions, [err] receives the exception instance. If the exception
class is derived from the standard root class BaseException, the
associated value is present as the exception instance's args
attribute.", I should be able to get the string out of err.args. Sure
enough, putting the above text into test.py and changing str(err)
to repr(err.args) yields this.

  $ python test.py
  trouble calling fcnCall: (u'unable to open file a\xf6k: integer 
division or modulo by zero',)

so that changing the above repr(err.args) to err.args[0] gives the
desired result.

  $ python test.py
  trouble calling fcnCall: unable to open file aök: integer division 
or modulo by zero

(In case this doesn't show up as I intended on your screen, I see an
o with a diaeresis in the filename.)

But the documentation "This may be a string or a tuple containing 
several
items of information (e.g., an error code and a string explaining the
code)." gives me no reason to believe that all exceptions have the 
desired
unicode string as the 0-th element of the tuple.  I confess that I'm 
unable
to confidently read exceptions.c .

No doubt I've missed something (I googled around the net and on this 
group
but I didn't have any luck).  I'd be grateful if someone could show 
me
striaght.

Thanks,
Jim

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


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Steven D'Aprano
On Mon, 29 Jan 2007 08:38:13 -0800, Szabolcs Nagy wrote:

>>> why use xrange? range is faster and simpler for small ranges

That is not true.

>>> import timeit
>>> timeit.Timer("range(50)", "").repeat()
[2.8599629402160645, 2.8296849727630615, 2.8609859943389893]
>>> timeit.Timer("xrange(50)", "").repeat()
[1.1806831359863281, 1.3563210964202881, 1.1632850170135498]

>>> timeit.Timer("range(5)", "").repeat()
[1.7963159084320068, 1.5487189292907715, 1.5596699714660645]
>>> timeit.Timer("xrange(5)", "").repeat()
[1.158560037612915, 1.1807279586791992, 1.1769890785217285]

There is very little reason to use range() unless you actually need the
entire list in one go. In fact, in Python 3.0, the existing range() will
be removed and xrange() will be renamed range().




-- 
Steven D'Aprano 

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


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Steven D'Aprano
On Mon, 29 Jan 2007 16:24:18 +0100, Laszlo Nagy wrote:

> NoName írta:
>> Hmmm..
>> In the Perl example password generates after user hit ENTER not 
>> continously like in Python you wrote... :)
>>
>> i want see various ways to generate passwords even if they some 
>> indirect like using BASE64
>>   
> I copied this from a recipe, I do not remember which one. I like it very 
> much because it creates password that are easy to type in. You can type 
> every odd letter with your left hand and every even letter with your 
> right hand.

That weakens the password significantly. For a six character alpha-numeric
password with no special characters, you have (26*2+10)**6 possible
passwords, or 56,800,235,584.

Using your password generator, you have:

>>> righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB'
>>> lefthand = '789yuiophjknmYUIPHJKLNM'
>>> len(righthand)
35
>>> len(lefthand)
23

and therefore only:

35*23*35*23*35*23 = (35*23)**3 = 521,660,125

possible passwords. That's about one percent of the earlier figure, so
you lose about 99% of the strength of the password. For eight character
passwords the difference is even more dramatic: you reduce the strength of
the password by a factor of roughly 99,999,995/100,000,000.

In my opinion, if you're going to accept such a drastic reduction in
password strength, better to go for a password that is easier to memorise
than a hard-to-memorise-but-easy-to-type weak password.

Here's one such algorithm:

* think of a meaningful phrase you won't forget: e.g. "Snow White and the
Seven Dwarves"

* take the first letter of each word: "swatsd" 

* mix up the capitals and make it leet: "5Wat7D"

* add some special characters if you can: "5W&t7D"

* if it is not long enough, add a suffix or prefix or both: "p5W&t7D."

And now you have a strong password that you can remember but is unlikely
to be guessed.



-- 
Steven D'Aprano 

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


Re: The reliability of python threads

2007-01-29 Thread Aahz
In article <[EMAIL PROTECTED]>,
Carl J. Van Arsdall <[EMAIL PROTECTED]> wrote:
>Aahz wrote:
>>
>> My response is that you're asking the wrong questions here.  Our database
>> server locked up hard Sunday morning, and we still have no idea why (the
>> machine itself, not just the database app).  I think it's more important
>> to focus on whether you have done all that is reasonable to make your
>> application reliable -- and then put your efforts into making your app
>> recoverable.
>>   
>Well, I assume that I have done all I can to make it reliable.  This 
>list is usually my last resort, or a place where I come hoping to find 
>ideas that aren't coming to me naturally.  The only other thing I 
>thought to come up with was that there might be network errors.  But 
>i've gone back and forth on that, because TCP should handle that for me 
>and I shouldn't have to deal with it directly in pyro, although I've 
>added (and continue to add) checks in places that appear appropriate 
>(and in some cases, checks because I prefer to be paranoid about errors).

My point is that an app that dies only once every few months under load
is actually pretty damn stable!  That is not the kind of problem that
you are likely to stimulate.

>> I'm particularly making this comment in the context of your later point
>> about the bug showing up only every three or four months.
>>
>> Side note: without knowing what error messages you're getting, there's
>> not much anybody can say about your programs or the reliability of
>> threads for your application.
>   
>Right, I wasn't coming here to get someone to debug my app, I'm just 
>looking for ideas.  I constantly am trying to find new ways to improve 
>my software and new ways to reduce bugs, and when i get really stuck, 
>new ways to track bugs down.  The exception won't mean much, but I can 
>say that the error appears to me as bad data.  I do checks prior to 
>performing actions on any data, if the data doesn't look like what it 
>should look like, then the system flags an exception.
>
>The problem I'm having is determining how the data went bad.  In 
>tracking down the problem a couple guys mentioned that problems like 
>that usually are a race condition.  From here I examined my code, 
>checked out all the locking stuff, made sure it was good, and wasn't 
>able to find anything.  Being that there's one lock and the critical 
>sections are well defined, I'm having difficulty.  One idea I have to 
>try and get a better understanding might be to check data before its 
>stored.  Again, I still don't know how it would get messed up nor can I 
>reproduce the error on my own. 
>
>Do any of you think that would be a good practice for trying to track 
>this down? (Check the data after reading it, check the data before 
>saving it)

What we do at my company is maintain log files.  When we think we have
identified a potential choke point for problems, we add a log call.
Tracking this down will involve logging the changes to your data until
you can figure out where it goes wrong -- once you know where it goes
wrong, you have an excellent chance of figuring out why.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set update in 2.5

2007-01-29 Thread Duncan Smith
Peter Otten wrote:
> Duncan Smith wrote:
> 
> 
>> In moving from 2.4 to 2.5 I find that some of my unit tests are now
>>failing.  I've worked out that the problem relates to the set update
>>method.  In 2.4 I could update a set with an iterable type derived from
>>dict as the argument.  I now find that the set is updated with the hash
>>values of the items in my iterable, rather than the items themselves.
>>Converting to a list first gets round the problem.
>>
>>My iterable type has the same API as 'set' but requires items to have
>>hashable 'uid' attributes, so they can also be looked up by uid.  I hope
>>this, and the fact that this worked fine in 2.4 will be enough to track
>>down the issue without me having to paste reams of code (other than the
>>following, pasted from IDLE).  Any ideas?  Cheers.
>>
>>Duncan
>>
>>
>>
>from graphItems import Node
>from keyed_sets import KeyedSet
>n = Node(1)
>n.uid
>>
>>1
>>
>k = KeyedSet([n])
>k
>>
>>KeyedSet([1])
>>
>type(iter(k).next())
>>
>>
>>
>type(k[1])
>>
>>
>>
>s = set()
>s.update(list(k))
>type(iter(s).next())
>>
>>
>>
>s = set()
>s.update(k)
>type(iter(s).next())
>>
>>
>>
>s = set()
>s.add(n)
>type(iter(s).next())
>>
>>
>>
>hash(n)
>>
>>1
>>
> 
> Is your KeyedSet derived from dict?
> 

Thanks Peter.  It is derived from dict.

> $ python2.5
> [snip]
> 
class D(dict):
> 
> ... def __iter__(self): return self.itervalues()
> ...
> 
d = D(a=1, b=2)
set(d)
> 
> set(['a', 'b'])
> 
> 
> $ python2.4
> [snip]
> 
class D(dict):
> 
> ... def __iter__(self): return self.itervalues()
> ...
> 
d = D(a=1, b=2)
set(d)
> 
> set([1, 2])
> 
> 
> I think you should file a bug report. The fix is probably
> 
> --- setobject.c 2006-09-08 08:02:26.0 +0200
> +++ setobject_new.c 2007-01-28 10:02:24.071688248 +0100
> @@ -854,7 +854,7 @@
> if (PyAnySet_Check(other))
> return set_merge(so, other);
> 
> -   if (PyDict_Check(other)) {
> +   if (PyDict_CheckExact(other)) {
> PyObject *value;
> Py_ssize_t pos = 0;
> while (PyDict_Next(other, &pos, &key, &value)) {
> 
> Peter

I will file a report.  Cheers.

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


Re: Excellent Interview with Dennis D'Souza, full of laughs

2007-01-29 Thread Michael L Torrie
On Mon, 2007-01-29 at 15:47 -0800, [EMAIL PROTECTED] wrote:
> 
I know this is a useless gesture, but my normal tolerance for such
behavior has reached an end.

Please stop spamming this list with off-topic profanities.  Your
ramblings have nothing to do with programming in Python (this is a
computer-related group by the way) and grow tiresome.  I generally
tolerate occasional off-topic posts because they can be intelligent,
witty, diverting, and sometimes informative and educational.  However
your posts are none of these things.  There are plenty of forums out
there for you to vent your frustrations and express your beliefs and
opinions.  Kindly take your musings elsewhere, particularly when you
have to resort to using profanity to make up for your lack of elegant
expression and inability to argue a point, or even present a point.

Should this become more of a problem, I would vote in favor of moving
this newsgroup to being moderated.  In fact, I'd be in favor of shutting
down the newsgroup entirely and using the members-only mailing list
exclusively, although I know a number of people here would oppose that.

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


Re: deepcopy alternative?

2007-01-29 Thread Szabolcs Nagy
> I believe the only thing stopping me from doing a deepcopy is the
> function references, but I'm not sure.  If so is there any way to
> transform a string into a function reference(w/o eval or exec)?

what's your python version?
for me deepcopy(lambda:1) does not work in py2.4 but it works in py2.5
(in py2.4 i tried to override __deepcopy__ but it had no effect)

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


Bush, clean up your shit and farts before you leave - Hillary Clinton

2007-01-29 Thread thermate
But Bush was merely an ego front for the neocons ... He spoke their 
speeches, signed their recommendations, and ordered their wars, go and 
listen to Benjamin Friedman's excellent video in his very passionate 
voice ...

http://video.google.com/videoplay?docid=3552214685532803163&q



http://www.nydailynews.com/front/story/492891p-415149c.html

Hil to W: Clean up your own mess
Leaving it to next Prez is irresponsible, she tells Iowa crowd

BY MICHAEL McAULIFF
DAILY NEWS WASHINGTON BUREAU

Hillary Clinton addresses crowd at town-hall style meeting yesterday 
in Davenport, Iowa. Her two-day swing through Iowa, where she hit hard 
on issues like Iraq war and health care, was first trip to state with 
earliest caucus since announcing presidential candidacy.
DAVENPORT, Iowa - President Bush should clean up the mess he made in 
Iraq and bring American troops home before he leaves the White House 
in 2009, Sen. Hillary Clinton said yesterday.

Clinton fired her rhetoric-raising broadside at Bush and the Iraq war 
on her first swing through Iowa as a presidential hopeful, painting 
herself as tough, warm and presidential all at the same time.

"The President has said this is going to be left to his successor," 
she said at a rally in Davenport. "I think it's the height of 
irresponsibility, and I really resent it.

"This was his decision to go to war; he went with an ill-conceived 
plan, an incompetently executed strategy, and we should expect him to 
extricate our country from this before he leaves office," the former 
First Lady said.

White House spokesman Rob Saliterman criticized Clinton (D-N.Y.) for 
"a partisan attack that sends the wrong message to our troops and the 
Iraqi people."

One questioner challenged Clinton to explain her vote in late 2002 to 
authorize the war. She said Congress was "misled" at the time by the 
President.

"He took the authority that I and others gave him, and he misused it," 
she said. "And I regret that deeply. And if we had known then what we 
know now, there never would have been a vote, and I never would have 
voted to give this President that authority."

Dawn Trettin, 33, and her son Ramon Briones, 18, who has joined the 
Army, said they liked what they heard from Clinton. Trettin, though, 
teared up when someone in the crowd told her son not to go to Iraq.

"I don't want to just pull out and leave it in chaos," she said, 
though she was waiting to make up her mind on whom to vote for next 
year.

Her son, who said he liked Clinton's depth, was ready to commit after 
hearing her pitch. "I liked her," he said. "I would vote for her."

Clinton is leading her Democratic rivals in national polls, but she is 
not the front-runner in Iowa. If Iowa's first-in-the-nation caucus was 
held now, she would lose to 2004 vice presidential nominee John 
Edwards. She also trails former Iowa Gov. Tom Vilsack and Illinois 
Sen. Barack Obama in state polls.

She completed a two-day swing through the state last night in a bid to 
close the gap and tried to erase the perception among many Iowans that 
she can't win, talking to them in small groups in living rooms and by 
the thousands in large halls.

The reception was strong, and Camp Clinton liked what it saw.

"We are thrilled with the weekend," said Clinton spokesman Howard 
Wolfson.

Clinton also focused on middle-class issues like making college more 
affordable and obtaining universal health care coverage.

She promised to try to at least get universal coverage for kids during 
her next two years in the Senate.

Today, she's picking up the war theme theme again in Texas, attending 
the dedication of Brooke Army Medical Center's $50 million Center for 
the Intrepid. The 60,000-square-foot physical rehabilitation center is 
for veterans injured in the war.

Originally published on January 28, 2007

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


Another link to the audio of radio interview by Dinesh D'Souza - HILLARIOUS

2007-01-29 Thread thermate
"http://a1135.g.akamai.net/f/1135/18227/1h/
cchannel.download.akamai.com/18227/podcast/PORTLAND-OR/KPOJ-AM/
1-23-07%20POJ-cast.mp3?CPROG=PCAST&MARKET=PORTLAND-
OR&NG_FORMAT=newstalk&SITE_ID=674&STATION_ID=KPOJ-
AM&PCAST_AUTHOR=AM620_KPOJ&PCAST_CAT=Talk_Radio&PCAST_TITLE=Thom_Hartma
nn_Podcast"

http://loadedorygun.blogspot.com/2007/01/disassembling-dsouza.html

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


Re: Excellent Interview with Dennis D'Souza, full of laughs

2007-01-29 Thread thermate
Listen you mother fucker VULTURE, the past cold war was with soviet
block, NOW the whole world hates you ... bastard you need friends, but
now with your 911 in which YOU KILLED YOUR OWN CITIZENS, you are THE
MOST ODIOUS NATION ON EARTH.

YOU NEED FRIENDS, your biggest perceived rival CHINA is the most
popular nation on earth ... Venezuela's Chavez is most popular, and 
you
are the most odious anglo-saxon yank bastards ... Islamists hate you
also and neocons also hate you, only using you as trash paper as they
used Germany during WW1 and WW2, listen to Benjamin Friedman

On Jan 29, 10:15 am, "Frank Arthur" <[EMAIL PROTECTED]> wrote:
> Islamist bastard <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]
>
> <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]
>
> > FBI spook bastard  that speaks french also
>
> > On Jan 29, 8:13 am, "Hampton Din" <[EMAIL PROTECTED]> wrote:
> >>  stupid troll

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


Re: Conversion of string to integer

2007-01-29 Thread John Machin


On Jan 30, 6:48 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 
wrote:
> On Jan 29, 2:55 pm, "jupiter" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi guys,
>
> > I have a problem. I have a list which contains strings and numeric.
> > What I want is to compare them in loop, ignore string and create
> > another list of numeric values.
>
> > I tried int() and decimal() but without success.
>
> > eq of problem is
>
> > #hs=string.split(hs)
> > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
>
> > j=0
> > for o in range(len(hs)):
> > print hs[o],o
> > p=Decimal(hs[o])
> > if p > 200: j+=j
> > print "-"*5,j
> > print "*"*25
>
> > I could be the best way to solve this ..?
>
> > @nilfunction isinstance can help you to determine the type/class of an
> object:
>
> py>hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
> py>
> py>for i in hs:
> py>if isinstance(i, str):
> py>print str(i)
> py>elif isinstance(i, float):
> py>print float(i)
> py>elif isinstance(i, int):
> py>print int(i)
> py>else:
> py>print 'dunno type of this element: %s' % str(i)
> popopopopop
> 254.25
> pojdjdkjdhhjdccc
> 25452.25

Call me crazy, but I can't understand what the above code is meant to 
demonstrate.

(1) All of the elements in "hs" are *known* to be of type str. The 
above code never reaches the first elif. The OP's problem appears to 
be to distinguish which elements can be *converted* to a numeric type.

(2) if isinstance(i, some_type) is true, then (usually) some_type(i) 
does exactly nothing that is useful

Awaiting enlightenment ...

John

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


Re: Overloading assignment operator

2007-01-29 Thread Michael Spencer
J. Clifford Dyer wrote:
  > I think that's the first time I've actually seen someone use a Monty
> Python theme for a python example, and I must say, I like it.  However,
> "We are all out of Wensleydale."
> 
> Cheers,
> Cliff

Oh, then you clearly don't waste nearly enough time on this newsgroup ;-)

http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=spam+eggs

http://groups.google.com/group/comp.lang.python/search?q=shrubbery

http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=knights+ni

http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=larch

Idly yours,

Michael

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


Re: python 2.3 module ref

2007-01-29 Thread Szabolcs Nagy

> any pointers to a 2.3 module ref?

also look at:
http://rgruet.free.fr/PQR2.3.html#OtherModules

when coding for different python versions i can reccommend this quick 
ref:
http://rgruet.free.fr/

(every language feature is colorcoded according to the version when it 
was included)

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


select windows

2007-01-29 Thread Siqing Du
Hi,

Is there is a way to write a program to select and switch between
windows? For instance, if I have three windows: Firefox, Thunderbird,
and emacs, can I run a program to bring up the desired windows, instead
of click on the  windows use mouse.

Thanks,

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


deepcopy alternative?

2007-01-29 Thread none
I have a very complex data structure which is basically a class object 
containing (sometimes many) other class objects, function references, 
ints, floats, etc.  The man for the copy module states pretty clearly 
that it will not copy methods or functions.  I've looked around for a 
while (prob just using the wrong keywords) and haven't found a good 
solution.  As a workaround I've been using cPickle, loads(dumps(obj)) 
which is incredibly slow (~8 sec for a 1000 elem list).

I believe the only thing stopping me from doing a deepcopy is the 
function references, but I'm not sure.  If so is there any way to 
transform a string into a function reference(w/o eval or exec)?

Example
from copy import deepcopy
a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj[funcRef])
b = deepcopy(a)
TypeError: function() takes at least 2 arguments (0 given)

All I want is a deepcopy of the list.  Any suggestions would be appreciated.

Jack Trades

PS: If the answer to this is in __getstate__() or __setstate__() is 
there some reference to how these should be implemented besides the 
library reference?
-- 
http://mail.python.org/mailman/listinfo/python-list


python-list@python.org

2007-01-29 Thread Pappy
SHORT VERSION:
Python File B changes sys.stdout to a file so all 'prints' are written 
to the file.  Python file A launches python file B with os.popen("./B 
2>&^1 >dev/null &").  Python B's output disappears into never-never 
land.

LONG VERSION:
I am working on a site that can kick off large-scale simulations.  It 
will write the output to an html file and a link will be emailed to 
the user.  Also, the site will continue to display "Loading..." if the 
user wants to stick around.

The simulation is legacy, and it basically writes its output to stdout 
(via simple print statements).  In order to avoid changing all these 
prints, I simply change sys.stdout before calling the output 
functions.  That works fine.  The whole thing writes to an html file 
all spiffy-like.

On the cgi end, all I want my (python) cgi script to do is check for 
form errors, make sure the server isn't crushed, run the simulation 
and redirect to a loading page (in detail, I write a constantly 
updating page to the location of the final output file.  When the 
simulation is done, the constantly updating file will be magically 
replaced).  The root problem is that the popen mechanism described 
above is the only way I've found to truly 'Detach' my simulation 
process.  With anything else, Apache (in a *nix environment) sits and 
spins until my simulation is done.  Bah.

Any ideas?

_jason

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


Re: [Boost.Graph] graph.vertices property creates new objects

2007-01-29 Thread Szabolcs Nagy
> It seems that the vertices iterator creates new vertex objects every
> time instead of iterating over the existing ones. This essentially

i don't know much about bgl, but this is possible since vertices are 
most likely not stored as python objects inside boost

> prevents, among other things, storing vertices as keys in a dictionary
> since the hashes of the stored and the new vertex differ although they
> compare equal. Is this really what's happening, and if so, why ?

that sounds bad, fortunately __hash__ can be overriden so even if id() 
differs hash() can be the same for the same vertex.
if __hash__ is not handled then it's a bug in bgl imho.

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


Re: ctypes: Setting callback functions in C libraries

2007-01-29 Thread [EMAIL PROTECTED]
I realized my wrapping was broken, fixing that below...

On Jan 25, 12:47 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 
wrote:
> I'm trying to wrap GNU readline withctypes(the Python readline
> library doesn't support the callback interface), but I can't figure out
> how to set values to a variable inside the library.  This is Python 2.5
> on Linux.  Here's what I have so far--if you comment out the memmove
> call (3 lines) it works as expected:
[SNIP]
> I need to assign ourfunc to RL_ATTEMPTED_COMPLETION_FUNCTION, but
> obviously simple assignment rebinds the name rather than assigning it
> to the C variable.
>
> Usingctypes.memmove to overwrite it(as I have here) will run the
> function but segfault when ourfunc goes to return (poking around with
> the debugger shows it's dying inctypes' callbacks.c at line 216, "keep
> = setfunc(mem, result, 0);" because setfunc is NULL).  I'm not entirely
> sure that's not because of some error in the prototyping or restype
> setting rather than as a result of memmove, but the memmove seems
> sketchy enough (only sets the function pointer itself presumably, not
> anything thatctypeswrappers need) that I'm looking for a better way
> to do it.
>
> As it is, returning rv directly or simply returning None causes the
> same segfault.
>
> Any idea?
>
> Thanks very much for your time!

# START
#!/usr/local/bin/python2.5
import ctypes

ctypes.cdll.LoadLibrary("libcurses.so")#, mode=ctypes.RTLD_GLOBAL)
ctypes.CDLL("libcurses.so", mode=ctypes.RTLD_GLOBAL)
ctypes.cdll.LoadLibrary("libreadline.so")
readline = ctypes.CDLL("libreadline.so")

RL_COMPLETION_FUNC_T = \
ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char_p),
ctypes.c_char_p, ctypes.c_int, ctypes.c_int)
RL_LINE_BUFFER = ctypes.c_char_p.in_dll(readline, "rl_line_buffer")
RL_ATTEMPTED_COMPLETION_FUNCTION = \
RL_COMPLETION_FUNC_T.in_dll(readline,
"rl_attempted_completion_function")

def our_complete(text, start, end):
print "Test", text, start, end
rv = None
arrtype = ctypes.c_char_p*4
globals()["rv"] = arrtype("hello", "hatpin", "hammer", None)
globals()["crv"]=ctypes.cast(rv, ctypes.POINTER(ctypes.c_char_p))
return rv
ourfunc = RL_COMPLETION_FUNC_T(our_complete)

_readline = readline.readline
_readline.argtypes = [ctypes.c_char_p]
_readline.restype = ctypes.c_char_p

ctypes.memmove(ctypes.addressof(RL_ATTEMPTED_COMPLETION_FUNCTION),
   ctypes.addressof(ourfunc),
   4)
line = _readline("Input: ")
print "INPUT was: ", line
#END

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


Re: Overloading assignment operator

2007-01-29 Thread J. Clifford Dyer
Steven D'Aprano wrote:
> On Tue, 23 Jan 2007 18:07:55 -0800, Russ wrote:
> 
>> Achim Domma wrote:
>>> Hi,
>>>
>>> I want to use Python to script some formulas in my application. The user
>>> should be able to write something like
>>>
>>> A = B * C
>>>
>>> where A,B,C are instances of some wrapper classes. Overloading * is no
>>> problem but I cannot overload the assignment of A. I understand that
>>> this is due to the nature of Python, but is there a trick to work around
>>> this?
>>> All I'm interested in is a clean syntax to script my app. Any ideas are
>>> very welcome.
>>>
>>> regards,
>>> Achim
>> Why do you need to overload assignment anyway? If you overloaded "*"
>> properly, it should return
>> the result you want, which you then "assign" to A as usual. Maybe I'm
>> missing something.
> 
> One common reason for overriding assignment is so the left-hand-side of
> the assignment can choose the result type. E.g. if Cheddar, Swiss and
> Wensleydale are three custom classes, mutually compatible for
> multiplication:
> 
> B = Cheddar()  # B is type Cheddar
> C = Swiss()# C is type Swiss
> # without overloading assignment
> A = B * C  # A is (possibly) Cheddar since B.__mul__ is called first
> A = C * B  # A is (possibly) Swiss since C.__mul__ is called first
> # with (hypothetical) assignment overloading 
> A = B * C  # A is type Wensleydale since A.__assign__ is called
> 
> Except, of course, there is no assignment overloading in Python. There
> can't be, because A may not exist when the assignment is performed, and
> if it does exist it might be a complete different type.
> 
> Instead, you can do something like this:
>  
> A = Wensleydale(B) * Wensleydale(C)
> 
> or 
> 
> A = Wensleydale(B * C)
> 
> 
> 
> 

I think that's the first time I've actually seen someone use a Monty
Python theme for a python example, and I must say, I like it.  However,
"We are all out of Wensleydale."

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


Re: Bush, yank bastards kicked by india in their arse Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-29 Thread thermate
On Jan 29, 11:15 am, "Vance P. Frickey" <[EMAIL PROTECTED]> wrote:

> Directorate (overseas espionage), his old employers owned
> someone in just about every important government agency in
> India, from the 1970s until they stopped being able to
> afford paying all those bribes.

But in this anglo-saxon heaven, monica lewinsky owns every president 
by his balls. Reagan and Herber Walker Bush have a serious pedophilia 
charges against
them. The jewcons control George Bush. In another article I will 
describe how
his mind is controlled. How he is fed the information and has no 
personal skill.
He is only good for exercising his ego and repeating what is taught to 
him. He
only signs documents. He cannot write his own speech. He cannot 
passionately
defend himself against tough opponents in public. In the presidential 
debates
he was scared to death. Certaily, kerry let him off very easily, and 
possibly
because kerry was under the threat of blackmail to not cross the line. 
If kerry
has attacked bush as a liar, or with valery plame case or Abu Gharib 
or using other strong points bush would have probably fainted from 
fear.

Almost every US senator is in the pocket of a certain lobby, which is 
too obvious to name  LAUGHING OUT LOUD

God save the Honorable Reverend Jimmy Carter for the book ..

Dont talk about India Impudently, ever .

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


Re: The reliability of python threads

2007-01-29 Thread Carl J. Van Arsdall
Hendrik van Rooyen wrote:
> [snip]
>> could definitely do more of them.  The thing will be 
>> 
>
> When I read this - I thought - probably your stuff is working 
> perfectly - on your test cases - you could try to send it some
> random data and to see what happens - seeing as you have a test 
> server, throw the kitchen sink at it.
>
> Possibly "random" here means something that "looks like" data
> but that is malformed in some way. Kind of try to "trick" the 
> system to get it to break reliably.
>
> I'm sorry I can't be more specific - it sounds so weak, and you
> probably already have test cases that "must fail" but I don't 
> know how to put it any better...
>   
Well, sometimes a weak analogy is the best thing because it allows me to 
fill in the blanks "How can I throw a kitchen sink at it in a way I 
never have before"

And away my mind goes, so thank you.

-carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread NoName
WOW! :shock:

in this case:

while 1:i=__import__;print 
i('binascii').b2a_base64(i('os').urandom(6)),;raw_input()


On 30 Янв., 04:06, "Szabolcs Nagy" <[EMAIL PROTECTED]> wrote:
> > while
> > 1:i=__import__;print''.join(i('random').choice(i('string').letters
> > +'1234567890')for x in range(8)),;raw_input()while
> 1:i=__import__;r='random';print''.join(i(r).choice(i('string').letters
> +'1234567890')for x in`r`),;raw_input()
>
> even shorter:
> range -> `'random'`
>
> :)

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

Re: Data structure and algorithms

2007-01-29 Thread azrael
thanks guys. i see that there is no way then to go back to C to 
satisfy my prof and get a grade

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


Re: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll

2007-01-29 Thread Peter Wang
On Jan 29, 2:47 pm, [EMAIL PROTECTED] wrote:
> The library seems to build correctly (producing Polygon.py and
> cPolygon.pyd), but when I import it I get the following message from
> python.exe: "This application has failed to start because MSVCR80.dll
> was not found". I thought that this might be due to Python trying to
> link against  the .dll from Microsoft Visual C++ Express 2005, also
> installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C
> ++ Express 2005, and any trace of it from my environment variables,
> but that doesn't seem to change anything.

Alex,  I'm not familiar with the particular problem you're seeing, but 
did you try building the polygon library using the gcc that's included 
with the Enthought distribution?

python setup.py build_clib build_ext --inplace --compiler=mingw32


-Peter

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


We sell to everyone!!! Government, Wholesalers, Distributers, Entreprenuers.....www.martin-global.com

2007-01-29 Thread Martin Global
Martin Global is one of North America's leading importers of goods
 manufactured and produced throughout Asia. We are distinctively 
unique
 from other importers, as we have one of North America's largest 
networks
 linking our organization directly to thousands of manufacturers and 
suppliers in
 Asia and throughout the world.

 We at Martin Global are proud of our reputation for excellence: a
 reputation based on our commitment to the highest manufacturing and 
ethical
 standards.  At Martin Global, all of our business relationships with 
customers,
 suppliers, manufacturers and employees rest on a foundation of 
integrity and
 trust.


 Mission Statement

 Martin Global puts the needs of its clients first! We strive to 
establish
 long-term personal relationships built upon clients' trust in our 
ability
 to provide superior products at competitive prices. Whether you're a 
large
 corporation, government entity or a sole proprietor, we take these
 relationships very seriously and we believe that our success is 
measured
 by the success of our clients and their return business. Inquiries 
always welcomed.

 Your message will responded to within 8 hours.

 Regards,


 Donovan Martin
 Martin Global

www.martin-global.com

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


We sell to everyone!!! Government, Wholesalers, Distributers, Entreprenuers.....www.martin-global.com

2007-01-29 Thread Martin Global
Martin Global is one of North America's leading importers of goods
 manufactured and produced throughout Asia. We are distinctively 
unique
 from other importers, as we have one of North America's largest 
networks
 linking our organization directly to thousands of manufacturers and 
suppliers in
 Asia and throughout the world.

 We at Martin Global are proud of our reputation for excellence: a
 reputation based on our commitment to the highest manufacturing and 
ethical
 standards.  At Martin Global, all of our business relationships with 
customers,
 suppliers, manufacturers and employees rest on a foundation of 
integrity and
 trust.


 Mission Statement

 Martin Global puts the needs of its clients first! We strive to 
establish
 long-term personal relationships built upon clients' trust in our 
ability
 to provide superior products at competitive prices. Whether you're a 
large
 corporation, government entity or a sole proprietor, we take these
 relationships very seriously and we believe that our success is 
measured
 by the success of our clients and their return business. Inquiries 
always welcomed.

 Your message will responded to within 8 hours.

 Regards,


 Donovan Martin
 Martin Global

www.martin-global.com

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


Re: strip question

2007-01-29 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> hi
> can someone explain strip() for these :
> [code]
> 
x='www.example.com'
x.strip('cmowz.')
> 
> 'example'
> [/code]
> 
> when i did this:
> [code]
> 
x = 'abcd,words.words'
x.strip(',.')
> 
> 'abcd,words.words'
> [/code]
> 
> it does not strip off "," and "." .Why is this so?

Probably because the Fine Manual(tm) says that str.strip() removes 
heading and trailing chars ?

"""
[EMAIL PROTECTED] ~ $ python
Python 2.4.1 (#1, Jul 23 2005, 00:37:37)
[GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on 
linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> help(''.strip)
Help on built-in function strip:

strip(...)
 S.strip([chars]) -> string or unicode

 Return a copy of the string S with leading and trailing
 whitespace removed.
 If chars is given and not None, remove characters in chars instead.
 If chars is unicode, S will be converted to unicode before stripping
"""


You may want to try str.replace() instead:

"""
 >>> help(''.replace)
Help on built-in function replace:

replace(...)
 S.replace (old, new[, count]) -> string

 Return a copy of string S with all occurrences of substring
 old replaced by new.  If the optional argument count is
 given, only the first count occurrences are replaced.
 >>> 'abcd,words.words'.replace(',', '').replace('.', '')
'abcdwordswords'
"""

> thanks

HTH

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


Re: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll

2007-01-29 Thread Martin v. Löwis
[EMAIL PROTECTED] schrieb:
> The library seems to build correctly (producing Polygon.py and 
> cPolygon.pyd), but when I import it I get the following message from 
> python.exe: "This application has failed to start because MSVCR80.dll 
> was not found". I thought that this might be due to Python trying to 
> link against  the .dll from Microsoft Visual C++ Express 2005, also 
> installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C
> ++ Express 2005, and any trace of it from my environment variables, 
> but that doesn't seem to change anything.
> 
> Any help would be greatly appreciated.

Can you find out where msvcrt.lib comes from? If you manage to copy
the linker command line, I think link.exe has a way of telling you
where it picked up the file. If that won't work, and you find multiple
copies of msvcrt.lib on your disk, you can use dumpbin /all on
each of them to find out which one is right.

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


Re: Sourcing Python Developers

2007-01-29 Thread Kartic
Paul Rubin sayeth,  on 01/29/2007 03:44 PM:
> Kartic <[EMAIL PROTECTED]> writes:
>> In any case, we have immediate requirements for a Pythonista with C++,
>> MySQL, XML, Debian expertise. Please email resume to:
> 
> Generally it's ok to post here to the newsgroup with Python jobs.  But
> you should describe the specific openings you're trying to fill, and
> their locations.  

Paul - Thanks for the clarification; will use the list _sparingly_ post 
jobs.

The skills I listed are the once I have (Py, MySQL, C++, XML, Debian). 
Location: Torrance CA.
Compensation: Commensurate with Experience.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Behavior when inserting new items

2007-01-29 Thread Bruno Desthuilliers
Drew a écrit :
>>What is your actual usecase?
>>
>>diez
> 
> 
> The issue is that I don't know how long the list will eventually be. 

How is this an issue ? Python's lists are not fixed-sized arrays.

> Essentially I'm trying to use a 2D list to hold lines that I will 
> eventually print to the screen.
 >
> Blank elements in the list will be 
> printed as spaces. I suppose every time I add an element, I could find 
> the difference between the size of the list and the desired index and 
> fill in the range between with " " values,

Yes. But note that [1,2,3,' ',' ',4]
is not the same thing as [1,2,3,,,4] (which is not valid Python FWIW).

> however I just wanted to 
> see if there was a more natural way in the language.

I'm not sure I get it. Do you mean you're trying to use a list of lists 
as a representation of a 2D matrix (IOW, a bitmap) ? Something like

bpm = [
   ['X',' ',' ',' ','X'],
   [' ','X',' ','X',' '],
   [' ',' ','X',' ',' '],
   [' ','X',' ','X',' '],
   ['X',' ',' ',' ','X'],
]

If so, using dicts can be somewhat simpler and less memory-consuming:

d = {1:1, 2:2, 3:3}
d[10] = 4
for i in range(1, max(d.keys())+1):
   print d.get(i, ' ')

That is, instead of storing useless spaces for "blank cells" and having 
to do math to compute how many of them you have to insert/delete, you 
just place stuff at desired indices, and 'fill in' spaces when printing 
out to screen.

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


Re: Executing Javascript, then reading value

2007-01-29 Thread Melih Onvural
Thanks, let me check out this route, and then I'll post the results.

Melih Onvural

On Jan 29, 4:04 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On 29 Jan 2007 12:44:07 -0800, Melih Onvural <[EMAIL PROTECTED]> wrote:
>
> >I need to execute some javascript and then read the value as part of a
> >program that I am writing. I am currently doing something like this:Python 
> >doesn't include a JavaScript runtime.  You might look into the
> stand-alone Spidermonkey runtime.  However, it lacks the DOM APIs, so
> it may not be able to run the JavaScript you are interested in running.
> There are a couple other JavaScript runtimes available, at least.  If
> Spidermonkey is not suitable, you might look into one of them.
>
> Jean-Paul

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


Re: python 2.3 module ref

2007-01-29 Thread Martin v. Löwis
David Bear schrieb:
> Since redhat packages python2.3 with their distro (RHEL 4..) I was looking
> for a module reference for that version. Looking at python.org I only see
> current documentation.
> 
> any pointers to a 2.3 module ref?

http://www.python.org/doc/2.3/
http://www.python.org/doc/2.3/lib/lib.html

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


Re: List Behavior when inserting new items

2007-01-29 Thread Drew

> > Is there any way to produce this kind of behavior easily?Hints:
>  >>> [None] * 5
> [None, None, None, None, None]
>  >>> [1, 2, 3, None] + [10]
> [1, 2, 3, None, 10]
>
> HTH

That is exactly what I was looking for. I'm actually working on some 
problems at http://codgolf.com. I find it helps me to learn a language 
and I'm coming from ruby where arrays have subtle differences from 
python's lists. Thanks for all the helpful responses.

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


Re: Convert from unicode chars to HTML entities

2007-01-29 Thread Martin v. Löwis
Steven D'Aprano schrieb:
> A few issues:
> 
> (1) It doesn't seem to be reversible:
> 
 '© and many more...'.decode('latin-1')
> u'© and many more...'
> 
> What should I do instead?

For reverse processing, you need to parse it with an
SGML/XML parser.

> (2) Are XML entities guaranteed to be the same as HTML entities?

Please make a terminology difference between "entity", "entity
reference", and "character reference".

An (external parsed) entity is a named piece of text, such
as the copyright character. An entity reference is a reference
to such a thing, e.g. ©

A character reference is a reference to a character, not to
an entity. xmlcharrefreplace generates character references,
not entity references (let alone generating entities). The
character references in XML and HTML both reference by
Unicode ordinal, so it is "the same".

> (3) Is there a way to find out at runtime what encoders/decoders/error
> handlers are available, and what they do? 

Not through Python code. In C code, you can look at the
codec_error_registry field of the interpreter object.

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


Re: python 2.3 module ref

2007-01-29 Thread Robert Kern
David Bear wrote:
> Since redhat packages python2.3 with their distro (RHEL 4..) I was looking
> for a module reference for that version. Looking at python.org I only see
> current documentation.
> 
> any pointers to a 2.3 module ref?

  http://docs.python.org/

Click on "Locate previous versions."

  http://www.python.org/doc/versions/

Click on "2.3.5" (or whichever microrelease your desire).

  http://www.python.org/doc/2.3.5/

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Executing Javascript, then reading value

2007-01-29 Thread Jean-Paul Calderone
On 29 Jan 2007 12:44:07 -0800, Melih Onvural <[EMAIL PROTECTED]> wrote:
>I need to execute some javascript and then read the value as part of a
>program that I am writing. I am currently doing something like this:

Python doesn't include a JavaScript runtime.  You might look into the
stand-alone Spidermonkey runtime.  However, it lacks the DOM APIs, so
it may not be able to run the JavaScript you are interested in running.
There are a couple other JavaScript runtimes available, at least.  If
Spidermonkey is not suitable, you might look into one of them.

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


python 2.3 module ref

2007-01-29 Thread David Bear
Since redhat packages python2.3 with their distro (RHEL 4..) I was looking
for a module reference for that version. Looking at python.org I only see
current documentation.

any pointers to a 2.3 module ref?
-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Behavior when inserting new items

2007-01-29 Thread Bruno Desthuilliers
Drew a écrit :
> I'm looking to add an element to list of items, however I'd like to 
> add it at a specific index greater than the current size:
> 
> list = [1,2,3]

NB: better to avoid using builtins types and functions names as identifiers.

> list.insert(10,4)
> 
> What I'd like to see is something like:
> 
> [1,2,3,,4]

Hint : the Python representation of nothing is a singleton object named 
None.

> However I see:
> 
> [1,2,3,4]

Yeps. I thought it would have raised an IndexError. But I seldom use 
list.insert() to append to a list - there's list.append() (and/or 
list.extend()) for this.

> Is there any way to produce this kind of behavior easily?

Hints:
 >>> [None] * 5
[None, None, None, None, None]
 >>> [1, 2, 3, None] + [10]
[1, 2, 3, None, 10]

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


Re: List Behavior when inserting new items

2007-01-29 Thread [EMAIL PROTECTED]


On Jan 29, 1:10 pm, "Drew" <[EMAIL PROTECTED]> wrote:
> > What is your actual usecase?
>
> > diezThe issue is that I don't know how long the list will eventually be.
> Essentially I'm trying to use a 2D list to hold lines that I will
> eventually print to the screen. Blank elements in the list will be
> printed as spaces. I suppose every time I add an element, I could find
> the difference between the size of the list and the desired index and
> fill in the range between with " " values, however I just wanted to
> see if there was a more natural way in the language.

I would use DBR's suggestion to use a dictionary and only store
actual values. In this example, I'm making a histogram that only
ends up having results for 4,7,8,9,10 but I want the graph to show
the zero occurrences as well, so I just create them on the fly
when printing.

print
print 'tc factor of 2 distribution (* scale = 8)'
print
tchistkeys = tchist.keys()
tchistkeys.sort()
prev_key = 0
for i in tchistkeys:
while prev_key0:
s = s + '.'
print s
prev_key += 1

##tc factor of 2 distribution (* scale = 8)
##
##  0 (  0)
##  1 (  0)
##  2 (  0)
##  3 (  0)
##  4 (  1) .
##  5 (  0)
##  6 (  0)
##  7 (112) **
##  8 (219) ***.
##  9 ( 58) ***.
## 10 (110) *.




>
> Thanks,
> Drew

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


Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll

2007-01-29 Thread alexandre_irrthum
Hi there,

I am trying to install a Python library with a C extension (the 
Polygon library) and I am having a bad time. My Python version is 
Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug  2 2006, 12:09:59) 
[MSC v.1310 32 bit (Intel)] on Windows XP Pro. I have dutifully 
followed the instructions here:

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

i.e.,

- Installed Microsoft Visual C++ Toolkit Compiler 2003
- Installed Microsoft Platform SDK for Windows Server 2003 R2
- Installed Microsoft .NET Framework SDK, version 1.1
- setup the path, include and lib environment variables with a .bat 
file, as described in the wiki document

The library seems to build correctly (producing Polygon.py and 
cPolygon.pyd), but when I import it I get the following message from 
python.exe: "This application has failed to start because MSVCR80.dll 
was not found". I thought that this might be due to Python trying to 
link against  the .dll from Microsoft Visual C++ Express 2005, also 
installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C
++ Express 2005, and any trace of it from my environment variables, 
but that doesn't seem to change anything.

Any help would be greatly appreciated.

Regards,

alex

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


Re: Sourcing Python Developers

2007-01-29 Thread Paul Rubin
Kartic <[EMAIL PROTECTED]> writes:
> In any case, we have immediate requirements for a Pythonista with C++,
> MySQL, XML, Debian expertise. Please email resume to:

Generally it's ok to post here to the newsgroup with Python jobs.  But
you should describe the specific openings you're trying to fill, and
their locations.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Executing Javascript, then reading value

2007-01-29 Thread Melih Onvural
I need to execute some javascript and then read the value as part of a 
program that I am writing. I am currently doing something like this:

import htmllib, urllib, formatter

class myparser(htmllib.HTMLParser):
insave = 0
def start_div(self, attrs):
for i in attrs:
if i[0] == "id" and i[1] == "pr":
self.save_bgn()
self.insave = 1

def end_div(self):
if self.insave == 1:
print self.save_end()
self.insave = 0

parser = myparser(formatter.NullFormatter())

#def getPageRank(self, url):
try:
learn_url = "http://127.0.0.1/research/getPageRank.html?q=http://
www.yahoo.com&"
pr_url = urllib.urlopen(learn_url)
parser.feed(pr_url.read())
except IOError, e:
print e

but the result is the javascript function and not the calculated 
value. Is there anyway to get the javascript to execute first, and 
then return to me the value? thanks in advance,

Melih Onvural

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


Re: Python does not play well with others

2007-01-29 Thread Bruno Desthuilliers
John Nagle a écrit :

(snip)

>My main concern is with glue code to major packages.  The connections
> to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major
> weaknesses.

Neither MySQLdb nor mod_python are part of the Python's standard lib AFAIK.

>  If you're doing web applications,

I do.

> those are standard pieces
> which need to work right. 

I avoid using MySQL - SQLite does a better job as a lighweight 
SQL-compliant no-server solution, and PostgreSQL is years ahead of MySQL 
when it comes to serious, rock-solid transactional RDBMS. But I had no 
problem with the MySQLdb package so far. I also tend to favor 
Apache-independant deployment solutions, so while I had some fun with 
mod_python, I failed to clearly understand how broken it is. And I did 
not have to worry about the ssl support in Python so far. FWIW, I had do 
some LDAP stuff with both PHP and Python, and I would certainly not 
advocate PHP's LDAP support.

> There's a tendency to treat those as abandonware
> and re-implement them as event-driven systems in Twisted.

While Twisted seems an interesting project, it's usually not the first 
mentioned when talking about web development with Python.

>  Yet the
> main packages aren't seriously broken.  It's just that the learning curve
> to make a small fix to any of them is substantial, so nobody new takes
> on the problem.

If you feel you need it, then it's up to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Behavior when inserting new items

2007-01-29 Thread Paul McGuire
> py>def __init__(self, arg = []):
> py>self.__list = arg

Please don't perpetuate this bad habit!!!  "arg=[]" is evaluated at 
compile time, not runtime, and will give all default-inited llists the 
same underlying list.

The correct idiom is:

def __init__(self, arg = None):
if arg is not None:
self.__list = arg
else:
self.__list = []

-- Paul

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


Re: SQL connecting

2007-01-29 Thread Scripter47
John Nagle skrev:
> Scripter47 wrote:
>> Hey
>>
>> It got a problem with python to connect to my SQL DBs, that's installed
>> on my apache server. how do i connect to sql? Gettting data? Insert into 
>> it?
> 
> You need a third-party open source package called "MySQLdb".
> 
>   John Nagle
Yeah look great but im using python 2.5, and it only support 2.3-2.4 :(, 
but thanks :)

Any better solutions :)

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


Re: Conversion of string to integer

2007-01-29 Thread [EMAIL PROTECTED]


On Jan 29, 2:55 pm, "jupiter" <[EMAIL PROTECTED]> wrote:
> Hi guys,
>
> I have a problem. I have a list which contains strings and numeric.
> What I want is to compare them in loop, ignore string and create
> another list of numeric values.
>
> I tried int() and decimal() but without success.
>
> eq of problem is
>
> #hs=string.split(hs)
> hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
>
> j=0
> for o in range(len(hs)):
> print hs[o],o
> p=Decimal(hs[o])
> if p > 200: j+=j
> print "-"*5,j
> print "*"*25
>
> I could be the best way to solve this ..?
>
> @nil

function isinstance can help you to determine the type/class of an 
object:

py>hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
py>
py>for i in hs:
py>if isinstance(i, str):
py>print str(i)
py>elif isinstance(i, float):
py>print float(i)
py>elif isinstance(i, int):
py>print int(i)
py>else:
py>print 'dunno type of this element: %s' % str(i)
popopopopop
254.25
pojdjdkjdhhjdccc
25452.25

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


Re: SQL connecting

2007-01-29 Thread John Nagle
Scripter47 wrote:
> Hey
> 
> It got a problem with python to connect to my SQL DBs, that's installed
> on my apache server. how do i connect to sql? Gettting data? Insert into 
> it?

You need a third-party open source package called "MySQLdb".

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


Re: List Behavior when inserting new items

2007-01-29 Thread [EMAIL PROTECTED]
On Jan 29, 7:57 pm, "Drew" <[EMAIL PROTECTED]> wrote:
> I'm looking to add an element to list of items, however I'd like to
> add it at a specific index greater than the current size:
>
> list = [1,2,3]
> list.insert(10,4)
>
> What I'd like to see is something like:
>
> [1,2,3,,4]
>
> However I see:
>
> [1,2,3,4]
>
> Is there any way to produce this kind of behavior easily?
>
> Thanks,
> Drew

You could write your own class mimicing a list with your desired 
behaviour, something like:

py>class llist(object):
py>def __init__(self, arg = []):
py>self.__list = arg
py>def __setitem__(self, key, value):
py>length = len(self.__list)
py>if  length < key:
py>for i in range(length, key +1):
py>self.__list.append(None)
py>self.__list[key] = value
py>def __str__(self):
py>return str(self.__list)
py>
py>x = llist()
py>x[10] = 1
py>print x
[None, None, None, None, None, None, None, None, None, None, 1]

for other methods to add to the llist class see http://docs.python.org/
ref/sequence-types.html

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


Re: Conversion of string to integer

2007-01-29 Thread Adam


On Jan 29, 1:55 pm, "jupiter" <[EMAIL PROTECTED]> wrote:
> Hi guys,
>
> I have a problem. I have a list which contains strings and numeric.
> What I want is to compare them in loop, ignore string and create
> another list of numeric values.


You can iterate over the list and use the type() function to work out 
what each entry and choose what to do with it.

type() works like so:
###Code###
>>> a = ["test", 1.25, "test2"]
>>> if type(a[2]) == str:
print "a string"


a string
>>>
###End Code###

Adam

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


Re: Bush, yank bastards kicked by india in their arse Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-29 Thread Vance P. Frickey
Hawk wrote:
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>
> you are such a dork.
>
> India has been a Russian satellite for years and years. 
> Who has been
> running their schools?  Not the British.

According to Oleg Kalugin, former head of the KGB's First 
Directorate (overseas espionage), his old employers owned 
someone in just about every important government agency in 
India, from the 1970s until they stopped being able to 
afford paying all those bribes.

Kalugin's book /The_First_Directorate/ is very interesting 
(even if he's a bit cagey in what he says and what he leaves 
unsaid).  Circumlocution didn't help Kalugin, though - he's 
on Putin's hit list anyway.  He can look forward to reading 
by his own light at bedtime if he's not careful from now on.
-- 
Vance P. Frickey
remove "safety" from listed Email address to send mail

"Either bring this back or be brought back upon it." - a 
Spartan (or Roman, depending on the source you believe) 
mother's words to her son on giving him his shield 


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


SQL connecting

2007-01-29 Thread Scripter47
Hey

It got a problem with python to connect to my SQL DBs, that's installed
on my apache server. how do i connect to sql? Gettting data? Insert into it?

it is a localserver with php if that means something

here is a *REALLY* dirty solution that a have used:
[CODE]
from urllib import *
# sql query
s = 'INSERT INTO `test` (`test`) VALUES ("1");'

# encode and insert into db
params = urlencode({'sql': sql})
urlopen("http://localhost/in/sql.php?%s"; % params)
[/CODE]

-- 
   _.____  __
  /   _/ ___|__|__/  |_  ___  /  |  \__  \
  \_  \_/ ___\_  __ \  \ \   __\/ __ \_  __ \/   |  |_  //
  /\  \___|  | \/  |  |_> >  | \  ___/|  | \/^   / //
/___  /\___  >__|  |__|   __/|__|  \___  >__|  \   | //
 \/ \/ |__| \/   |__|


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


Re: List Behavior when inserting new items

2007-01-29 Thread Drew
> What is your actual usecase?
>
> diez

The issue is that I don't know how long the list will eventually be. 
Essentially I'm trying to use a 2D list to hold lines that I will 
eventually print to the screen. Blank elements in the list will be 
printed as spaces. I suppose every time I add an element, I could find 
the difference between the size of the list and the desired index and 
fill in the range between with " " values, however I just wanted to 
see if there was a more natural way in the language.

Thanks,
Drew

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


Re: wxPython StatusBar Help

2007-01-29 Thread Frank Niessink

2007/1/29, herve <[EMAIL PROTECTED]>:



Does anybody know how to change the foreground colors in a wx.StatusBar




wx.StatusBar is a subclass of wx.Window so SetForegroundColour should
work...

Cheers, Frank

PS: In general, wxPython related questions are best asked on the
wxPython-users mailinglist (see http://www.wxpython.org/maillist.php).
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List Behavior when inserting new items

2007-01-29 Thread Diez B. Roggisch
Drew schrieb:
> I'm looking to add an element to list of items, however I'd like to 
> add it at a specific index greater than the current size:
> 
> list = [1,2,3]
> list.insert(10,4)
> 
> What I'd like to see is something like:
> 
> [1,2,3,,4]
> 
> However I see:
> 
> [1,2,3,4]
> 
> Is there any way to produce this kind of behavior easily?

Use a dictionary?

If you know how large the list eventually will be, and that each 
position is filled, you can also use range(n) to create a list.

What is your actual usecase?

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


Re: Sourcing Python Developers

2007-01-29 Thread Kartic
Current requirements in US only.

Kartic sayeth,  on 01/29/2007 01:56 PM:
> Hello,
> 
> My company has quite a few opening involving python expertise. We are 
> always looking for python resources (and find it difficult filling these 
> positions, might I add). Is there any place to find developers' resumes 
> (like finding jobs from http://python.org/community/jobs/)? If any one 
> knows of a resume repository (other than Monster, Dice, 
> Costs-an-arm-and-leg job site) please share.
> 
> In any case, we have immediate requirements for a Pythonista with C++, 
> MySQL, XML, Debian expertise. Please email resume to: 
> python-resumes(at)temporaryforwarding.com
> 
> Thank you,
> --Kartic
-- 
http://mail.python.org/mailman/listinfo/python-list


List Behavior when inserting new items

2007-01-29 Thread Drew
I'm looking to add an element to list of items, however I'd like to 
add it at a specific index greater than the current size:

list = [1,2,3]
list.insert(10,4)

What I'd like to see is something like:

[1,2,3,,4]

However I see:

[1,2,3,4]

Is there any way to produce this kind of behavior easily?

Thanks,
Drew

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


Sourcing Python Developers

2007-01-29 Thread Kartic
Hello,

My company has quite a few opening involving python expertise. We are 
always looking for python resources (and find it difficult filling these 
positions, might I add). Is there any place to find developers' resumes 
(like finding jobs from http://python.org/community/jobs/)? If any one 
knows of a resume repository (other than Monster, Dice, 
Costs-an-arm-and-leg job site) please share.

In any case, we have immediate requirements for a Pythonista with C++, 
MySQL, XML, Debian expertise. Please email resume to: 
python-resumes(at)temporaryforwarding.com

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


[Boost.Graph] graph.vertices property creates new objects

2007-01-29 Thread George Sakkis
I've just started toying with the python bindings of BGL and I'm 
puzzled from the following:

>>> from boost.graph import Graph
>>> g = Graph()
>>> v = g.add_vertex()
>>> g.vertices.next() == v
True
>>> g.vertices.next() is v
False

It seems that the vertices iterator creates new vertex objects every 
time instead of iterating over the existing ones. This essentially 
prevents, among other things, storing vertices as keys in a dictionary 
since the hashes of the stored and the new vertex differ although they 
compare equal. Is this really what's happening, and if so, why ?

George

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


Re: Data structure and algorithms

2007-01-29 Thread Beej
On Jan 28, 2:56 pm, "azrael" <[EMAIL PROTECTED]> wrote:
> class Node:
>   def __init__(self, cargo=None, next=None):
> self.cargo = cargo
> self.next  = next

This is OK for the node itself, but maybe you should try writing a 
LinkedList class that you use:

class LinkedList(object):
def __init__(self):
self.head = None

def append(self, node):
...

def remove(self, node):
...

>>> ll = LinkedList()
>>> ll.append(Node(3490))

(For extra fun, make it so you can iterate over the linked list and 
call it like this:for n in ll: print n   :-) )

> >>> list=[]
> >>> list.append(Node(1))
> >>> list.append(Node(2))
> >>> list[0].next=list[1]
> >>> list.append(Node(3))
> >>> list[1].next=list[2]

I'd classify this as "not pretty".  Sure, it's more "dynamic" in that 
you don't have a variable to reference every node, but it's way 
cleaner to make an encapsulating LinkedList class, right?

In in Python, references to objects are very much like pointers in C:

>>> foo = Node(3490)  # foo is a reference to a Node instance
>>> bar = foo   # bar points to the same Node instance as foo
>>> foo
<__main__.Node object at 0xb7b362ec>
>>> bar
<__main__.Node object at 0xb7b362ec>

See?  They point to the name Node object.

> I think that my concept is wrong by using a list to create a list.

I agree with you, if your goal is to implement your own list.  Using 
the Python functionality just makes things less clear.

> Is
> it possible to manage the insertation of new object like in C by
> allocating new memory space.

Absolutely.  The "next" pointer thing is the way to go, so you're on 
the right track with that.

When deleting nodes from the list, you don't explicitly delete them; 
you just need to remove all your references to them.  Nodes will be 
garbage collected when there are no more references to them anywhere.

> any sugestions how to make the implementation more like in C. I never
> managed the syntax of C so I stoped when structs crossed my way.
> Please help. I dont want to learn C.

Ah, it's a pity.  C is my favorite compiled procedural language.

-Beej

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


Re: Can I undecorate a function?

2007-01-29 Thread Steve Holden
Matthew Wilson wrote:
> The decorator as_string returns the decorated function's value as
> string.  In some instances I want to access just the function f,
> though, and catch the values before they've been decorated.
> 
> Is this possible?
> 
> def as_string(f):
> def anon(*args, **kwargs):
> y = f(*args, **kwargs)
> return str(y)
> return anon
> 
> @as_string
> def f(x):
> return x * x
> 
It's much simpler not to use the decorator syntax if you also want 
access to the original function.

Simply declare f as a function, then assign decorator(f) to some other name.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: Python does not play well with others

2007-01-29 Thread Skip Montanaro

> Andy Dustman, the author of the package is quite responsive to requests
> raised in the mysql-python forums on SourceForge
> (http://sourceforge.net/forum/?group_id=22307).  If you have problems with
> MySQLdb, bring them up there.  I'm sure Andy will respond.

I apologize in advance for beating this dead horse...  This morning  a
possible bug was reported in MySQLdb.  Andy determined it was indeed a bug,
had a fix checked into the source repository in a couple hours and reported
that it would be in the next 1.2 beta release.

Skip


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


Re: Excellent Interview with Dennis D'Souza, full of laughs

2007-01-29 Thread Frank Arthur
Islamist bastard <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> FBI spook bastard  that speaks french also
>
> On Jan 29, 8:13 am, "Hampton Din" <[EMAIL PROTECTED]> wrote:
>>  stupid troll
>
> 


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


Re: Excellent Interview with Dennis D'Souza, full of laughs

2007-01-29 Thread Frank Arthur
Real funny? Holocaust Deniers Convention in Iran?

Sick, sick Islamists!

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> http://a1135.g.akamai.net/f/1135/18227/1h/cchannel.download.akamai.com/
> 18227/podcast/PORTLAND-OR/KPOJ-AM/1-23-07%20POJ-cast.mp3?


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


Re: Can I undecorate a function?

2007-01-29 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Matt> In some instances I want to access just the function f, though,
> Matt> and catch the values before they've been decorated.
> 
> def f(x):
> return x * x
> 
> @as_string
> def fs(x):
> return f(x)

or just
fs = as_string(f)

Kent

> 
> Call the one you want.
> 
> Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: next berlin python-group meeting fr., 2.2.

2007-01-29 Thread Stephan Diehl
Stephan Diehl wrote:

> http://starship.python.net/cgi-bin/mailman/listinfo/python-berlin

argghhh, wrong link. please try
http://starship.python.net/mailman/listinfo/python-berlin
-- 
http://mail.python.org/mailman/listinfo/python-list


next berlin python-group meeting fr., 2.2.

2007-01-29 Thread Stephan Diehl
after a long (veeeyy) long time, I'm pleased to announce our next 
python meeting in berlin.
time: friday 2.2. 7pm
place:Cafe & Restaurant UNENDLICH
Boetzowstrasse 14
10407 Berlin (Prenzlauer Berg "Boetzowviertel")

This is a fun meeting without offical talks.
If you haven't done so already, subscribe to
http://starship.python.net/cgi-bin/mailman/listinfo/python-berlin
for last minute information. If you plan to come, please leave a short 
notice there, so we know how many people to expect.

Cheers

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


Re: Can I undecorate a function?

2007-01-29 Thread Diez B. Roggisch
Matthew Wilson wrote:

> The decorator as_string returns the decorated function's value as
> string.  In some instances I want to access just the function f,
> though, and catch the values before they've been decorated.
> 
> Is this possible?
> 
> def as_string(f):
> def anon(*args, **kwargs):
> y = f(*args, **kwargs)
> return str(y)
> return anon
> 
> @as_string
> def f(x):
> return x * x

Untested:


def as_string(f):
def anon(*args, **kwargs):
y = f(*args, **kwargs)
return str(y)
andon.the_function = f
return anon


@as_string
def f(x):
   return x * x

print f.the_function(10)


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


Re: Can I undecorate a function?

2007-01-29 Thread skip
Matt> In some instances I want to access just the function f, though,
Matt> and catch the values before they've been decorated.

def f(x):
return x * x

@as_string
def fs(x):
return f(x)

Call the one you want.

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


Can I undecorate a function?

2007-01-29 Thread Matthew Wilson
The decorator as_string returns the decorated function's value as
string.  In some instances I want to access just the function f,
though, and catch the values before they've been decorated.

Is this possible?

def as_string(f):
def anon(*args, **kwargs):
y = f(*args, **kwargs)
return str(y)
return anon

@as_string
def f(x):
return x * x

Matt


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Possible security hole in SSL - was Random Passwords Generation

2007-01-29 Thread John Nagle
Paul Rubin wrote:
> "Szabolcs Nagy" <[EMAIL PROTECTED]> writes:
> 
>>file('/dev/urandom').read(6).encode('base64')
>>(oneliner and without import sa op requested)
> 
> 
> Nice, though Un*x dependent (os.urandom is supposed to be portable).

Uh oh.  I was looking at the Python "SSL" code recently, and
noted that OpenSSL initializes the keys with '/dev/urandom' if
available, and otherwise relies on the caller to seed it with
random data and to check that enough randomness has been input.

But the Python glue code for SSL doesn't seem to have the
machinery to seed SSL with randomness.  I suspect that on
platforms without '/dev/urandom', Python's SSL package may
be using the same keys every time.  This needs to be looked
at by a crypto expert.

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


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Szabolcs Nagy

> while
> 1:i=__import__;print''.join(i('random').choice(i('string').letters
> +'1234567890')for x in range(8)),;raw_input()
>

while 
1:i=__import__;r='random';print''.join(i(r).choice(i('string').letters
+'1234567890')for x in`r`),;raw_input()

even shorter:
range -> `'random'`

:)

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


Re: stop script w/o exiting interpreter

2007-01-29 Thread Garrick . Peterson
> I want, and the script will stop executing at that line and will
> return to the interactive interpreter, as I wish.

May I recommend wrapping your main program in a function definition? Such 
as:

main():
# Bulk of your code (use a macro to indent it faster)

if __name__ == "__main__":
main()

Then you should be able to throw in a "return" at any point and get a 
clean break, without affecting the flow of your program. This should make 
it easier to debug as well, offering a clean entry point from the python 
interactive session, and letting you return a specific value you wish to 
check.


Garrick M. Peterson
Quality Assurance Analyst
Zoot Enterprises, Inc.
[EMAIL PROTECTED]

Copyright © 2007 Zoot Enterprises, Inc. and its affiliates.  All rights 
reserved. This email, including any attachments, is confidential and may 
not be redistributed without permission. If you are not an intended 
recipient, you have received this message in error; please notify us 
immediately by replying to this message and deleting it from your 
computer. Thank you. -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Szabolcs Nagy
> If you really want a hack, here it is:
>
> while 1:print
> ''.join(__import__('random').choice(__import__('string').letters+'1234567890')
> for x in xrange(8)),;n=raw_input()
>
> This is a one-liner (though mail transmission may split it up), no
> import statements. If someone can come up with an even smaller version,
> feel free to post. :)

while 
1:i=__import__;print''.join(i('random').choice(i('string').letters
+'1234567890')for x in range(8)),;raw_input()

same but shorter:
i = __import__;
xrange -> range (why use xrange? range is faster and simpler for small 
ranges)
n =(not needed)

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


  1   2   >