Re: Free software versus software idea patents

2011-04-11 Thread wisecracker
Hi harrismh777...

>> With enough software, you can simulate anything. That means that the
>> entire universe can be expressed as lambda calculus. Does that mean
>> that nothing can ever be patented, because it's all just mathematics?

> Great question... the simple answer is, no. But the extended answer 
> is a little complicated and not well understood by most folks, so its 
> worth talking about, at least a lot. You may skip to the last paragraph 
> for the main point... or stay tuned for the explanation.

I`ve been reading this thread with interest...

Great reply, one of the best I`ve read on any ML/Forum I frequent...
Do I have your permission to quote your reply intact in threads where the 
patent, etc,
issues arise, and they often do on other sites.

TIA...



--
73...

Bazza, G0LCU...

Team AMIGA...

http://homepages.tesco.net/wisecracker/

http://main.aminet.net/search?readme=wisecracker

http://mikeos.berlios.de/

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


Re: Multiprocessing, shared memory vs. pickled copies

2011-04-11 Thread John Nagle

On 4/10/2011 3:29 PM, sturlamolden wrote:

On 10 apr, 18:27, John Nagle  wrote:


 Unless you have a performance problem, don't bother with shared
memory.

 If you have a performance problem, Python is probably the wrong
tool for the job anyway.


Then why does Python have a multiprocessing module?


Because nobody can fix the Global Interpreter Lock problem in CPython.

The multiprocessing module is a hack to get around the fact
that Python threads don't run concurrently, and thus, threaded
programs don't effectively use multi-core CPUs.

John Nagle

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


Re: [OT] Free software versus software idea patents

2011-04-11 Thread geremy condra
On Sun, Apr 10, 2011 at 7:49 PM, harrismh777  wrote:
> Chris Angelico wrote:
>>>
>>> >      All software can be expressed as lambda calculus. The point being,
>>> > all
>>> >  software is mathematics...
>
>> With enough software, you can simulate anything. That means that the
>> entire universe can be expressed as lambda calculus. Does that mean
>> that nothing can ever be patented, because it's all just mathematics?
>
>    Great question... the simple answer is, no. But the extended answer is a
> little complicated and not well understood by most folks, so its worth
> talking about, at least a lot. You may skip to the last paragraph for the
> main point... or stay tuned for the explanation.
>    Mathematical processes and algorithms are not patentable (by rule)
> because they are 'natural' and 'obvious'. In other words, a natural set of
> laws (mathematics, just one example) are universally used naturally and
> obviously by all humans in the course of thinking, creating, expressing,
> &etc., and therefore these ideas are not patentable because they are the
> natural and obvious 'stuff' from which and through which the human mind
> processes the natural world. You cannot patent the Pythagorean theorem. You
> cannot patent addition, nor subtraction, nor the logical concepts for
> boolean algebra nor can you patent lambda calculus. These are just
> examples.
>    You cannot patent the mathematical concept of nand gate; however,
> Motorola may patent the mechanical electrical implementation of the nand
> gate (CMOS 4011 quad nand). Also, Texas Instruments may patent their
> mechanical electrical implementation of the nand gate concept (TTL sn7400n
> quad chip). The chips are patentable, but the mathematical concept 'behind'
> the chips is not patentable.
>    Software is another sort of animal entirely. Because software is not just
> based on mathematics--- IT IS mathematics.

I am extremely skeptical of this argument. Leaving aside the fact that
you've randomly decided to drop the "decidable" qualifier here- a big
problem in its own right- it isn't clear to me that software and
computation are synonymous. Lambda calculus only models computation,
and software has real properties in implementation that are strictly
dependent on the physical world. Since perfectly predicting those
properties would seem to require that you perfectly model significant
portions of the physical universe, I think it's quite reasonable to
contend that the existence of lambda calculus no more rules out the
applicability of patents to software (which I detest) than it rules
out the applicability of patents to hardware (which I find only
slightly less ridiculous) or other meatspace inventions.

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


Re: Free software versus software idea patents

2011-04-11 Thread rusi
On Apr 11, 12:53 pm, geremy condra  wrote:
> On Sun, Apr 10, 2011 at 7:49 PM, harrismh777  wrote:
> > Chris Angelico wrote:
>
> >>> >      All software can be expressed as lambda calculus. The point being,
> >>> > all
> >>> >  software is mathematics...
>
> >> With enough software, you can simulate anything. That means that the
> >> entire universe can be expressed as lambda calculus. Does that mean
> >> that nothing can ever be patented, because it's all just mathematics?
>
> >    Great question... the simple answer is, no. But the extended answer is a
> > little complicated and not well understood by most folks, so its worth
> > talking about, at least a lot. You may skip to the last paragraph for the
> > main point... or stay tuned for the explanation.
> >    Mathematical processes and algorithms are not patentable (by rule)
> > because they are 'natural' and 'obvious'. In other words, a natural set of
> > laws (mathematics, just one example) are universally used naturally and
> > obviously by all humans in the course of thinking, creating, expressing,
> > &etc., and therefore these ideas are not patentable because they are the
> > natural and obvious 'stuff' from which and through which the human mind
> > processes the natural world. You cannot patent the Pythagorean theorem. You
> > cannot patent addition, nor subtraction, nor the logical concepts for
> > boolean algebra nor can you patent lambda calculus. These are just
> > examples.
> >    You cannot patent the mathematical concept of nand gate; however,
> > Motorola may patent the mechanical electrical implementation of the nand
> > gate (CMOS 4011 quad nand). Also, Texas Instruments may patent their
> > mechanical electrical implementation of the nand gate concept (TTL sn7400n
> > quad chip). The chips are patentable, but the mathematical concept 'behind'
> > the chips is not patentable.
> >    Software is another sort of animal entirely. Because software is not just
> > based on mathematics--- IT IS mathematics.
>
> I am extremely skeptical of this argument. Leaving aside the fact that
> you've randomly decided to drop the "decidable" qualifier here- a big
> problem in its own right- it isn't clear to me that software and
> computation are synonymous. Lambda calculus only models computation,
> and software has real properties in implementation that are strictly
> dependent on the physical world. Since perfectly predicting those
> properties would seem to require that you perfectly model significant
> portions of the physical universe, I think it's quite reasonable to
> contend that the existence of lambda calculus no more rules out the
> applicability of patents to software (which I detest) than it rules
> out the applicability of patents to hardware (which I find only
> slightly less ridiculous) or other meatspace inventions.
>
> Geremy Condra


-
... the widespread belief, incorrectly known as the Church-Turing
thesis, that no model of computation more expressive than Turing
machines can exist. Yet Turing's original thesis only refers to the
computation of functions and explicitly excludes other computational
paradigms such as interaction.

In this paper, we identify and analyze the historical reasons for this
widespread belief. Only by
accepting that it is false can we begin to properly investigate formal
models of interaction machines.
We conclude the paper by presenting one such model, Persistent Turing
Machines (PTMs). PTMs
capture sequential interaction, which is a limited form of
concurrency; they allow us to formulate
the Sequential Interaction Thesis, going beyond the expressiveness of
Turing machines and of the
Church-Turing thesis.

From
http://www.cse.uconn.edu/~dqg/papers/cie05.pdf

may be of interest (and also other papers of Peter Wegner questioning
the universality of Turing machines lambda calculus etc)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encoding problem when launching Python27 via DOS

2011-04-11 Thread Jean-Pierre M
Thanks a lot for this quick answer! It is very clear!

Ti better understand what the difference between encoding and decoding is I
found the following website: http://www.evanjones.ca/python-utf8.html

I change the program to (changes
are in bold):
*# -*- coding: utf8 -*- *(no more cp1252 the source file is directly in
unicode)
*#!/usr/bin/python*
*'''*
*Created on 27 déc. 2010*
*
*
*@author: jpmena*
*'''*
*from datetime import datetime*
*import locale*
*import codecs*
*import os,sys*
*
*
*class Log(object):*
*log=None*
*def __init__(self,log_path):*
*self.log_path=log_path*
*if(os.path.exists(self.log_path)):*
*os.remove(self.log_path)*
*#self.log=open(self.log_path,'a')*
*self.log=codecs.open(self.log_path, "a", 'utf-8')*
**
*def getInstance(log_path=None):*
*print "encodage systeme:"+sys.getdefaultencoding()*
*if Log.log is None:*
*if log_path is None:*
*log_path=os.path.join(os.getcwd(),'logParDefaut.log')*
*Log.log=Log(log_path)*
*return Log.log*
**
*getInstance=staticmethod(getInstance)*
**
*def p(self,msg):*
*aujour_dhui=datetime.now()*
*date_stamp=aujour_dhui.strftime("%d/%m/%y-%H:%M:%S")*
*print sys.getdefaultencoding()*
*unicode_str='%s : %s \n'  % (date_stamp,unicode(msg,'utf-8'))*
*#unicode_str=msg*
*self.log.write(unicode_str)*
*return unicode_str*
**
*def close(self):*
*self.log.flush()*
*self.log.close()*
*return self.log_path*
*
*
*if __name__ == '__main__':*
*l=Log.getInstance()*
*l.p("premier message de Log à accents")*
*Log.getInstance().p("second message de Log")*
*l.close()*

The DOS conole output is now:
*C:\Documents and Settings\jpmena\Mes
documents\VelocityRIF\VelocityTransforms>generationProgrammeSitePublicActuel.cmd
*
*Page de codes active : 1252*
*encodage systeme:ascii*
*ascii*
*encodage systeme:ascii*
*ascii*

And the Generated Log file showsnow the expected result:
*11/04/11-10:53:44 : premier message de Log à accents *
*11/04/11-10:53:44 : second message de Log*

Thanks.

If you have other links of interests about unicode encoding and decoding  in
Python. They are welcome

2011/4/10 MRAB 

> On 10/04/2011 13:22, Jean-Pierre M wrote:
> > I created a simple program which writes in a unicode files some french
> text with accents!
> [snip]
> This line:
>
>
>l.p("premier message de Log à accents")
>
> passes a bytestring to the method, and inside the method, this line:
>
>
>unicode_str=u'%s : %s \n'  %
> (date_stamp,msg.encode(self.charset_log,'replace'))
>
> it tries to encode the bytestring to Unicode.
>
> It's not possible to encode a bytestring, only a Unicode string, so
> Python tries to decode the bytestring using the fallback encoding
> (ASCII) and then encode the result.
>
> Unfortunately, the bytestring isn't ASCII (it contains accented
> characters), so it can't be decoded as ASCII, hence the exception.
>
> BTW, it's probably better to forget about cp1252, etc, and use UTF-8
> instead, and also to use Unicode wherever possible.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Free software versus software idea patents

2011-04-11 Thread Steven D'Aprano
On Mon, 11 Apr 2011 00:53:57 -0700, geremy condra wrote:

> On Sun, Apr 10, 2011 at 7:49 PM, harrismh777 
> wrote:
>> Chris Angelico wrote:

 >      All software can be expressed as lambda calculus. The point
 >      being,
 > all
 >  software is mathematics...
>>
>>> With enough software, you can simulate anything. That means that the
>>> entire universe can be expressed as lambda calculus. Does that mean
>>> that nothing can ever be patented, because it's all just mathematics?
>>
>>    Great question... the simple answer is, no. But the extended
>>    answer is a
>> little complicated and not well understood by most folks, so its worth
>> talking about, at least a lot. You may skip to the last paragraph for
>> the main point... or stay tuned for the explanation.
>>    Mathematical processes and algorithms are not patentable (by rule)
>> because they are 'natural' and 'obvious'. In other words, a natural set
>> of laws (mathematics, just one example) are universally used naturally
>> and obviously by all humans in the course of thinking, creating,
>> expressing, &etc., and therefore these ideas are not patentable because
>> they are the natural and obvious 'stuff' from which and through which
>> the human mind processes the natural world. You cannot patent the
>> Pythagorean theorem. You cannot patent addition, nor subtraction, nor
>> the logical concepts for boolean algebra nor can you patent lambda
>> calculus. These are just examples.
>>    You cannot patent the mathematical concept of nand gate; however,
>> Motorola may patent the mechanical electrical implementation of the
>> nand gate (CMOS 4011 quad nand). Also, Texas Instruments may patent
>> their mechanical electrical implementation of the nand gate concept
>> (TTL sn7400n quad chip). The chips are patentable, but the mathematical
>> concept 'behind' the chips is not patentable.
>>    Software is another sort of animal entirely. Because software is
>>    not just
>> based on mathematics--- IT IS mathematics.
> 
> I am extremely skeptical of this argument. Leaving aside the fact that
> you've randomly decided to drop the "decidable" qualifier here- a big
> problem in its own right- it isn't clear to me that software and
> computation are synonymous. Lambda calculus only models computation, and
> software has real properties in implementation that are strictly
> dependent on the physical world. Since perfectly predicting those
> properties would seem to require that you perfectly model significant
> portions of the physical universe, I think it's quite reasonable to
> contend that the existence of lambda calculus no more rules out the
> applicability of patents to software (which I detest) than it rules out
> the applicability of patents to hardware (which I find only slightly
> less ridiculous) or other meatspace inventions.

I agree with all of this: I too detest software patents, and find 
hardware patents problematic but pragmatic. But if there's a reason for 
accepting one and rejecting the other, it's far more subtle than the hand-
waving about mathematics. I believe that the reason falls more to 
*pragmatic* reasons than *philosophical* reasons: software patents act to 
discourage innovation, while hardware patents (arguably) act to encourage 
it. After all, encouraging innovation is what patents are for.

M Harris' argument fails right at the beginning:

"Mathematical processes and algorithms are not patentable (by rule) 
because they are 'natural' and 'obvious'."

It's not clear to me how the Banach-Tarski paradox can be described as 
'natural':

Using the axiom of choice on non-countable sets, you can prove 
that a solid sphere can be dissected into a finite number of 
pieces that can be reassembled to two solid spheres, each of 
same volume of the original. No more than nine pieces are needed.
... This is usually illustrated by observing that a pea can be 
cut up into finitely pieces and reassembled into the Earth.

http://www.cs.uwaterloo.ca/~alopez-o/math-faq/mathtext/node36.html


And I think anyone who knows the slightest bit of mathematics would be 
falling over laughing at the suggestion that it is 'obvious'.

Of course, some mathematics is obvious, or at least intuitive (although 
proving it rigorously can be remarkably difficult -- after 4000 years of 
maths, we still don't have an absolutely bullet-proof proof that 1+1=2). 
But describing mathematics as 'obvious' discounts the role of invention, 
human imagination, ingenuity and creativity in mathematics. There's 
nothing obvious about (say) asymmetric encryption, or solving NP-complete 
problems like the knapsack problem, to mention just two examples out of 
literally countless examples.[1]

If it were just a matter of joining the dots, there would be no unsolved 
problems, since Euler would have solved them all 200 years ago.[2]

Part of the patent problem is that the distinction between discovery of a 
fact (which should no

Do UART require data structure/format for serial communication?

2011-04-11 Thread VGNU Linux
Hi All,
I have two chips one understands Python and the other embedded C.I have
connected both chips using UART serial communication channel, however I have
no idea how data communication must be achieved between this 2 chips. As for
example send using C chip string "Hello Python" which python chip easily
understands and replies back a string "Hi C".
I am pretty new to embedded systems can anybody help me understand data
communication using UART.
Thank in advance.

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


Send Sms with Nokia Phone

2011-04-11 Thread Santhosh Kumar
Hi all,
 I try to implement a sms forwarding system. My aim is to when some
hits happen in database It should send a sms so I did some research with
gammu and gammu-smsd I did all the configuration and also test sms is
working fine when I give echo "hello world" /etc/gammu text +91xx this
is working fine for me. I followed the document for my requirement with
gammu-smsd but I didn't find the python programming for doing the sms if hit
in mysql database. Kindly please help me what should I do further by giving
me some demo or documentation it is not necessary I should only go with
gammu it can be anything but should be  with opensource.

Thanks in Advance,

With Regards,
Never Say No,
Santhosh V.Kumar
+919840411410
http://santhoshvkumar.110mb.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do UART require data structure/format for serial communication?

2011-04-11 Thread Jean-Michel Pichavant

VGNU Linux wrote:

Hi All,
I have two chips one understands Python and the other embedded C.I 
have connected both chips using UART serial communication channel, 
however I have no idea how data communication must be achieved between 
this 2 chips. As for example send using C chip string "Hello Python" 
which python chip easily understands and replies back a string "Hi C". 
I am pretty new to embedded systems can anybody help me understand 
data communication using UART.

Thank in advance.

VGNU

have a look at http://pyserial.sourceforge.net/

Most of the time, people write a CLI running on the chip. Commands 
(strings) are sent to the CLI through the UART, the interpreter then 
calls the appropriate function.



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


Help Amigos

2011-04-11 Thread Gabriel Novaes
Hello community

My name is Gabriel. I'am from Brazil. 27. I finished last year
Degree in Computer Engineering and I would go to the U.S.A
to learn the local language.
I wonder how is the market for developers, which
city ​​is best for this?
I program for 5 years PHP (MVC) and for the past four months I
working with Python and Django. Incidentally, I love it and work on it

Working on a site in Brazil claims, moreover, the largest site
latin america complaints. (ser for 'reclamação' in google.com.br).

I would like to review and help the community. I am very interested in
live in the USA.

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


Re: Help Amigos

2011-04-11 Thread Gabriel Novaes
On 11 abr, 09:01, Gabriel Novaes  wrote:
> Hello community
>
> My name is Gabriel. I'am from Brazil. 27. I finished last year
> Degree in Computer Engineering and I would go to the U.S.A
> to learn the local language.
> I wonder how is the market for developers, which
> city ​​is best for this?
> I program for 5 years PHP (MVC) and for the past four months I
> working with Python and Django. Incidentally, I love it and work on it
>
> Working on a site in Brazil claims, moreover, the largest site
> latin america complaints. (ser for 'reclamação' in google.com.br).
>
> I would like to review and help the community. I am very interested in
> live in the USA.
>
> Even more.


Visit my site and to know my job. www.igrow.com.br
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving Python Keywords

2011-04-11 Thread Glazner
On Apr 10, 4:28 am, candide  wrote:
> Python is very good at introspection, so I was wondering if Python (2.7)
> provides any feature to retrieve the list of its keywords (and, as,
> assert, break, ...).

>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'with', 'yield']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Amigos

2011-04-11 Thread Jean-Michel Pichavant

Gabriel Novaes wrote:

Hello community

My name is Gabriel. I'am from Brazil. 27. I finished last year
Degree in Computer Engineering and I would go to the U.S.A
to learn the local language.
I wonder how is the market for developers, which
city ​​is best for this?
I program for 5 years PHP (MVC) and for the past four months I
working with Python and Django. Incidentally, I love it and work on it

Working on a site in Brazil claims, moreover, the largest site
latin america complaints. (ser for 'reclamação' in google.com.br).

I would like to review and help the community. I am very interested in
live in the USA.

Even more.
  

Hi,

You can start by having a look at http://www.python.org/community/jobs/.

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


Feature suggestion: math.zod for painlessly avoiding ZeroDivisionError

2011-04-11 Thread Natan Yellin
Hey everyone,
This is my first posting to python-list, so be gentle.

I propose the following function for the math module (which can, of course,
be rewritten in C):

>  zod = lambda a, b: b and a / b


zod, the zero or divide function, is useful for division where the
denominator can be 0. For example, here's one line of code

> stat = x / y


If y can be zero, that one-liner needs to be rewritten as:

> if y != 0:
> stat = x / y
> else:
> stat = 0

...which is 4 lines of code for simple division!


Using zod, the zero or divide function, we can write:

> stat = zod(x,y)


I've encountered this issue before, but I don't know how common it is. Let
me know!
Would you use zod? Or do you need ood (one or divide), in which case lets
forget this altogether!

Natan

--
blog: http://natanyellin.com
twitter: @aantn 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion: math.zod for painlessly avoiding ZeroDivisionError

2011-04-11 Thread Natan Yellin
On Mon, Apr 11, 2011 at 5:20 PM, Chris Angelico  wrote:

> On Tue, Apr 12, 2011 at 12:10 AM, Natan Yellin  wrote:
> > Hey everyone,
> > This is my first posting to python-list, so be gentle.
> > I propose the following function for the math module (which can, of
> course,
> > be rewritten in C):
> >>
> >>  zod = lambda a, b: b and a / b
> >
> > If y can be zero, that one-liner needs to be rewritten as:
> >>
> >> if y != 0:
> >> stat = x / y
> >> else:
> >> stat = 0
>
> You can optimize that the same way as your zod function:
> stat = y and x/y

I'm dealing with long-named variables inside of dictionaries, which makes
that impractical.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dump interpreter history?

2011-04-11 Thread Aahz
In article ,
Ken D'Ambrosio  wrote:
>
>Hey, all.  A co-worker asked me a question, and I've got no idea how (or
>if) it can be done.  Bottom line: he'd like to save off the text from an
>interpreter session, his thinking being that you've already tried to get
>what you want, and now you just need to gussy it up in an editor.

I've never used it myself, but IIRC ipython does what you want very
nicely.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-03-22
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dump interpreter history?

2011-04-11 Thread rusi
script
readline
ipython

all nice solutions...
There's one more (old) one: emacs

ie you can run python inside (under) emacs
That way you can pun thus: your interactions with python are a session
when you choose and a file when you choose (buffer in emacs-speak).

[Frank admission: The emacs python modes are multiple and in a (bit of
a) mess]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Free software versus software idea patents

2011-04-11 Thread Ian Kelly
On Sun, Apr 10, 2011 at 6:04 PM, harrismh777  wrote:
> The deal with motive number (2) is that there are fewer and fewer teams who
> are concerned with interoperability. For instance (my team), we moved our
> stuff to gnulinux based systems and dumped Microsoft completely... we have
> no need for them at all (they're dead). The Linux Foundation president made
> a splash the other day by saying that bashing Microsoft was like kicking a
> puppy (the server cloud war is over, and Microsoft lost... big). The desktop
> is all that is left... and that is dying... rapidly. Their lockin is well
> entrenched (like Borg implants ) but the number of mom & pops ( like my
> entire extended family, for instance) who are moving to Ubuntu (themselves)
> is astounding! It will not be long and Microsoft will die... and none too
> soon.

So what is that number?  Anecdotes are unreliable; I would like to see
the actual data.  The only non-techie I personally know who uses Linux
is my wife, and she only uses it because it's what's installed at
home.  My brother-in-law was a Linux fan at one time but has
regressed.

>    IE is dead. It is flat dead... almost nobody is using it... not even
> die-hard Windows gaming fanboys... we're on our way to freedom.

I'm sorry, but that is patently false.  Just look at the actual data:

http://www.getclicky.com/marketshare/global/web-browsers/
http://marketshare.hitslink.com/report.aspx?qprid=0&qptimeframe=M#
http://gs.statcounter.com/#browser-ww-monthly-201103-201103-bar
http://www.w3counter.com/globalstats.php?year=2011&month=3

Depending on the source, IE's market share is anywhere from 39% to
56%, and all of those sources list it higher than Firefox or any other
single browser.  To say "IE is dead" is either prevarication or
unsubstantiated wishful thinking.

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


Re: Feature suggestion: math.zod for painlessly avoiding ZeroDivisionError

2011-04-11 Thread Terry Reedy

On 4/11/2011 10:10 AM, Natan Yellin wrote:

Hey everyone,
This is my first posting to python-list, so be gentle.

I propose the following function for the math module (which can, of
course, be rewritten in C):

  zod = lambda a, b: b and a / b


This is way too trivial to add.


zod, the zero or divide function, is useful for division where the
denominator can be 0. For example, here's one line of code
stat = x / y
If y can be zero, that one-liner needs to be rewritten as:
if y != 0:
 stat = x / y
else:
 stat = 0


No. 'stat = y and x/y', which will be faster than 'stat = zod(x,y)', 
which does the same thing but adds a function call/


--
Terry Jan Reedy

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


Re: [OT] Free software versus software idea patents

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 3:26 AM, Ian Kelly  wrote:
> So what is that number?  Anecdotes are unreliable; I would like to see
> the actual data.  The only non-techie I personally know who uses Linux
> is my wife, and she only uses it because it's what's installed at
> home.  My brother-in-law was a Linux fan at one time but has
> regressed.

The company where I work used to be a Windows shop exclusively, but
now we're migrating more and more to Linux. All my devo is now Linux,
and my boss is encouraging my coworkers to do the same. That's still
anecdotal data though.

We use Linux for technological reasons more than anything else.
Windows doesn't give us the power of iptables, for instance.

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


Re: Dump interpreter history?

2011-04-11 Thread Terry Reedy

On 4/11/2011 11:54 AM, Aahz wrote:

In article,
Ken D'Ambrosio  wrote:


Hey, all.  A co-worker asked me a question, and I've got no idea how (or
if) it can be done.  Bottom line: he'd like to save off the text from an
interpreter session, his thinking being that you've already tried to get
what you want, and now you just need to gussy it up in an editor.


I've never used it myself, but IIRC ipython does what you want very
nicely.


Idle will save the contents of the shell window, including opening slash 
line and prompts.


--
Terry Jan Reedy

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


Re: Do UART require data structure/format for serial communication?

2011-04-11 Thread John Nagle

On 4/11/2011 4:57 AM, Jean-Michel Pichavant wrote:

VGNU Linux wrote:

Hi All,
I have two chips one understands Python and the other embedded C.I
have connected both chips using UART serial communication channel,
however I have no idea how data communication must be achieved between
this 2 chips. As for example send using C chip string "Hello Python"
which python chip easily understands and replies back a string "Hi C".
I am pretty new to embedded systems can anybody help me understand
data communication using UART.
Thank in advance.


What do you want to do?

There are many serial protocols.  At the low end, you can
send text. At the high end, you can send TCP over PPP.
The Arduno crowd has some protocols of their own.  See
"http://www.arduino.cc/en/Reference/Libraries";.

Any useful protocol must be able to deal with errors
on the link, either end restarting, and the other end failing
to respond.  All those things happen frequently with serial
ports.

What do you want to do?

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


Re: [OT] Free software versus software idea patents

2011-04-11 Thread geremy condra
On Mon, Apr 11, 2011 at 2:10 AM, Steven D'Aprano
 wrote:
> On Mon, 11 Apr 2011 00:53:57 -0700, geremy condra wrote:



>> I am extremely skeptical of this argument. Leaving aside the fact that
>> you've randomly decided to drop the "decidable" qualifier here- a big
>> problem in its own right- it isn't clear to me that software and
>> computation are synonymous. Lambda calculus only models computation, and
>> software has real properties in implementation that are strictly
>> dependent on the physical world. Since perfectly predicting those
>> properties would seem to require that you perfectly model significant
>> portions of the physical universe, I think it's quite reasonable to
>> contend that the existence of lambda calculus no more rules out the
>> applicability of patents to software (which I detest) than it rules out
>> the applicability of patents to hardware (which I find only slightly
>> less ridiculous) or other meatspace inventions.
>
> I agree with all of this: I too detest software patents, and find
> hardware patents problematic but pragmatic. But if there's a reason for
> accepting one and rejecting the other, it's far more subtle than the hand-
> waving about mathematics. I believe that the reason falls more to
> *pragmatic* reasons than *philosophical* reasons: software patents act to
> discourage innovation, while hardware patents (arguably) act to encourage
> it. After all, encouraging innovation is what patents are for.
>
> M Harris' argument fails right at the beginning:
>
> "Mathematical processes and algorithms are not patentable (by rule)
> because they are 'natural' and 'obvious'."
>
> It's not clear to me how the Banach-Tarski paradox can be described as
> 'natural':
>
>    Using the axiom of choice on non-countable sets, you can prove
>    that a solid sphere can be dissected into a finite number of
>    pieces that can be reassembled to two solid spheres, each of
>    same volume of the original. No more than nine pieces are needed.
>    ... This is usually illustrated by observing that a pea can be
>    cut up into finitely pieces and reassembled into the Earth.
>
>    http://www.cs.uwaterloo.ca/~alopez-o/math-faq/mathtext/node36.html
>
>
> And I think anyone who knows the slightest bit of mathematics would be
> falling over laughing at the suggestion that it is 'obvious'.

I'd quibble with you over terminology here. BTP arises naturally- ie,
without being explicitly constructed- in certain axiomatic systems.
But I get your point.

> Of course, some mathematics is obvious, or at least intuitive (although
> proving it rigorously can be remarkably difficult -- after 4000 years of
> maths, we still don't have an absolutely bullet-proof proof that 1+1=2).

Erm. This is getting a bit far afield, but yes, we do. The statement
you provide above part of Presbuger arithmetic, which is both complete
and decidable.

> But describing mathematics as 'obvious' discounts the role of invention,
> human imagination, ingenuity and creativity in mathematics. There's
> nothing obvious about (say) asymmetric encryption, or solving NP-complete
> problems like the knapsack problem, to mention just two examples out of
> literally countless examples.[1]

Meh. Obvious is in the eye of the beholder, and I doubt we'll wind up
coming up with a satisfying and rigorous definition here. I'd
therefore rest on the concept of 'natural' I outlined earlier, which
would clearly forbid patenting the product of discovery but allow
patenting inventions.

> If it were just a matter of joining the dots, there would be no unsolved
> problems, since Euler would have solved them all 200 years ago.[2]
>
> Part of the patent problem is that the distinction between discovery of a
> fact (which should not be patentable) and invention (which, at least
> sometimes, should be patentable) is not clear. The iPod existed as a
> Platonic ideal in some mathematical bazillion-dimensional abstract design
> space long before it was invented by Apple; does that make it a discovery
> rather than an invention? On the other hand, it is doing Apple a great
> disservice to ignore their creativity in finding that design point, out
> of the infinite number of almost-iPods that suck[3] or don't work.

I agree. Of course, your post existed as a billion-point platonic
ideal beforehand, so you can't really claim credit (man, Plato figured
*everything* out!), but still.

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


Re: Multiprocessing, shared memory vs. pickled copies

2011-04-11 Thread sturlamolden
On 11 apr, 09:21, John Nagle  wrote:

>      Because nobody can fix the Global Interpreter Lock problem in CPython.
>
>      The multiprocessing module is a hack to get around the fact
> that Python threads don't run concurrently, and thus, threaded
> programs don't effectively use multi-core CPUs.

Then why not let NumPy use shared memory in this case? It is as simple
as this:

import numpy as np
import sharedmem as sm
private_array = np.zeros((10,10))
shared_array  = sm.zeros((10,10))

I.e. the code is identical (more or less).

Also, do you think shared memory has other uses besides parallel
computing, such as IPC? It is e.g. an easy way to share data between
Python and an external program. Do you e.g. need to share (not send)
large amounts of data between Python and Java or Matlab?

The difference here from multiprocessing.Array is that IPC with
multiprocessing.Queue will actually work, because I am not using
anonymous shared memory. Instead of inherting handles, the segment has
a name in the file system, which means it can be memory mapped from
anywhere.

I posted the code to the NumPy mailing list yesterday.

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


Re: Multiprocessing, shared memory vs. pickled copies

2011-04-11 Thread sturlamolden
On 11 apr, 21:11, sturlamolden  wrote:

> import numpy as np
> import sharedmem as sm
> private_array = np.zeros((10,10))
> shared_array  = sm.zeros((10,10))

I am also using this to implement synchronization primitives (barrier,
lock, semaphore, event) that can be sent over an instance of
multiprocessing.Queue. The synchronization primitives in
multiprocessing cannot be communicated this way.

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


[Feature Request] dict.setdefault()

2011-04-11 Thread rantingrick

setdefault should take **kw args in the case of needing to set
multiple defaults at one time. I would even settle for an *arg list if
i had to. Anything is better than...

d.setdefault(blah, blah)
d.setdefault(blah, blah)
d.setdefault(blah, blah)
d.setdefault(blah, blah)
if blah is not blah:
d.setdefault(blah, blah)

...nuff said.

PS: And to counter the very *extemely* likely chance of some smart
arse responses
  * YES, i know i could create my own setdefault method but that is
not the point.
  * I know we are under the moratorium but someone had to mention it,

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


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread Westley Martínez
On Mon, 2011-04-11 at 14:35 -0700, rantingrick wrote:
> setdefault should take **kw args in the case of needing to set
> multiple defaults at one time. I would even settle for an *arg list if
> i had to. Anything is better than...
> 
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> if blah is not blah:
> d.setdefault(blah, blah)
> 
> ...nuff said.
> 
> PS: And to counter the very *extemely* likely chance of some smart
> arse responses
>   * YES, i know i could create my own setdefault method but that is
> not the point.
>   * I know we are under the moratorium but someone had to mention it,
> 
> --rr

Go to bugs.python.org

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


Re: Dump interpreter history?

2011-04-11 Thread John Gordon
In  Tim Chase 
 writes:

> > import readline
> > readline.write_history_file([filename])

> Just to clarify (I thought Daniel's answer was so easy it must 
> have misinterpreted the OP's request), that's a single string as 
> a filename, not a list containing a filename.  I tried

In most documentation, square brackets indicate that the enclosed item is
optional; the brackets are not meant to be used literally.

Therefore, this text:

  readline.write_history_file([filename])

says "You can call write_history_file() with no arguments at all, or
with one argument which is the name of the file to be written."

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: [OT] Free software versus software idea patents

2011-04-11 Thread Steven D'Aprano
On Mon, 11 Apr 2011 11:17:09 -0700, geremy condra wrote:

> On Mon, Apr 11, 2011 at 2:10 AM, Steven D'Aprano
>  wrote:
[...]
>> Of course, some mathematics is obvious, or at least intuitive (although
>> proving it rigorously can be remarkably difficult -- after 4000 years
>> of maths, we still don't have an absolutely bullet-proof proof that
>> 1+1=2).
> 
> Erm. This is getting a bit far afield, but yes, we do. The statement you
> provide above part of Presbuger arithmetic, which is both complete and
> decidable.

Ah, I didn't know that! How wonderful! But in any case, Presburger 
arithmetic is much weaker than even Peano arithmetic.

http://en.wikipedia.org/wiki/Presburger_arithmetic

So, let me re-phrase my statement... in any realistically complex 
arithmetic that is consistent with operations performed for real-world 
applications (e.g. multiplication, division, exponentiation, ...), one 
cannot demonstrate a bullet-proof proof of 1+1=2. Better? :)

Presburger arithmetic, Peano arithmetic, the Axiom of Choice... we're 
getting further and further away from "natural" mathematics, e.g. 
counting sheep in a field.


[...]
>> Part of the patent problem is that the distinction between discovery of
>> a fact (which should not be patentable) and invention (which, at least
>> sometimes, should be patentable) is not clear. The iPod existed as a
>> Platonic ideal in some mathematical bazillion-dimensional abstract
>> design space long before it was invented by Apple; does that make it a
>> discovery rather than an invention? On the other hand, it is doing
>> Apple a great disservice to ignore their creativity in finding that
>> design point, out of the infinite number of almost-iPods that suck[3]
>> or don't work.
> 
> I agree. Of course, your post existed as a billion-point platonic ideal
> beforehand, so you can't really claim credit (man, Plato figured
> *everything* out!), but still.

Damn Library of Babel, it has *everything* in it.


Anyway, this is now getting off-topic even for the original off-topic 
post. Time to move on, methinks.


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


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread MRAB

On 11/04/2011 23:16, Westley Martínez wrote:

On Mon, 2011-04-11 at 14:35 -0700, rantingrick wrote:

setdefault should take **kw args in the case of needing to set
multiple defaults at one time. I would even settle for an *arg list if
i had to. Anything is better than...

d.setdefault(blah, blah)
d.setdefault(blah, blah)
d.setdefault(blah, blah)
d.setdefault(blah, blah)
if blah is not blah:
 d.setdefault(blah, blah)

...nuff said.

PS: And to counter the very *extemely* likely chance of some smart
arse responses
   * YES, i know i could create my own setdefault method but that is
not the point.
   * I know we are under the moratorium but someone had to mention it,

--rr


Go to bugs.python.org


I'm not sure that "setdefault" should take **kw args for this because
of its existing argument structure (key + optional value).

A new method like "updatedefault" may be better, IMHO. It would act
like "update" except that it wouldn't overwrite existing values.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 8:41 AM, MRAB  wrote:
> I'm not sure that "setdefault" should take **kw args for this because
> of its existing argument structure (key + optional value).
>
> A new method like "updatedefault" may be better, IMHO. It would act
> like "update" except that it wouldn't overwrite existing values.

Wouldn't x.updatedefault(y) be pretty much y.update(x) ?

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


Re: Argument of the bool function

2011-04-11 Thread Ethan Furman

Mel wrote:

Python is a pragmatic language, so all the rules come pre-broken.


+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict.setdefault()

2011-04-11 Thread Raymond Hettinger
On Apr 11, 2:35 pm, rantingrick  wrote:
> setdefault should take **kw args in the case of needing to set
> multiple defaults at one time. I would even settle for an *arg list if
> i had to. Anything is better than...
>
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> if blah is not blah:
>     d.setdefault(blah, blah)

I hate to feed a troll, but I'm curious when you see that pattern of
calls.  The typical use case always makes immediate use of the value
returned by setdefault():

   d.setdefault(key, []).append()

The pattern you've shown would more typically be expressed like this:

   for key in multiple_defaults.items():
   if key, default_value not in d:
   d[key] = default_value

Or people sometimes use updates to get the same effect:

   result = multiple_defaults.copy()
   result.update(d)

Another approach is to use something like ChainMap() which has been
added to Python 3.3. 
http://docs.python.org/dev/library/collections.html#collections.ChainMap

   result = ChainMap(d, multiple_defaults)


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


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread Chris Rebert
On Mon, Apr 11, 2011 at 2:35 PM, rantingrick  wrote:
>
> setdefault should take **kw args in the case of needing to set
> multiple defaults at one time. I would even settle for an *arg list if
> i had to.

What would the return value be? dict.setdefault() doesn't currently
just return None you know.

> Anything is better than...
>
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> if blah is not blah:
>    d.setdefault(blah, blah)

The redundancy is easily removed:
defaults = {blah: blah, blah: blah, blah: blah, blah: blah}
defaults.update(d) # clobber defaults with specified vals
d = defaults # swap in, assuming not aliased
# if aliased, then instead:
# d.clear()
# d.update(defaults)
if blah is not blah:
d.setdefault(blah, blah)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Free software versus software idea patents

2011-04-11 Thread geremy condra
On Mon, Apr 11, 2011 at 3:28 PM, Steven D'Aprano
 wrote:
> On Mon, 11 Apr 2011 11:17:09 -0700, geremy condra wrote:
>
>> On Mon, Apr 11, 2011 at 2:10 AM, Steven D'Aprano
>>  wrote:
> [...]
>>> Of course, some mathematics is obvious, or at least intuitive (although
>>> proving it rigorously can be remarkably difficult -- after 4000 years
>>> of maths, we still don't have an absolutely bullet-proof proof that
>>> 1+1=2).
>>
>> Erm. This is getting a bit far afield, but yes, we do. The statement you
>> provide above part of Presbuger arithmetic, which is both complete and
>> decidable.
>
> Ah, I didn't know that! How wonderful! But in any case, Presburger
> arithmetic is much weaker than even Peano arithmetic.
>
> http://en.wikipedia.org/wiki/Presburger_arithmetic
>
> So, let me re-phrase my statement... in any realistically complex
> arithmetic that is consistent with operations performed for real-world
> applications (e.g. multiplication, division, exponentiation, ...), one
> cannot demonstrate a bullet-proof proof of 1+1=2. Better? :)

Well, Peano arithmetic is normal, everyday arithmetic fully
axiomatized, and Presburger arithmetic is a subset of it, so we can
utilize the fact that 1 + 1 = 2 is provable in Presburger arithmetic
(damn is my spell checker getting a workout on this sentence) to prove
it in Peano arithmetic, and therefore in everyday use.

You'd also be surprised what you can do with some limited arithmetic
forms. During my undergrad I spent some time writing a Presburger
prover that was actually fairly handy- there are definitely instances
where trading multiplication by non-constant factors for provability
superpowers is a good deal.

> Presburger arithmetic, Peano arithmetic, the Axiom of Choice... we're
> getting further and further away from "natural" mathematics, e.g.
> counting sheep in a field.

Yes, the sheep would much rather hear about patent reform than the
axiom of choice ;)



> Anyway, this is now getting off-topic even for the original off-topic
> post. Time to move on, methinks.

Yeah, looks like a good time to let this one trail off.

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


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread MRAB

On 11/04/2011 23:44, Chris Angelico wrote:

On Tue, Apr 12, 2011 at 8:41 AM, MRAB  wrote:

I'm not sure that "setdefault" should take **kw args for this because
of its existing argument structure (key + optional value).

A new method like "updatedefault" may be better, IMHO. It would act
like "update" except that it wouldn't overwrite existing values.


Wouldn't x.updatedefault(y) be pretty much y.update(x) ?


I suppose it would, except that it wouldn't be in-place as such, and it
wouldn't be as efficient if you're wanting to default only a few
entries in a larger dict.
--
http://mail.python.org/mailman/listinfo/python-list


Feature suggestion -- return if true

2011-04-11 Thread zildjohn01
This is an idea I've had bouncing around in my head for a long time
now. I propose the following syntax:

return? expr

be expanded to

_temp = expr
if _temp: return _temp

It's a pattern I use all the time in my code, and although it's a bit
unorthodox, IMO it's concise, readable, and easily understandable.

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


Re: [OT] Free software versus software idea patents

2011-04-11 Thread Ben Finney
geremy condra  writes:

> […] I think it's quite reasonable to contend that the existence of
> lambda calculus no more rules out the applicability of patents to
> software (which I detest) than it rules out the applicability of
> patents to hardware (which I find only slightly less ridiculous) or
> other meatspace inventions.

That matches my own position on the topic.

Further, most software idea patents are worded so that they give lip
service to the theory that pure algorithms can't be patented; they tie
the patent to “A machine for computation plus [insert broad obfuscated
description of algorithm here]”. Yessir, this is an amazing invention of
ours to turn this general-purpose computer into a machine that does what
we want it to do. Patenting ideas? You must be thinking of someone else.

So, even if the theory of non-patentable algorithms were to stand up in
most jurisdictions, it doesn't have any force against the software idea
patents that are actually problematic.

-- 
 \   “Give a man a fish, and you'll feed him for a day; give him a |
  `\religion, and he'll starve to death while praying for a fish.” |
_o__)   —Anonymous |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Feature Request] dict.setdefault()

2011-04-11 Thread Tim Chase

On 04/11/2011 05:44 PM, Chris Angelico wrote:

On Tue, Apr 12, 2011 at 8:41 AM, MRAB  wrote:

I'm not sure that "setdefault" should take **kw args for this because
of its existing argument structure (key + optional value).

A new method like "updatedefault" may be better, IMHO. It would act
like "update" except that it wouldn't overwrite existing values.


Wouldn't x.updatedefault(y) be pretty much y.update(x) ?


As I understand, the difference would be the following pseudocode:

 def update(self, d):
   for k,v in dict(d).iteritems():
 self[k] = v

 def updatedefault(self, d={}, **kwargs):
   for k,v in chain(
  dict(d).iteritems(),
  kwargs.iteritems()
  ):
 # MRAB's comment about "wouldn't overwrite existing"
 if k not in self:
   self[k] = v

My concern with the initial request is that dict.setdefault() 
already returns the (existent or defaulted) value, so you can do 
things like


  d.setdefault(my_key, []).append(item)

If you allow it to take multiple kwargs, what would the return 
value be (positionality of kwargs is lost, so returning a tuple 
wouldn't be readily possible)?


Finally, if it were added, I'd call it something like merge()

-tkc




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


Announcing pyOpenSSL 0.12

2011-04-11 Thread exarkun

Exciting news everyone,

I have just released pyOpenSSL 0.12.  pyOpenSSL provides Python bindings 
to a number of OpenSSL APIs, including certificates, public and private 
keys, and of course running TLS (SSL) over sockets or arbitrary in- 
memory buffiers.


This release fixes an incompatibility with Python 2.7 involving 
memoryviews.  It also exposes the "info callback" constants used to 
report progress of the TLS handshake and later steps of SSL connections. 
Perhaps most interestingly, it also adds support for inspecting 
arbitrary X509 extensions.


http://python.org/pypi/pyOpenSSL - check it out.

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


Re: dict.setdefault()

2011-04-11 Thread Raymond Hettinger
On Apr 11, 4:25 pm, Tim Chase  wrote:
> Finally, if it were added, I'd call it something like merge()

Guido rejected merge() a long time ago.

Anyway, there is a new ChainMap() tool in the collections module for
Py3.3 that should address a number of use cases for handling default
values.


Raymond

twitter: @raymondh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 9:17 AM, zildjohn01  wrote:
> This is an idea I've had bouncing around in my head for a long time
> now. I propose the following syntax:

Maybe this is more appropriare for the python-ideas list ?

>    return? expr

This syntax does not fit well within python ideology.

> be expanded to
>
>    _temp = expr
>    if _temp: return _temp

This could be simplified to just:

return expr or None

And more to the point... If your calee is relying
on the result of this function, just returning the
evaluation of "expr" is enough.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 10:27 AM, James Mills
 wrote:
> This could be simplified to just:
>
> return expr or None
>
> And more to the point... If your calee is relying
> on the result of this function, just returning the
> evaluation of "expr" is enough.

I'm thinking here that that's not a solution; he'll have more code to
follow. An example of what I think he's trying to do:

def fac(n):
# attempt to get from a cache
return? cache[n]
# not in cache, calculate the value
ret=1 if n<=1 else fac(n-1)*n
# and cache and return it
cache[n]=ret; return ret

If the rest of the function can be implemented as an expression, it
might be possible to use:

return expr or other_expr

But in the example of a lookup cache, that wouldn't work so easily -
assignment isn't an expression. If 'x=y' had a value as it does in C,
the above function could become:

def fac(n):
return cache[n] or (cache[n]=1 if n<=1 else fac(n-1)*n)

which is a reasonable one-liner, albeit not the most efficient
factorial implementation. Is there a simple and Pythonic way to do
this?

BTW, assume for the purposes of discussion that the return? expr is a
complex one, such that it's well worth evaluating only once (maybe
even has side effects).

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


Re: Feature suggestion -- return if true

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 10:46 AM, Chris Angelico  wrote:
> def fac(n):
>    return cache[n] or (cache[n]=1 if n<=1 else fac(n-1)*n)

Hmm. The function-call version of dictionary assignment IS legal in an
expression, but it's getting stupid...

def fac(n):
return cache.get(n) or (cache.__setitem__(n,1 if n<=1 else
fac(n-1)*n) or cache[n])

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


Re: Feature suggestion -- return if true

2011-04-11 Thread Grant Edwards
On 2011-04-12, James Mills  wrote:
> On Tue, Apr 12, 2011 at 9:17 AM, zildjohn01  wrote:
>> This is an idea I've had bouncing around in my head for a long time
>> now. I propose the following syntax:
>
> Maybe this is more appropriare for the python-ideas list ?
>
>> ?? ??return? expr
>
> This syntax does not fit well within python ideology.
>
>> be expanded to
>>
>> ?? ??_temp = expr
>> ?? ??if _temp: return _temp
>
> This could be simplified to just:
>
> return expr or None

How is that the same?

  return? something()  return something() or None
  return? somethingelse()  return somethingelse() or None
  log("didn't find an answer") log("didn't find an answer") 
  raise ValueError raise ValueError

Are you saying the two snippets above are equivalent?

-- 
Grant


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


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 11:44 AM, Grant Edwards  wrote:
> How is that the same?
>
>  return? something()                  return something() or None
>  return? somethingelse()              return somethingelse() or None
>  log("didn't find an answer")         log("didn't find an answer")
>  raise ValueError                     raise ValueError
>
> Are you saying the two snippets above are equivalent?

def foo(n):
x = n < 5
if x:
return x

is functionally equivalent to:

def foo(n):
return n < 5

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Jason Swails
On Mon, Apr 11, 2011 at 7:12 PM, James Mills
wrote:

>
> > Are you saying the two snippets above are equivalent?
>
> def foo(n):
>x = n < 5
>if x:
>return x
>
> is functionally equivalent to:
>
> def foo(n):
>return n < 5
>
>
This is only true if n < 5.  Otherwise, the first returns None and the
second returns False.

>>> def foo(n):
... x = n < 5
... if x: return x
...
>>> def foo1(n):
... return n < 5
...
>>> foo(4)
True
>>> foo1(4)
True
>>> foo(6)
>>> foo1(6)
False
>>>

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


Re: Feature suggestion -- return if true

2011-04-11 Thread Grant Edwards
On 2011-04-12, James Mills  wrote:
> On Tue, Apr 12, 2011 at 11:44 AM, Grant Edwards  
> wrote:
>> How is that the same?
>>
>> ??return? something() ?? ?? ?? ?? ?? ?? ?? ?? ??return something() or None
>> ??return? somethingelse() ?? ?? ?? ?? ?? ?? ??return somethingelse() or None
>> ??log("didn't find an answer") ?? ?? ?? ?? log("didn't find an answer")
>> ??raise ValueError ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? raise ValueError
>>
>> Are you saying the two snippets above are equivalent?
>
> def foo(n):
> x = n < 5
> if x:
> return x
>
> is functionally equivalent to:
>
> def foo(n):
> return n < 5

That's not what I asked.

You stated that

  return? 

was equivalent to

  return  or None

If that was the case then the two code snippets _I_ posted should be
equivalent:

  return? something()   return something() or None
  return? somethingelse()   return somethingelse() or None
  log("didn't find an answer")  log("didn't find an answer")
  raise ValueError  raise ValueError

If the two snipped above are not equivalent, then

  return? 

is isn't equivalent to

  return  or None

-- 
Grant


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


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 12:18 PM, Jason Swails  wrote:
> This is only true if n < 5.  Otherwise, the first returns None and the
> second returns False.

Which is why I said:

return expr or None

But hey let's argue the point to death!

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Zero Piraeus
:

>> This is only true if n < 5.  Otherwise, the first returns None and the
>> second returns False.
>
> Which is why I said:
>
> return expr or None
>
> But hey let's argue the point to death!

Ok ;-)

I think the point is that OP doesn't want to return *at all* if expr
is False - presumably because there are further statements after the
proposed 'conditional' return.

Anyway,

  return? expr

isn't very pythonic - so how about one of these?

  return expr if True
  return expr else continue

I kid, I kid ...

 -[]z.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 12:20 PM, James Mills
 wrote:
> On Tue, Apr 12, 2011 at 12:18 PM, Jason Swails  wrote:
>> This is only true if n < 5.  Otherwise, the first returns None and the
>> second returns False.
>
> Which is why I said:
>
> return expr or None
>
> But hey let's argue the point to death!

That's still not equivalent. "return expr or None" will always
terminate the function. The OP's request was for something which would
terminate the function if and only if expr is non-false.

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


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 12:18 PM, Grant Edwards  wrote:
> You stated that
>
>  return? 
>
> was equivalent to
>
>  return  or None

This is _not_ what I said.

Quoting from my earlier post:

"""
>return? expr

This syntax does not fit well within python ideology.

> be expanded to
>
>_temp = expr
>if _temp: return _temp

This could be simplified to just:

return expr or None
"""

Please read carefully before putting words in my mouth.

I stated very clear y that return? expr didn't seem fitting
in the python ideology as syntax for this behavior.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Chris Angelico
On Tue, Apr 12, 2011 at 12:43 PM, Zero Piraeus  wrote:
>  return? expr
>
> isn't very pythonic - so how about one of these?
>
>  return expr if True
>  return expr else continue
>
> I kid, I kid ...

Or:

if expr:
  return it

Actually, I'm not sure how stupid an idea that is. Inside an if, 'it'
is the value of the condition. Might actually be useful in a few
places Naw, I think it's still a stupid idea.

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


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 12:43 PM, Zero Piraeus  wrote:
> I think the point is that OP doesn't want to return *at all* if expr
> is False - presumably because there are further statements after the
> proposed 'conditional' return.

If that's the case then we're all making assumptions
about what the OP intended. Perhaps OPs should be more
clear ? :)

kid!

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.setdefault()

2011-04-11 Thread rantingrick
On Apr 11, 5:41 pm, MRAB  wrote:

> A new method like "updatedefault" may be better, IMHO. It would act
> like "update" except that it wouldn't overwrite existing values.

That's sounds good MRAB! After you mentioned this i had an epiphany...
why not just add an extra argument to dict.update?

>>> dict.update(D, clobberexistingkeys=False)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 12:44 PM, Chris Angelico  wrote:
> That's still not equivalent. "return expr or None" will always
> terminate the function. The OP's request was for something which would
> terminate the function if and only if expr is non-false.

The OP did not state this at all.
There was never any mention of early termination
of the function iif expr was True.

Sorry :/ I'm not picking on your comprehension skills here
but you didn't read what the OP wrote (which he/she may not have
been clear about in the first place( nor what I said in reply.

Have a nice day,

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Literate Programming

2011-04-11 Thread Tim Arnold
"Hans Georg Schaathun"  wrote in message 
news:aca678-b87@svn.schaathun.net...
> On Fri, 8 Apr 2011 12:58:34 -0400, Tim Arnold
>   wrote:
> :  If you already know LaTeX, you might experiment with the *.dtx docstrip
> :  capability.
>
> Hi.  Hmmm.  That's a new thought.  I never thought of using docstrip
> with anything but LaTeX.  It sounds like a rather primitive tool for
> handling python code, and I would expect some serious trouble getting
> sensible highlighting in vim/eclim (or most other editors for that
> matter).  But I'll give it a thought.  Thanks.
>
> :  It has some pain points if you're developing from scratch, but I use it 
> once
> :  I've got a system in reasonable shape.
>
> Hmmm.  I wonder if I am every going to reach that stage :-)
>
> : You have full control over the
> :  display and you can make the code files go anywhere you like when you 
> run
> :  pdflatex on your file.
>
> If you use docstrip with python, what packages do you use to highlight
> code and markup programming concepts (methods/classes/variables)?
> If I may ask ...
>
> -- 
> :-- Hans Georg

I don't use anything special, just the verbatim environment is fine for my 
purposes.  But you might like the listings package which iirc has syntax 
highlighting built-in for python. ah, yes:
http://en.wikibooks.org/wiki/LaTeX/Packages/Listings

There's also the 'fancyvrb' package:
http://www.ctan.org/tex-archive/macros/latex/contrib/fancyvrb

good luck,
--Tim


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


Help with regex needed

2011-04-11 Thread Yuri Slobodyanyuk
Good day everyone,
I am trying to make this pretty simple regex to work but got stuck,
I'd appreciate your help .
Task: Get current date , then read file of format below, find the line that
matches
the current date of month,month and year and extract the number from such
line.
Here is what I did , but if i run it at 11 April 2011 ...
   - regex pattern_match  matches nothing
   - regex pattern_test  matches the line "4141411 Fri 11 11 2011" , logical
as it is the last matching line in year 2011 with the date of 11th.
My question - why regex pattern_match  does not match anything and how to
make it match the exact line i want.
Thanks
Yuri

from datetime import datetime, date, time
import re
today_day = datetime.now()
time_tuple= today_day.timetuple()
pattern_match = re.compile("([0-9])+ +" +  "Fri +" + str(time_tuple[1]) + "
+"  +   str(time_tuple[2]) + " +"  +  str(time_tuple[0]) + " +")
hhh = open("file_with_data.data",'r')
pattern_test =  re.compile("([0-9]+)" + ".*"  + " +" +
str(time_tuple[2]).strip(' \t\n\r') + " +"  + str(time_tuple[0]).strip('
\t\n\r') )
for nnn in hhh:
if  (re.search(pattern_test,nnn)):
   print nnn.split()[0]

111 Fri 4  8 2011
2323232 Fri 4 15 2011
4343434 Fri 4 22 2011
8522298 Fri 4 29 2011
.
5456678 Fri 10 28 2011
563 Fri 11  4 2011
4141411 Fri 11 11 2011
332 Fri 11 18 2011

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


Re: Help with regex needed

2011-04-11 Thread Kushal Kumaran
On Tue, Apr 12, 2011 at 10:50 AM, Yuri Slobodyanyuk
 wrote:
> Good day everyone,
> I am trying to make this pretty simple regex to work but got stuck,
> I'd appreciate your help .
> Task: Get current date , then read file of format below, find the line that
> matches
> the current date of month,month and year and extract the number from such
> line.
> Here is what I did , but if i run it at 11 April 2011 ...
>    - regex pattern_match  matches nothing
>    - regex pattern_test  matches the line "4141411 Fri 11 11 2011" , logical
> as it is the last matching line in year 2011 with the date of 11th.
> My question - why regex pattern_match  does not match anything and how to
> make it match the exact line i want.
> Thanks
> Yuri

Consider using datetime.strptime to parse dates and times.  You will
have to strip off the first column since it doesn't look like part of
the date itself.

>
> from datetime import datetime, date, time
> import re
> today_day = datetime.now()
> time_tuple= today_day.timetuple()
> pattern_match = re.compile("([0-9])+ +" +  "Fri +" + str(time_tuple[1]) + "
> +"  +   str(time_tuple[2]) + " +"  +  str(time_tuple[0]) + " +")
> hhh = open("file_with_data.data",'r')
> pattern_test =  re.compile("([0-9]+)" + ".*"  + " +" +
> str(time_tuple[2]).strip(' \t\n\r') + " +"  + str(time_tuple[0]).strip('
> \t\n\r') )
> for nnn in hhh:
>     if  (re.search(pattern_test,nnn)):
>    print nnn.split()[0]
>
> 111 Fri 4  8 2011
> 2323232 Fri 4 15 2011
> 4343434 Fri 4 22 2011
> 8522298 Fri 4 29 2011
> .
> 5456678 Fri 10 28 2011
> 563 Fri 11  4 2011
> 4141411 Fri 11 11 2011
> 332 Fri 11 18 2011
>
> --
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



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


Re: Help with regex needed

2011-04-11 Thread Chris Rebert
On Mon, Apr 11, 2011 at 10:20 PM, Yuri Slobodyanyuk
 wrote:
> Good day everyone,
> I am trying to make this pretty simple regex to work but got stuck,
> I'd appreciate your help .
> Task: Get current date , then read file of format below, find the line that
> matches
> the current date of month,month and year and extract the number from such
> line.
> Here is what I did , but if i run it at 11 April 2011 ...
>    - regex pattern_match  matches nothing
>    - regex pattern_test  matches the line "4141411 Fri 11 11 2011" , logical
> as it is the last matching line in year 2011 with the date of 11th.
> My question - why regex pattern_match  does not match anything and how to
> make it match the exact line i want.
> Thanks
> Yuri
>
> from datetime import datetime, date, time
> import re
> today_day = datetime.now()
> time_tuple= today_day.timetuple()
> pattern_match = re.compile("([0-9])+ +" +  "Fri +" + str(time_tuple[1]) + "
> +"  +   str(time_tuple[2]) + " +"  +  str(time_tuple[0]) + " +")
   ^^

This trailing " +" *requires* that the lines have trailing spaces. Do
they? Such files typically don't, and your example input doesn't
either (although that may be due to email formatting lossage).

Cheers,
Chris
--
http://blog.rebertia.com

> hhh = open("file_with_data.data",'r')
> pattern_test =  re.compile("([0-9]+)" + ".*"  + " +" +
> str(time_tuple[2]).strip(' \t\n\r') + " +"  + str(time_tuple[0]).strip('
> \t\n\r') )
> for nnn in hhh:
>     if  (re.search(pattern_test,nnn)):
>    print nnn.split()[0]
>
> 111 Fri 4  8 2011
> 2323232 Fri 4 15 2011
> 4343434 Fri 4 22 2011
> 8522298 Fri 4 29 2011
> .
> 5456678 Fri 10 28 2011
> 563 Fri 11  4 2011
> 4141411 Fri 11 11 2011
> 332 Fri 11 18 2011
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with regex needed

2011-04-11 Thread Chris Rebert
On Mon, Apr 11, 2011 at 10:20 PM, Yuri Slobodyanyuk
 wrote:
> Good day everyone,
> I am trying to make this pretty simple regex to work but got stuck,
> I'd appreciate your help .

"Some people, when confronted with a problem, think 'I know, I'll use
regular expressions.' Now they have two problems."


> 111 Fri 4  8 2011
> 2323232 Fri 4 15 2011
> 4343434 Fri 4 22 2011
> 8522298 Fri 4 29 2011
> .
> 5456678 Fri 10 28 2011
> 563 Fri 11  4 2011
> 4141411 Fri 11 11 2011
> 332 Fri 11 18 2011

There's no need to use regexes to parse such a simple file format.
Just use str.split() [without any arguments] on each line of the file,
and do the field equality checks yourself; your code will simpler.
Relevant docs: http://docs.python.org/library/stdtypes.html#str.split

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-11 Thread Nobody
On Tue, 12 Apr 2011 13:01:43 +1000, James Mills wrote:

>> That's still not equivalent. "return expr or None" will always
>> terminate the function. The OP's request was for something which would
>> terminate the function if and only if expr is non-false.
> 
> The OP did not state this at all.
> There was never any mention of early termination
> of the function iif expr was True.

What the OP actually said was:

> I propose the following syntax:
> 
> return? expr
> 
> be expanded to
> 
> _temp = expr
> if _temp: return _temp

It should be abundantly clear that this only returns if the expression is
considered true, otherwise it continues on to the following statements.


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


Re: Feature suggestion -- return if true

2011-04-11 Thread James Mills
On Tue, Apr 12, 2011 at 4:08 PM, Nobody  wrote:
> It should be abundantly clear that this only returns if the expression is
> considered true, otherwise it continues on to the following statements.

Uggh come on guys. We've been over this.
You cannot make that assumption.

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Twisted-Python] Announcing pyOpenSSL 0.12

2011-04-11 Thread anatoly techtonik
Good news. It may worth to update http://wiki.python.org/moin/SSL with
details. Right now it says that pyOpenSSL can not validate server
identity.
--
anatoly t.



On Tue, Apr 12, 2011 at 3:19 AM,   wrote:
> Exciting news everyone,
>
> I have just released pyOpenSSL 0.12.  pyOpenSSL provides Python bindings
> to a number of OpenSSL APIs, including certificates, public and private
> keys, and of course running TLS (SSL) over sockets or arbitrary in-
> memory buffiers.
>
> This release fixes an incompatibility with Python 2.7 involving
> memoryviews.  It also exposes the "info callback" constants used to
> report progress of the TLS handshake and later steps of SSL connections.
> Perhaps most interestingly, it also adds support for inspecting
> arbitrary X509 extensions.
>
> http://python.org/pypi/pyOpenSSL - check it out.
>
> Jean-Paul
>
> ___
> Twisted-Python mailing list
> twisted-pyt...@twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
>
-- 
http://mail.python.org/mailman/listinfo/python-list