Re: Returning a custom file object (Python 3)

2015-05-28 Thread Steven D'Aprano
On Thursday 28 May 2015 15:49, Chris Angelico wrote:

> ... but I don't think replacing all of open() is what Steven has in
> mind; it's a function that does a lot of work, most of which is what's
> wanted.

Correct. If I wanted to replace open(), I would have just shadowed it, or 
monkey-patched it, or just used myopen().

I want open() to return my own subclass instead of the standard one. And I 
think you have the solution I was looking for:


> Depending on how brutal you want to be, though, you _could_ hack around
> it.
> 
 from io import TextIOWrapper
 class MyFile(TextIOWrapper):
> ... def demo(self): print("Hello, world!")
> ...
 f = open("/tmp/dummy", "w", encoding="utf-8")
 f
> <_io.TextIOWrapper name='/tmp/dummy' mode='w' encoding='utf-8'>
 f.__class__
> 
 f.__class__ = MyFile
 f.demo()
> Hello, world!
> 
> This does appear to work. Whether or not it's a good idea is a
> separate question.


And this is EXACTLY the sort of use-case that having __class__ be writable 
is intended to solve. So this is exactly the solution I was after, thank 
you. Er... except for one little problem... in Python 3.3:

py> f = open("/tmp/a", "r")
py> f.__class__ = MyFile
Traceback (most recent call last):
  File "", line 1, in 
TypeError: __class__ assignment: only for heap types


So it doesn't work for me. What version of Python are you using?



-- 
Steve

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


Re: Returning a custom file object (Python 3)

2015-05-28 Thread Chris Angelico
On Thu, May 28, 2015 at 5:04 PM, Steven D'Aprano
 wrote:
>> This does appear to work. Whether or not it's a good idea is a
>> separate question.
>
>
> And this is EXACTLY the sort of use-case that having __class__ be writable
> is intended to solve. So this is exactly the solution I was after, thank
> you. Er... except for one little problem... in Python 3.3:
>
> py> f = open("/tmp/a", "r")
> py> f.__class__ = MyFile
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: __class__ assignment: only for heap types
>
>
> So it doesn't work for me. What version of Python are you using?

Huh, didn't even think to check other versions.

$ python3
Python 3.5.0b1+ (default:7255af1a1c50+, May 26 2015, 00:39:06)
[GCC 4.9.2] on linux

It's a build fresh from source control around about this weekend (some
time after feature freeze, obviously, but beyond that all I know is
what you see there). I guess this is pretty new; trying the same thing
on 3.4.2 doesn't work. But hey! 3.5 will be out soon...

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


Re: Returning a custom file object (Python 3)

2015-05-28 Thread Oscar Benjamin
On 28 May 2015 at 03:16, Steven D'Aprano  wrote:
> I'd like to return a custom file object, say my own subclass. I can easily
> subclass the file object:
>
>
> from io import TextIOWrapper
> class MyFile(TextIOWrapper):
> pass
>
>
> but how do I tell open() to use MyFile?

Does the below do what you want?

#!/usr/bin/env python3

class Wrapper:
def __init__(self, wrapped):
self._wrapped = wrapped
def __getattr__(self, attrname):
return getattr(self._wrapped, attrname)
# Special methods are not resolved by __getattr__
def __iter__(self):
return self._wrapped.__iter__()
def __enter__(self):
return self._wrapped.__enter__()
def __exit__(self, *args):
return self._wrapped.__exit__(*args)

class WrapFile(Wrapper):
def write(self):
return "Writing..."

f = WrapFile(open('wrap.py'))
print(f.readline())
with f:
print(len(list(f)))
print(f.write())

>
> Answers for Python 3, thanks.

Tested on 3.2.


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


Hi. I have questions about Python

2015-05-28 Thread 이현상
Hi.Please note that do not speak english well.
Do you know Python 2 vs Python3 MultiProcessing the difference ?Multiprocessing 
is better performance?
Search results do not make a big difference.
Why it will occur following the performance issues 
?http://www.reddit.com/r/Python/comments/37khen/is_that_why_python3_slower_than_python2/

Thank you.
블로그서명까뭉이 멜랑꼴리
만원은 구겨져도 천원이 되지 않는다.-- 
https://mail.python.org/mailman/listinfo/python-list


[QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Alexis Dubois
Hello everyone!

My QT GUI contains 8 QlistWidgets filled with a large amount of data.
Each item of a list is related to items of other lists in the same row.
So I want to scroll the 8 lists with only one vertical scrollbar (and 
vice-versa)

But I don't know how to manage this.
Do you have an idea?

(I'm quite new in python, I'm translating my tcl/tk app to this code)
thanks in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Laura Creighton
You want to define a scrollable area and then add your labels to it.
The code here: 
http://stackoverflow.com/questions/22255994/pyqt-adding-widgets-to-scrollarea-during-the-runtime

should show you what you need to do, though for you the job is easier if you
do not need to add the labels after the app is running.

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


Question About Image Processing in Python

2015-05-28 Thread Serge Christian Ibala
Hello All,


I want to know which version of Python is compatible (or can be associated
with which version of which "tools or package" for image processing)



I am working under Window and it is so complicated to find out which
version of which tool goes with which other version?



I want to use the following package

“numpy, matplotib, mahotas, ipython   OpenCV and SciPy"



Let say I use





Python 2.7 or Python 2.10 which version of the following tools



“numpy, matplotib, mahotas, ipython, OpenCV and SciPy”



should I use? and where can I find them?


Are there any package available for image processing using Python 3.4.3?



Or what is the recommendation of Python for image processing?



Do you know any good Python book on the subject or tutorial ?




Thank you enormously,


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


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Alexis Dubois
Le jeudi 28 mai 2015 12:12:42 UTC+2, Laura Creighton a écrit :
> You want to define a scrollable area and then add your labels to it.
> The code here: 
> http://stackoverflow.com/questions/22255994/pyqt-adding-widgets-to-scrollarea-during-the-runtime
> 
> should show you what you need to do, though for you the job is easier if you
> do not need to add the labels after the app is running.
> 
> Laura

Thanks Laura.
But as I understand the scrollable area, it's useful to scroll widgets.
But here, in my case, I want to scroll inside my widgets.
My QlistWidgets are fixed in size and data are append inside.
Because I want only one scrollbar for all lists, I set the 
"setVerticalScrollBarPolicy" lists property to "ScrollBarAlwaysOff" and tried 
to do what I need with a QScrollBar.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Laura Creighton
In a message of Thu, 28 May 2015 03:44:22 -0700, Alexis Dubois writes:
>Le jeudi 28 mai 2015 12:12:42 UTC+2, Laura Creighton a écrit :
>> You want to define a scrollable area and then add your labels to it.
>> The code here: 
>> http://stackoverflow.com/questions/22255994/pyqt-adding-widgets-to-scrollarea-during-the-runtime
>> 
>> should show you what you need to do, though for you the job is easier if you
>> do not need to add the labels after the app is running.
>> 
>> Laura
>
>Thanks Laura.
>But as I understand the scrollable area, it's useful to scroll widgets.
>But here, in my case, I want to scroll inside my widgets.
>My QlistWidgets are fixed in size and data are append inside.
>Because I want only one scrollbar for all lists, I set the 
>"setVerticalScrollBarPolicy" lists property to "ScrollBarAlwaysOff" and tried 
>to do what I need with a QScrollBar.

Ah, sorry, I misunderstood the question.

Hmmm.  I've never tried to do that.  Let me see if I can get something
to work.

Back later,
hack hack hack!
Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question About Image Processing in Python

2015-05-28 Thread Terry Reedy

On 5/28/2015 6:34 AM, Serge Christian Ibala wrote:


I want to know which version of Python is compatible (or can be
associated with which version of which "tools or package" for image
processing)


pillow is a one standard for image processing but I see that mahotas 
does different things. pillow is both 2.x and 3.x.



I am working under Window and it is so complicated to find out which
version of which tool goes with which other version?


The magic site for Windows binaries is
http://www.lfd.uci.edu/~gohlke/pythonlibs/
Now pip installable with an extra arg if not automatic.


I want to use the following package

“numpy, matplotib, mahotas, ipython   OpenCV and SciPy"


opencv seems to be the only one not available for 3.x.



Python 2.7 or Python 2.10 which version of the following tools


no 2.10, just 2.7.10, which is what you should install.


“numpy, matplotib, mahotas, ipython, OpenCV and SciPy”


just try pip install xyz and let it pick but see above if necessary for 
Windows binaries.



Are there any package available for image processing using Python 3.4.3?




--
Terry Jan Reedy


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


Re: Question About Image Processing in Python

2015-05-28 Thread Oscar Benjamin
On 28 May 2015 at 11:34, Serge Christian Ibala
 wrote:
> Hello All,
>
> I want to know which version of Python is compatible (or can be associated
> with which version of which "tools or package" for image processing)
>
> I am working under Window and it is so complicated to find out which version
> of which tool goes with which other version?
>
> I want to use the following package
>
> “numpy, matplotib, mahotas, ipython   OpenCV and SciPy"

I would just install the most recent released versions unless I saw
some information that suggested a problem with that.

You may want to consider installing something like the Anaconda Python
distribution which includes most of these packages (all except
mahotas) with a single installer:
http://docs.continuum.io/anaconda/install.html

You can see the list of packages included here:
http://docs.continuum.io/anaconda/pkg-docs.html

It will also install the mingw compiler that you could use to install
mahotas using pip/conda.


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


Re: Question About Image Processing in Python

2015-05-28 Thread Todd
On Thu, May 28, 2015 at 1:05 PM, Terry Reedy  wrote:

> On 5/28/2015 6:34 AM, Serge Christian Ibala wrote:
>
>
>  I want to use the following package
>>
>> “numpy, matplotib, mahotas, ipython   OpenCV and SciPy"
>>
>
> opencv seems to be the only one not available for 3.x.
>
>
OpenCV 3 (which is in RC1 now) supports Python 3.x.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Laura Creighton
Looks like what you need to do is to 
connect verticalScrollBar().valueChanged (in one widget) to
verticalScrollBar().setValue in all of the others.

So is this code on the right track?  It uses lists, not labels, and
doesn't hide the scrollbars, but is this the behaviour you need (
and weren't getting)?  It should work for labels too..


from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.listA = QtGui.QListWidget(self)
self.listB = QtGui.QListWidget(self)
self.listC = QtGui.QListWidget(self)

widgets=[self.listA, self.listB, self.listC]
layout = QtGui.QHBoxLayout(self)

for w1 in widgets:
layout.addWidget(w1)
for index in range(100):
w1.addItem('This is line number %d' % (index +1))
for w2 in widgets:
if w1 != w2:

w1.verticalScrollBar().valueChanged.connect(w2.verticalScrollBar().setValue)

if __name__ == '__main__':

import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Peter Otten
Alexis Dubois wrote:

> My QT GUI contains 8 QlistWidgets filled with a large amount of data.
> Each item of a list is related to items of other lists in the same row.
> So I want to scroll the 8 lists with only one vertical scrollbar (and
> vice-versa)
> 
> But I don't know how to manage this.
> Do you have an idea?
> 
> (I'm quite new in python, I'm translating my tcl/tk app to this code)
> thanks in advance

Are you perhaps looking for a table widget?

https://srinikom.github.io/pyside-docs/PySide/QtGui/QTableWidget.html

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


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Alexis Dubois
Thanks Peter, but no, even if it could be possible to use a QTableWidget 
instead of my 8 lists.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Alexis Dubois
Thank you Laura, it works.
(Even if connecting the scrollbar of one list to other lists is not what I 
exactly want to do, but no matter, I change the line 
"w1.verticalScrollBar().valueChanged.connect(w2.verticalScrollBar().setValue)" 
a little bit to fit my need. )
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-05-28 Thread Anssi Saari
Marko Rauhamaa  writes:

> Ned Batchelder :
>
>> I would find it much clearer to not use a nested class at all, and
>> instead to pass the object into the constructor:
>
> Nested classes are excellent and expressing the state pattern  http://en.wikipedia.org/wiki/State_pattern>.

Do you have an example of state pattern using nested classes and python?
With a quick look I didn't happen to find one in any language.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question About Image Processing in Python

2015-05-28 Thread Sturla Molden
Serge Christian Ibala  wrote:

> Or what is the recommendation of Python for image processing?

Basic setup everyone should have:

Python
NumPy
SciPy (e.g. scipy.ndimage)
Cython
C and C++ compiler
matplotlib
scikit-image
scikit-learn
pillow

Also consider:
mahotas
tifffile (by Christoph Gohlke)
OpenCV
PyOpenGL
VTK
mayavi
pyglet
PyGame
PyQt

Abandonware:
PIL

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


Re: Hi. I have questions about Python

2015-05-28 Thread Sturla Molden
이현상  wrote:
> Hi.Please note that do not speak english well.
> Do you know Python 2 vs Python3 MultiProcessing the difference
> ?Multiprocessing is better performance?

The main difference is that multiprocessing on Python 3.4 (and later) will
allow you to use APIs that are not "forksafe" on Linux or Mac. One example
is Accelerate Framework on Mac OSX (e.g. used by numpy.linalg).

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


Re: should "self" be changed?

2015-05-28 Thread Marko Rauhamaa
Anssi Saari :

> Do you have an example of state pattern using nested classes and
> python? With a quick look I didn't happen to find one in any language.

Here's an sampling from my mail server:


class SMTPServerConnection(ServerConnection):
#: : :
#: : :

def __init__(self, server, sock, domain, peer):
super().__init__(server, sock)
conn = self
client_ip = peer[0]

class STATE:
def __str__(self):
return self.__class__.__name__
def handle_command(self, cmd):
conn.log("handle_command (unexpected): {}".format(cmd))
assert False
def handle_bad_command(self, reason):
conn.log("handle_bad_command (unexpected): {}".format(reason))
assert False
def handle_eof(self):
conn.log("eof (unexpected)")
assert False
def terminate(self):
assert False

class IDLE(STATE):
def handle_command(self, cmd):
conn.log("handle_command: {}".format(cmd))
verb, args = conn.split_cmd(cmd)
if verb == b'EHLO':
self.process_ehlo_or_helo(
args,
"PIPELINING",
"SIZE {:d}".format(conn.MAX_MSG_SIZE),
"VRFY",
"EXPN",
"8BITMIME")
elif verb == b'HELO':
self.process_ehlo_or_helo(args)
elif verb in [ b'NOOP', b'RSET' ]:
conn.respond(250, "OK")
elif verb == b'HELP':
conn.respond(214, "No help available")
elif verb in [ b'VRFY', b'EXPN' ]:
conn.respond(550, "Access denied to you")
elif verb == b'QUIT':
conn.respond(221, "{} Closing channel".format(
server.domain))
conn.shut_down()
conn.set_state(QUITTING)
elif verb == b'MAIL':
self.handle_mail(args)
elif verb in [ b'RCPT', b'DATA' ]:
conn.respond(503, "Bad sequence of commands")
else:
conn.respond(500, "Command unrecognized")

def process_ehlo_or_helo(self, args, *capabilities):
if not args:
conn.respond(501, "Missing parameter")
return
try:
# may be an IP address
conn.helo_domain_name = args[0].decode()
except UnicodeError:
conn.respond(501, "Bad encoding in parameter")
return
if conn.local_client:
conn.respond(250, server.domain, *capabilities)
conn.set_state(IDLE)
return
## todo: remove the "suspend" concept from mux
conn.suspend()
conn.log("authorize helo {} from {}".format(
conn.helo_domain_name, client_ip))
conn.set_state(SPF_HELO)
def callback(verdict, reason):
conn.state.handle_spf_verdict(
verdict, reason, *capabilities)
conn.spf_query = server.spf_client.authorize_helo(
server.host, conn.helo_domain_name, server.family,
client_ip, callback, xid = id(conn))

#: : :
#: : :

class SPF_HELO(STATE):
def terminate(self):
conn.resume()
conn.spf_query.cancel()
conn.close()
if conn.timer is not None:
conn.timer.cancel()
conn.timer = None
conn.set_state(ZOMBIE)

def handle_spf_verdict(self, verdict, reason, *capabilities):
conn.resume()
conn.log("verdict {} reason {}".format(verdict, reason))
# RFC 4408 §2.5.5 calls for leniency for SoftFail
#if verdict in [ SPFClient.FAIL, SPFClient.SOFT_FAIL ]:
if verdict in [ SPFClient.FAIL ]:
conn.respond(550, "SPF check failed: {}".format(reason))
conn.set_state(IDLE)
return
conn.respond(250, server.domain, *capabilities)
conn.set_state(IDLE)

class SPF_SENDER(STATE):
def terminate(self):
conn.resume()
conn.spf_query.cancel()
conn.close()
if conn.timer is not None:
conn.timer.cancel()
conn.timer = None
conn.set_state(

Re: [QT] Scroll multiple lists with one scrollbar

2015-05-28 Thread Laura Creighton
In a message of Thu, 28 May 2015 05:53:34 -0700, Alexis Dubois writes:
>Thank you Laura, it works.
>(Even if connecting the scrollbar of one list to other lists is not what I 
>exactly want to do, but no matter, I change the line 
>"w1.verticalScrollBar().valueChanged.connect(w2.verticalScrollBar().setValue)" 
>a little bit to fit my need. )

Great, I had to go to a meeting, so things were not in such a nice
state as I would have liked.  In particular, if some of your lists
are never going to have any scroll bars attatched to them, there is
no need to wire them up to the thing.  But I thought  I had found
the little bit of magic you needed; glad I was correct this time.

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


Re: should "self" be changed?

2015-05-28 Thread Ian Kelly
On Thu, May 28, 2015 at 9:01 AM, Marko Rauhamaa  wrote:
> Anssi Saari :
>
>> Do you have an example of state pattern using nested classes and
>> python? With a quick look I didn't happen to find one in any language.
>
> Here's an sampling from my mail server:

I think I would be more inclined to use enums. This has the advantages
of not creating a new set of state classes for every connection
instance and that each state is a singleton instance, allowing things
like "if self.state is SMTPConnectionState.IDLE". It could look
something like this:

class SMTPConnectionState(Enum):

class IDLE:
@classmethod
def handle_command(cls, conn, cmd):
# ...

class SPF_HELO:
@classmethod
def terminate(cls, conn):
# ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a reliable sandboxed Python environment

2015-05-28 Thread davidfstr
Thanks for the responses folks. I will briefly summarize them:

> As you say, it is fundamentally not possible to make this work at 
the Python level.

This is pretty effectively demonstrated by "Tav's admirable but failed attempt 
to sandbox file IO":
* http://tav.espians.com/a-challenge-to-break-python-security.html

Wow there are some impressive ways to confuse the system. I particularly like 
overriding str's equality function to defeat mode checking code when opening 
files.

> When we needed this at edX, we wrote CodeJail 
> (https://github.com/edx/codejail). 
It's a wrapper around AppArmor to provide OS-level protection of code 
execution in subprocesses.  It has Python-specific features, but because it 
is based on AppArmor, can sandbox any process, so long as it's configured 
properly. 

This looks promising. I will take a closer look.

> What about launching the Python process in a Docker container?

This may work in combination with other techniques. Certainly faster than 
spinning up a new VM or snapshot-restoring a fixed VM on a repeated basis. 
Would need to see whether CPU, Memory, and Disk usage could be constrained at 
the level of a container.

- David


On Monday, May 25, 2015 at 7:24:32 PM UTC-7, davi...@gmail.com wrote:
> I am writing a web service that accepts Python programs as input, runs the 
> provided program with some profiling hooks, and returns various information 
> about the program's runtime behavior. To do this in a safe manner, I need to 
> be able to create a sandbox that restricts what the submitted Python program 
> can do on the web server.
> 
> Almost all discussion about Python sandboxes I have seen on the internet 
> involves selectively blacklisting functionality that gives access to system 
> resources, such as trying to hide the "open" builtin to restrict access to 
> file I/O. All such approaches are doomed to fail because you can always find 
> a way around a blacklist.
> 
> For my particular sandbox, I wish to allow *only* the following kinds of 
> actions (in a whitelist):
> * reading from stdin & writing to stdout;
> * reading from files, within a set of whitelisted directories;
> * pure Python computation.
> 
> In particular all other operations available through system calls are banned. 
> This includes, but is not limited to:
> * writing to files;
> * manipulating network sockets;
> * communicating with other processes.
> 
> I believe it is not possible to limit such operations at the Python level. 
> The best you could do is try replacing all the standard library modules, but 
> that is again just a blacklist - it won't prevent a determined attacker from 
> doing things like constructing their own 'code' object and executing it.
> 
> It might be necessary to isolate the Python process at the operating system 
> level.
> * A chroot jail on Linux & OS X can limit access to the filesystem. Again 
> this is just a blacklist.
> * No obvious way to block socket creation. Again this would be just a 
> blacklist.
> * No obvious way to detect unapproved system calls and block them.
> 
> In the limit, I could dynamically spin up a virtual machine and execute the 
> Python program in the machine. However that's extremely expensive in 
> computational time.
> 
> Has anyone on this list attempted to sandbox Python programs in a serious 
> fashion? I'd be interested to hear your approach.
> 
> - David
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-05-28 Thread Marko Rauhamaa
Ian Kelly :

> On Thu, May 28, 2015 at 9:01 AM, Marko Rauhamaa  wrote:
>> Anssi Saari :
>>
>>> Do you have an example of state pattern using nested classes and
>>> python? With a quick look I didn't happen to find one in any
>>> language.
>>
>> Here's an sampling from my mail server:
>
> I think I would be more inclined to use enums. This has the advantages
> of not creating a new set of state classes for every connection
> instance and that each state is a singleton instance, allowing things
> like "if self.state is SMTPConnectionState.IDLE". It could look
> something like this:
>
> class SMTPConnectionState(Enum):
>
> class IDLE:
> @classmethod
> def handle_command(cls, conn, cmd):
> # ...
>
> class SPF_HELO:
> @classmethod
> def terminate(cls, conn):
> # ...

Really, the main expressive choice is whether you use an inner class
(and get the advantages of a closure) or an outer class (and get
potential performance advantages).

When I have coded state machines for C or Java, I have noticed that
nothing beats enums and switch statements performance-wise, and
expressively, they're not that bad, either. Python doesn't have a switch
statement, so the natural thing is to ride on method dispatching
(whether via inner or outer classes). However, I must say the exception
"idiom" someone mentioned on this forum way back has its lure:

try: raise self.state
except IDLE:
#...
except SPF_HELO:
#...


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


Re: should "self" be changed?

2015-05-28 Thread Chris Angelico
On Fri, May 29, 2015 at 2:59 AM, Marko Rauhamaa  wrote:
> When I have coded state machines for C or Java, I have noticed that
> nothing beats enums and switch statements performance-wise, and
> expressively, they're not that bad, either. Python doesn't have a switch
> statement, so the natural thing is to ride on method dispatching
> (whether via inner or outer classes). However, I must say the exception
> "idiom" someone mentioned on this forum way back has its lure:
>
> try: raise self.state
> except IDLE:
> #...
> except SPF_HELO:
> #...

I take exception to that idiom. :)

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


Re: Question About Image Processing in Python

2015-05-28 Thread Alan Gauld

On 28/05/15 11:34, Serge Christian Ibala wrote:


I want to know which version of Python is compatible (or can be
associated with which version of which "tools or package" for image
processing)


It would help if you told us what kind of image processing.
If you mean programmatic manipulation of images similar
to what would be done using GIMP/Photoshop then the most
common tools are ImageMagick and Pillow. But you mention
neither, so I'm guessing you are looking at doing
something else - maybe trying to analyze content?

Given the list of tools you list I'd suggest fetching
an all-in-one distro like Anaconda or Canopy. That
way somebody else does the dependency dance for you.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Creating a reliable sandboxed Python environment

2015-05-28 Thread Stefan Behnel
davidf...@gmail.com schrieb am 26.05.2015 um 04:24:
> Has anyone on this list attempted to sandbox Python programs in a
> serious fashion? I'd be interested to hear your approach.

Not quite sandboxing Python, but I've seen people use my Lupa [1] library
for this. They're writing all their code in Python, and then let users
embed their own Lua code into it to script their API. The Lua runtime is
apparently quite good at sandboxing, and it's really small, just some 600KB
or so. Lupa then lets you easily control the access to your Python code at
a whitelist level by intercepting all Python attribute lookups.

It doesn't add much to your application to embed Lua (or even LuaJIT) in
Python, and it gives users a nicely object oriented language to call and
orchestrate your Python objects.

Stefan


[1] https://pypi.python.org/pypi/lupa

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


Re: Creating a reliable sandboxed Python environment

2015-05-28 Thread Chris Angelico
On Fri, May 29, 2015 at 4:41 AM, Stefan Behnel  wrote:
> davidf...@gmail.com schrieb am 26.05.2015 um 04:24:
>> Has anyone on this list attempted to sandbox Python programs in a
>> serious fashion? I'd be interested to hear your approach.
>
> Not quite sandboxing Python, but I've seen people use my Lupa [1] library
> for this. They're writing all their code in Python, and then let users
> embed their own Lua code into it to script their API. The Lua runtime is
> apparently quite good at sandboxing, and it's really small, just some 600KB
> or so. Lupa then lets you easily control the access to your Python code at
> a whitelist level by intercepting all Python attribute lookups.
>
> It doesn't add much to your application to embed Lua (or even LuaJIT) in
> Python, and it gives users a nicely object oriented language to call and
> orchestrate your Python objects.

Lua's a much weaker language than Python is, though. Can it handle
arbitrary-precision integers? Unicode? Dare I even ask,
arbitrary-precision rationals (fractions.Fraction)? Security comes at
a price, I guess.

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


Re: Decoding JSON file using python

2015-05-28 Thread Denis McMahon
On Thu, 28 May 2015 13:32:39 +1000, Cameron Simpson wrote:

> On 28May2015 01:38, Jon Ribbens  wrote:
>>On 2015-05-27, Karthik Sharma  wrote:
>>> I tried modifying the program as follows as per your
>>> suggestion.Doesn't seem to work.
>>
>>That's because you didn't modify the program as per their suggestion,
>>you made completely different changes that bore no relation to what they
>>said.
> 
> Actually, his changes looked good to me. He does print from data first,
> but only for debugging. Then he goes:
> 
>   message = json.loads(data)
> 
> and tried to access message['Message'].
> 
> However I am having trouble reproducing his issue because his quoted
> code is incorrect. I've tried to fix it, as listed below, but I don't
> know what is really meant to be in the 'data" string.

it looks like data is a broken array of one object, part of which is a 
further quoted json string.

There should be a string value after the isEvent but I have no idea what 
it should be, nor what else should come after.

"message":"tdetails":{att:val pairs}

is also wrong in the first level of inner json.

I think he wants data[0]['message'], but the inner json strings are 
broken too, and should look more like.

data: "[{\"Severity\":\"warn\",\"Subject\":\"Reporting\",\"Message\":
\"tdetails\",\"attr_name\":\"{\\\"Product\\\":\\\"Gecko\\\",\\\"CPUs\\
\":8,\\\"Language\\\":\\\"en-GB\\\",\\\"isEvent\\\":\\\"attr_value\\\"}\"}
]",

In this model, if the data attribute is a json string, then

data maps to a list / array

data[0] maps to an object / dictionary

data[0]["Message"] maps to the string literal "tdetails"

data[0]["attr_name"] maps to a string representation of a json ob with 
another level of escaping.

That string can then be loaded, eg:

attr_name = json.loads(data[0]["attr_name"])

See: http:/www.sined.co.uk/python/nested_json.py.txt


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decoding JSON file using python

2015-05-28 Thread Denis McMahon
On Wed, 27 May 2015 15:23:31 -0700, Karthik Sharma wrote:

> The JSON structure is valid as shown by http://jsonlint.com/

Not when I paste it in it's not. The "data" attribute is an unterminated 
string and is not followed by a comma.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Skybuck Flying

Hello,

I was just coding and ran into a little logic problem which is as follows:

There are two booleans/variables which can be either false or true.

The desired thrutle table is:

A = input
B = input
C = output

A B C:
---
F F T
F T F
T F T
T T T

Surpisingly enough I don't think there is a casual/common operator for this 
thruth table.


AND does not apply.
OR does not apply.
XOR does not apply.

So I would need some combined operators to give the desired result.

I tried logic below... but funny enough it failed, now I feel like a noob 
lol and share this funny little fail logic with you.


Can you improve/fix the logic ?

This is python code, but this^ logic/thruth table problem basically applies 
to any programming language:


# loop has to run if:
# while DesiredResult==True:
# Desired truth table for BotWaitForCooldown and CooldownDetected
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# False   FalseTrue
# False   True False
# True FalseTrue
# True True True
# desired/suiting logic:
# (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))

def TestLogic( BotWaitForCooldown, CooldownDetected ):
return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected) 
# this logic is flawed, please improve logic.


if TestLogic( False, False ) == True:
print "test 1 ok"
else:
print "test 1 failed"

if TestLogic( False, True ) == False:
print "test 2 ok"
else:
print "test 2 failed"

if TestLogic( True, False ) == True:
print "test 3 ok"
else:
print "test 3 failed"

if TestLogic( True, True ) == True:
print "test 4 ok"
else:
print "test 4 failed"

Bye,
 Skybuck. 


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


Pep 484 Type Hint Checker - Python releases supported?

2015-05-28 Thread Dan Stromberg
I believe I heard that the PEP 484 type checker is to go into CPython 3.5.

Since type annotations have been there since 3.0, is it at all likely
that CPython versions < 3.5 will also be supported by this checker?

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


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying
I think I have run into this problem before... but solved it with some 
seperate if statements.


However in this case/this time I would like to not solve it with if 
statements, but simply and/or/not/xor, in other words, boolean operators.


So what would help is a "thruth table to logic" convertor/generator ?!

Anybody know one that is suited for boolean logic/software 
programming/programming languages/boolean operations ?


Bye,
 Skybuck.

Original posting:

"Skybuck Flying"  wrote in message 
news:3794b$55678d83$5419aafe$56...@news.ziggo.nl...


Hello,

I was just coding and ran into a little logic problem which is as follows:

There are two booleans/variables which can be either false or true.

The desired thrutle table is:

A = input
B = input
C = output

A B C:
---
F F T
F T F
T F T
T T T

Surpisingly enough I don't think there is a casual/common operator for this
thruth table.

AND does not apply.
OR does not apply.
XOR does not apply.

So I would need some combined operators to give the desired result.

I tried logic below... but funny enough it failed, now I feel like a noob
lol and share this funny little fail logic with you.

Can you improve/fix the logic ?

This is python code, but this^ logic/thruth table problem basically applies
to any programming language:

# loop has to run if:
# while DesiredResult==True:
# Desired truth table for BotWaitForCooldown and CooldownDetected
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# False   FalseTrue
# False   True False
# True FalseTrue
# True True True
# desired/suiting logic:
# (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))

def TestLogic( BotWaitForCooldown, CooldownDetected ):
return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected)
# this logic is flawed, please improve logic.

if TestLogic( False, False ) == True:
print "test 1 ok"
else:
print "test 1 failed"

if TestLogic( False, True ) == False:
print "test 2 ok"
else:
print "test 2 failed"

if TestLogic( True, False ) == True:
print "test 3 ok"
else:
print "test 3 failed"

if TestLogic( True, True ) == True:
print "test 4 ok"
else:
print "test 4 failed"

Bye,
 Skybuck.

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Tim Chase
On 2015-05-28 23:50, Skybuck Flying wrote:
> A = input
> B = input
> C = output
> 
> A B C:
> ---
> F F T
> F T F
> T F T
> T T T
> 
> Surpisingly enough I don't think there is a casual/common operator
> for this thruth table.
> 
> AND does not apply.
> OR does not apply.
> XOR does not apply.

Sounds like you want "a or not b"

>>> print("\n".join("A=%s B=%s: %s" % (a, b, a or not b) for a in (True, False) 
>>> for b in (True, False)))
A=True B=True: True
A=True B=False: True
A=False B=True: False
A=False B=False: True

-tkc


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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread sohcahtoa82
On Thursday, May 28, 2015 at 2:50:18 PM UTC-7, Skybuck Flying wrote:
> Hello,
> 
> I was just coding and ran into a little logic problem which is as follows:
> 
> There are two booleans/variables which can be either false or true.
> 
> The desired thrutle table is:
> 
> A = input
> B = input
> C = output
> 
> A B C:
> ---
> F F T
> F T F
> T F T
> T T T
> 
> Surpisingly enough I don't think there is a casual/common operator for this 
> thruth table.
> 
> AND does not apply.
> OR does not apply.
> XOR does not apply.
> 
> So I would need some combined operators to give the desired result.
> 
> I tried logic below... but funny enough it failed, now I feel like a noob 
> lol and share this funny little fail logic with you.
> 
> Can you improve/fix the logic ?
> 
> This is python code, but this^ logic/thruth table problem basically applies 
> to any programming language:
> 
> # loop has to run if:
> # while DesiredResult==True:
> # Desired truth table for BotWaitForCooldown and CooldownDetected
> # BotWaitForCooldown:  CooldownDetected: Desired Result:
> # False   FalseTrue
> # False   True False
> # True FalseTrue
> # True True True
> # desired/suiting logic:
> # (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))
> 
> def TestLogic( BotWaitForCooldown, CooldownDetected ):
> return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected) 
> # this logic is flawed, please improve logic.
> 
> if TestLogic( False, False ) == True:
> print "test 1 ok"
> else:
> print "test 1 failed"
> 
> if TestLogic( False, True ) == False:
> print "test 2 ok"
> else:
> print "test 2 failed"
> 
> if TestLogic( True, False ) == True:
> print "test 3 ok"
> else:
> print "test 3 failed"
> 
> if TestLogic( True, True ) == True:
> print "test 4 ok"
> else:
> print "test 4 failed"
> 
> Bye,
>   Skybuck.

I think the logic you're really looking for is:

return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Grant Edwards
On 2015-05-28, Skybuck Flying  wrote:

> I tried logic below... but funny enough it failed, now I feel like a
> noob lol and share this funny little fail logic with you.
>
> Can you improve/fix the logic ?

> # while DesiredResult==True:
> # Desired truth table for BotWaitForCooldown and CooldownDetected
> # BotWaitForCooldown:  CooldownDetected: Desired Result:
> # FalseFalse True
> # FalseTrue  False
> # True False True
> # True True  True
> # desired/suiting logic:
> # (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))

I don't see why you think that's the desired logic, since it doesn't
match your truth table or your test.

> def TestLogic( BotWaitForCooldown, CooldownDetected ):
> return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected)
> # this logic is flawed, please improve logic.

def TestLogic( BotWaitForCooldown, CooldownDetected ):
return not ((not BotWaitForCooldown) and CooldownDetected)

works for me...

-- 
Grant Edwards   grant.b.edwardsYow! Alright, you!!
  at   Imitate a WOUNDED SEAL
  gmail.compleading for a PARKING
   SPACE!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pep 484 Type Hint Checker - Python releases supported?

2015-05-28 Thread Zachary Ware
On Thu, May 28, 2015 at 4:58 PM, Dan Stromberg  wrote:
> I believe I heard that the PEP 484 type checker is to go into CPython 3.5.
>
> Since type annotations have been there since 3.0, is it at all likely
> that CPython versions < 3.5 will also be supported by this checker?

All that's going into 3.5 is the typing.py module, which will also be
distributed on PyPI.  The actual type checking is being left to
third-party tools like MyPy (which was the basis for the typing.py
module).

I'm not sure if there is any plan to ever include an actual type
checker with the base Python distribution.

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


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying

This is a start lol:

https://www.youtube.com/watch?v=lKqTSBKmWA4

I wonder if it can be simplied... I'll give it a try.

Basically it comes down to creating a logic expression for each true result 
in the desired output and or-ing with each other.


The variables leading to the true result in the desired output need to be 
kept if true, and negated if false.


So for example:
A B C
F T T

((NOT A) AND (B) AND ETC) OR ETC.

What the video didn't really explain is probably to "and" the variables... 
but it did mention "multiply".


I guess "AND" is the closest thing to a multiply ;)

Makes sense... only AND gives a 1 output if all variables are true, 
otherwise it would zero out...


Bye,
 Skybuck. 


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


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying

However I can already see I am not happy with this video solution.

I have 3 true outputs, and only 1 false output.

That would require a lot of logic.

I guess I can turn it around and negate the whole thing... and focus on the 
false output.


Bye,
 Skybuck. 


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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Jussi Piitulainen
Skybuck Flying writes:

> There are two booleans/variables which can be either false or true.
>
> The desired thrutle table is:
>
> A = input
> B = input
> C = output
>
> A B C:
> ---
> F F T
> F T F
> T F T
> T T T

That's A >= B, where True >= False:

  >>> BB = False, True
  >>> print(*((A, B, A >= B) for A in BB for B in BB), sep = '\n')
(False, False, True)
(False, True, False)
(True, False, True)
(True, True, True)
  >>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Grant Edwards
On 2015-05-28, Grant Edwards  wrote:
> On 2015-05-28, Skybuck Flying  wrote:
>
>> I tried logic below... but funny enough it failed, now I feel like a
>> noob lol and share this funny little fail logic with you.
>>
>> Can you improve/fix the logic ?
>
>> # while DesiredResult==True:
>> # Desired truth table for BotWaitForCooldown and CooldownDetected
>> # BotWaitForCooldown:  CooldownDetected: Desired Result:
>> # FalseFalse True
>> # FalseTrue  False
>> # True False True
>> # True True  True
>> # desired/suiting logic:
>> # (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))
>
> I don't see why you think that's the desired logic, since it doesn't
> match your truth table or your test.
>
>> def TestLogic( BotWaitForCooldown, CooldownDetected ):
>> return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected)
>> # this logic is flawed, please improve logic.
>
> def TestLogic( BotWaitForCooldown, CooldownDetected ):
> return not ((not BotWaitForCooldown) and CooldownDetected)
>
> works for me...

While I think that's the most "obvious" solution and can be verified
by inspection: there's only out input state that is "false", so write an 
expression
for that one state and invert it.

However, you can apply De Morgan's law to simplify it:

   not ((not BotWaitForCooldown) and CooldownDetected)
   
is same as

   (BotWaitForCooldown or (not CooldownDetected))

-- 
Grant Edwards   grant.b.edwardsYow! Do you have exactly
  at   what I want in a plaid
  gmail.compoindexter bar bat??
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Grant Edwards
On 2015-05-28, Skybuck Flying  wrote:

> However I can already see I am not happy with this video solution.
>
> I have 3 true outputs, and only 1 false output.
>
> That would require a lot of logic.
>
> I guess I can turn it around and negate the whole thing... and focus on the 
> false output.

Don't they teach Karnaugh mapping any more?

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

-- 
Grant Edwards   grant.b.edwardsYow! I want the presidency
  at   so bad I can already taste
  gmail.comthe hors d'oeuvres.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying

Ok, problem solved for now, it seems:

I used video tutorial method and inverted it for the false case ;)

But anyway... I would not only need a "thruth table to logic/boolean 
operations converter" but also a "boolean operations optimizer" ;)


# loop has to run if:
# while DesiredResult==True:
# Desired truth table for BotWaitForCooldown and CooldownDetected
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# False   FalseTrue
# False   True False
# True FalseTrue
# True True True
# desired/suiting logic:
# (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))



def TestLogic( BotWaitForCooldown, CooldownDetected ):
# return BotWaitForCooldown or ((not BotWaitForCooldown) and 
CooldownDetected) # this logic is flawed, please improve logic.

return (not ((not BotWaitForCooldown) and CooldownDetected))  # fixes it.

if TestLogic( False, False ) == True:
print "test 1 ok"
else:
print "test 1 failed"

if TestLogic( False, True ) == False:
print "test 2 ok"
else:
print "test 2 failed"

if TestLogic( True, False ) == True:
print "test 3 ok"
else:
print "test 3 failed"

if TestLogic( True, True ) == True:
print "test 4 ok"
else:
print "test 4 failed"

Bye,
 Skybuck. 


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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Michael Torrie
On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
> I think the logic you're really looking for is:
> 
> return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))

Yes this is the simplest form.  For more complicated truth tables you
can create a K map and then apply a reduction algorithm to it.  This is
commonly done in logic circuits to reduce the number of gates to the
minimum.  While not faster, it can be expressed as:

return BotWaitForCooldown or not BotWaitForCooldown and not
CooldownDectected

Order of operations puts the ands above the ors.


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


Re: Accessing DataSocket Server with Python

2015-05-28 Thread Dan Stromberg
I have no idea about the protocol used by NI DataSockets, but you
might be able to reverse engineer the protocol by using the official
client with a sniffer.

Also, be aware that TCP/IP guarantees that you get the correct data in
the correct order, but it doesn't guarantee anything about the sizes
of the chunks in which that data arrives.  So you could send 100
bytes, 100 bytes, 100 bytes, but on the other end receive 100 bytes,
50 bytes, 75 bytes, 75 bytes.  When you catenate them all together,
it's still the same data though.

HTH.

On Wed, May 27, 2015 at 4:30 AM, Garrone, Corrado
 wrote:
> Dear Python Team,
>
> currently I am working on a research project for my bachelor degree. A
> LabVIEW application is used for current and power measurements, whereas the
> measured data are sent to DataSocket Server, a technology by National
> Instruments used for data exchange between computers and applications.
> DataSocket is based on TCP/IP and thus requesting data from DataSocket
> should be similar to an internet request.
> I know with the socket library in Python it is possible with to establish
> sockets, send internet requests and communicate between clients and servers.
> Is there a possibility to access NI DataSocket and get measurement data with
> Python on the same computer where Python is installed and the codes are
> executed? Can you maybe send me an example code where such a connection with
> DataSocket is established?
>
> If you got any queries, please do not hesitate to contact me.
>
> Thank you very much for your efforts.
>
> Kind regards,
>
> Corrado Garrone
> DH-Student Fachrichtung Elektrotechnik / Co-op Student B.Eng. Electrical
> Engineering
>
> Roche Diagnostics GmbH
> DFGHMV8Y6164
> Sandhofer Strasse 116
> 68305 Mannheim / Germany
>
> Phone: apprentice
> mailto:corrado.garr...@roche.com
>
> Roche Diagnostics GmbH
> Sandhofer Straße 116; D‑68305 Mannheim; Telefon +49‑621‑759‑0; Telefax
> +49‑621‑759‑2890
> Sitz der Gesellschaft: Mannheim - Registergericht: AG Mannheim HRB 3962 -
> Geschäftsführung: Dr. Ursula Redeker, Sprecherin; Edgar Vieth -
> Aufsichtsratsvorsitzender: Dr. Severin Schwan
>
> Confidentiality Note
> This message is intended only for the use of the named recipient(s) and may
> contain confidential and/or privileged information. If you are not the
> intended recipient, please contact the sender and delete the message. Any
> unauthorized use of the information contained in this message is prohibited.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Grant Edwards
On 2015-05-28, Grant Edwards  wrote:
> On 2015-05-28, Skybuck Flying  wrote:
>
>> However I can already see I am not happy with this video solution.
>>
>> I have 3 true outputs, and only 1 false output.
>>
>> That would require a lot of logic.
>>
>> I guess I can turn it around and negate the whole thing... and focus on the 
>> false output.
>
> Don't they teach Karnaugh mapping any more?
>
> http://en.wikipedia.org/wiki/Karnaugh_map

BTW, your example truth table is shown in the paragraph '2-variable
map examples'

-- 
Grant Edwards   grant.b.edwardsYow! Oh my GOD -- the
  at   SUN just fell into YANKEE
  gmail.comSTADIUM!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pep 484 Type Hint Checker - Python releases supported?

2015-05-28 Thread Chris Angelico
On Fri, May 29, 2015 at 8:06 AM, Zachary Ware
 wrote:
> On Thu, May 28, 2015 at 4:58 PM, Dan Stromberg  wrote:
>> I believe I heard that the PEP 484 type checker is to go into CPython 3.5.
>>
>> Since type annotations have been there since 3.0, is it at all likely
>> that CPython versions < 3.5 will also be supported by this checker?
>
> All that's going into 3.5 is the typing.py module, which will also be
> distributed on PyPI.  The actual type checking is being left to
> third-party tools like MyPy (which was the basis for the typing.py
> module).
>
> I'm not sure if there is any plan to ever include an actual type
> checker with the base Python distribution.

And MyPy is quite capable of probing code that belongs on older
interpreters than 3.5 (obviously, since it already exists); it even
has some measure of support for probing Py2 code, although you do need
to have a Python 3.2+ to actually run MyPy on.

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Lew Pitcher
On Thursday May 28 2015 17:50, in comp.lang.c, "Skybuck Flying"
 wrote:

> Hello,
> 
> I was just coding and ran into a little logic problem which is as follows:
> 
> There are two booleans/variables which can be either false or true.
> 
> The desired thrutle table is:
> 
> A = input
> B = input
> C = output
> 
> A B C:
> ---
> F F T
> F T F
> T F T
> T T T

Seems simple enough: C == A || !B

18:38 $ cat testlogic.c
#include 
#include 

/*
** A = input
** B = input
** C = output
** 
** A B C:
** ---
** F F T
** F T F
** T F T
** T T T
*/

int testlogic(int a, int b)
{
  return (a || !b);
}

int main(void)
{
  /* A B C */
  int ttable[4][3] = {  {0,0,1},/* F F T */
{0,1,0},/* F T F */
{1,0,1},/* T F T */
{1,1,1} /* T T T */
 };
  int rc = EXIT_SUCCESS;
  int i, max;

  for (i = 0, max = sizeof(ttable) / sizeof(ttable[0]); i < max ; ++i)
if (testlogic(ttable[i][0],ttable[i][1]) != ttable[i][2])
{
  printf("testlogic failed on test %d\n",i);
  rc = EXIT_FAILURE;
}

  if (rc == EXIT_SUCCESS) puts("SUCCESS");

  return rc;
}
18:39 $ cc -o testlogic testlogic.c
18:39 $ ./testlogic
SUCCESS


-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

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


[no subject]

2015-05-28 Thread yasna araya
hola, escribo para solicitar el uso del programa Python para trabajarlo con mi 
hijo. desde ya muchas gracias






Enviado desde Correo de Windows-- 
https://mail.python.org/mailman/listinfo/python-list


Re:

2015-05-28 Thread Chris Angelico
2015-05-29 9:44 GMT+10:00 yasna araya :
> hola, escribo para solicitar el uso del programa Python para trabajarlo con
> mi hijo. desde ya muchas gracias
>
> Enviado desde Correo de Windows

Hello!

This is an English-language list, and most of the people here - myself
included - are not fluent in Spanish. But you can download Python from
here:

https://www.python.org/downloads/

If that wasn't what you were looking for, I apologize; possibly
someone else here speaks better Spanish, or perhaps you could rephrase
your question in English.

All the best!

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Grant Edwards
On 2015-05-28, Michael Torrie  wrote:
> On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
>> I think the logic you're really looking for is:
>> 
>> return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
>
> Yes this is the simplest form.

Not really.


In old school notation, that's
___
A + A+B  

Apply De Morgan's law to the second term
_   _
   A + (A * B)

Invert
   
_ _
   A + (A*B)

Apply Demorgan's law once
_
   __   _
   A * (A * B)

and again for the second term
   _   
   A * (A + B)

Apply the distributive property:

   _ _
   A*A + A*B

The first term is always false, so we can drop it:
   _
   A*B

Now invert it again to cancel out the one we did back a few steps:

   ___
   _
   A*B

De Morgan one last time:
   _
   A + B
   
-- 
Grant Edwards   grant.b.edwardsYow! Xerox your lunch
  at   and file it under "sex
  gmail.comoffenders"!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Mark Lawrence

On 28/05/2015 23:39, Lew Pitcher wrote:

On Thursday May 28 2015 17:50, in comp.lang.c, "Skybuck Flying"
 wrote:


Hello,

I was just coding and ran into a little logic problem which is as follows:

There are two booleans/variables which can be either false or true.

The desired thrutle table is:

A = input
B = input
C = output

A B C:
---
F F T
F T F
T F T
T T T


Seems simple enough: C == A || !B

18:38 $ cat testlogic.c
#include 
#include 

/*
** A = input
** B = input
** C = output
**
** A B C:
** ---
** F F T
** F T F
** T F T
** T T T
*/

int testlogic(int a, int b)
{
   return (a || !b);
}

int main(void)
{
   /* A B C */
   int ttable[4][3] = {  {0,0,1},/* F F T */
 {0,1,0},/* F T F */
 {1,0,1},/* T F T */
 {1,1,1} /* T T T */
  };
   int rc = EXIT_SUCCESS;
   int i, max;

   for (i = 0, max = sizeof(ttable) / sizeof(ttable[0]); i < max ; ++i)
 if (testlogic(ttable[i][0],ttable[i][1]) != ttable[i][2])
 {
   printf("testlogic failed on test %d\n",i);
   rc = EXIT_FAILURE;
 }

   if (rc == EXIT_SUCCESS) puts("SUCCESS");

   return rc;
}
18:39 $ cc -o testlogic testlogic.c
18:39 $ ./testlogic
SUCCESS




Strangest looking Python I've ever seen.  Or is it a case of "Get thee 
behind me, Satan" :)


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Grant Edwards
On 2015-05-28, Grant Edwards  wrote:
> On 2015-05-28, Michael Torrie  wrote:
>> On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
>>> I think the logic you're really looking for is:
>>> 
>>> return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
>>
>> Yes this is the simplest form.
>
> Not really.
>
>
> In old school notation, that's
> ___
> A + A+B  
>
> [...]

That derivation was excessively round-about.  Here is the same thing
in fewer steps:

Invert:
 ___
 ___
 A + A+B  
 
De Morgan:
 _  
 A * (A + B)

Distribute:
 _ _
 A*A + A*B

Drop the null term:
  _
  A*B

Invert (to cancel out the first step)
  ___
  _
  A*B

De Morgan:
_
  A+B

-- 
Grant Edwards   grant.b.edwardsYow! I'm reporting for duty
  at   as a modern person.  I want
  gmail.comto do the Latin Hustle now!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re:

2015-05-28 Thread Néstor Boscán
Hola Yasna

Chris te escribe que puedes bajar la solución Python desde este link:

https://www.python.org/downloads/

También escribe que el foro es en inglés ya que la mayoría de las personas
que forman parte de la lista hablan inglés.

Saludos y éxitos

Translated:

Hi Yasna

Chris wrote that you can download Python from the following link:

https://www.python.org/downloads/

He also wrote that this forum is in english because the majority of the
people that are part of the list also speak english.

Regards

On Thu, May 28, 2015 at 6:20 PM, Chris Angelico  wrote:

> 2015-05-29 9:44 GMT+10:00 yasna araya :
> > hola, escribo para solicitar el uso del programa Python para trabajarlo
> con
> > mi hijo. desde ya muchas gracias
> >
> > Enviado desde Correo de Windows
>
> Hello!
>
> This is an English-language list, and most of the people here - myself
> included - are not fluent in Spanish. But you can download Python from
> here:
>
> https://www.python.org/downloads/
>
> If that wasn't what you were looking for, I apologize; possibly
> someone else here speaks better Spanish, or perhaps you could rephrase
> your question in English.
>
> All the best!
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


refer to xpath attributes generally

2015-05-28 Thread Sayth Renshaw
Is there a way to specify to all attributes in xpath? Instead of directly Eg 
//element/@attr

So that you could effectively loop and filter if an element had more than one 
Attribute?

So items = tree.xpath(@all_attrs)

>From lxml import etree 

Tree = etree.Xpath(//root)

For k, v in items:
Choose your k's


Thanks for your time in advance
Please forgive some formatting errors phone auto correct 
Sayth
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Paul

Skybuck Flying wrote:

Hello,

I was just coding and ran into a little logic problem which is as follows:

There are two booleans/variables which can be either false or true.

The desired thrutle table is:

A = input
B = input
C = output

A B C:
---
F F T
F T F
T F T
T T T

Surpisingly enough I don't think there is a casual/common operator for 
this thruth table.


AND does not apply.
OR does not apply.
XOR does not apply.

So I would need some combined operators to give the desired result.

I tried logic below... but funny enough it failed, now I feel like a 
noob lol and share this funny little fail logic with you.


Can you improve/fix the logic ?

This is python code, but this^ logic/thruth table problem basically 
applies to any programming language:


# loop has to run if:
# while DesiredResult==True:
# Desired truth table for BotWaitForCooldown and CooldownDetected
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# False   FalseTrue
# False   True False
# True FalseTrue
# True True True
# desired/suiting logic:
# (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))

def TestLogic( BotWaitForCooldown, CooldownDetected ):
return BotWaitForCooldown or ((not BotWaitForCooldown) and 
CooldownDetected) # this logic is flawed, please improve logic.


if TestLogic( False, False ) == True:
print "test 1 ok"
else:
print "test 1 failed"

if TestLogic( False, True ) == False:
print "test 2 ok"
else:
print "test 2 failed"

if TestLogic( True, False ) == True:
print "test 3 ok"
else:
print "test 3 failed"

if TestLogic( True, True ) == True:
print "test 4 ok"
else:
print "test 4 failed"

Bye,
 Skybuck.


If you ever have a really complicated truth table,
you can use Quine McCluskey minimization. At work, I
had no tool for minimizing boolean equations, so I got
some code from another engineer, code that ran on a
mainframe computer. And I converted the code to run
on a personal computer. The computers were so slow
back then, it might take ten to fifteen minutes to
minimize a ten variable truth table. On the mainframe
you could have a 2MB array for storage, whereas on my
personal computer at the time, the memory was segmented
and required some tricks to get enough.

http://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm

If it isn't a scam, the source code should be
reasonably short. The program I was using, might have
been on the order of 120 lines of source. This example
is a bit longer, and the couple programs I've been looking
at the source, I don't recognize what they're doing.

http://sourceforge.net/projects/mini-qmc/files/?source=navbar

Your problem isn't large enough to need this sort
of thing, but I thought I'd throw it in as a topic
of general interest. If it's one thing I've learned
over the years, hand-optimization of boolean equations
frequently leads to errors. And it's when you start
engaging your brain, and saying stuff like "I know the
answer", instead of sticking with your boolean algebra,
that errors creep in.

If you need a test case for your QM code, enter an
"XOR tree", as an XOR tree is irreducible and
should cough out the same info, as you entered in
the first place. That was one of my test cases,
when porting the code maybe 30 years ago. (And
no, I didn't keep a copy of the code. We didn't
do stuff like that back then. I didn't even have
a computer at home back then.)

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Denis McMahon
On Thu, 28 May 2015 14:58:19 -0700, sohcahtoa82 wrote:

> On Thursday, May 28, 2015 at 2:50:18 PM UTC-7, Skybuck Flying wrote:
>> Hello,

>> # Desired truth table for BotWaitForCooldown and CooldownDetected 
>> # BotWaitForCooldown:  CooldownDetected: Desired Result:
>> # FalseFalse True 
>> # FalseTrue  False 
>> # True False True 
>> # True True  True 

> I think the logic you're really looking for is:

> return BotWaitForCooldown or (not (BotWaitForCooldown or
> CooldownDetected))

Nope, it simplifies to:

BotWaitForCooldown or not CooldownDetected

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting an image from a file on windows

2015-05-28 Thread IronManMark20
Hello,

I have been working on a function that gets a bitmap of the thumbnail for a 
file. I have had problems getting a large image (256x256) and I was wondering 
if someone could help me on one object initialization that is driving me nuts.

I have code here: https://gist.github.com/IronManMark20/a83fe7ff7ea9b40c09af

I need to initialize a *void pointer for the third argument for SHGetImageList 
(ref https://msdn.microsoft.com/en-us/library/bb762185). 

What should the initialization look like (please give me example code, not just 
"Oh it should be a ctypes.c_void_p").

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread sohcahtoa82
On Thursday, May 28, 2015 at 3:17:10 PM UTC-7, Michael Torrie wrote:
> On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
> > I think the logic you're really looking for is:
> > 
> > return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
> 
> Yes this is the simplest form.  For more complicated truth tables you
> can create a K map and then apply a reduction algorithm to it.  This is
> commonly done in logic circuits to reduce the number of gates to the
> minimum.  While not faster, it can be expressed as:
> 
> return BotWaitForCooldown or not BotWaitForCooldown and not
> CooldownDectected
> 
> Order of operations puts the ands above the ors.

Order of operations might put the ands above the ors, but I still like using 
parentheses in expressions like that as I think it makes it more clear.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting an image from a file on windows

2015-05-28 Thread MRAB

On 2015-05-29 01:03, IronManMark20 wrote:

Hello,

I have been working on a function that gets a bitmap of the thumbnail
for a file. I have had problems getting a large image (256x256) and I
was wondering if someone could help me on one object initialization
that is driving me nuts.

I have code here:
https://gist.github.com/IronManMark20/a83fe7ff7ea9b40c09af

I need to initialize a *void pointer for the third argument for
SHGetImageList (ref
https://msdn.microsoft.com/en-us/library/bb762185).

What should the initialization look like (please give me example
code, not just "Oh it should be a ctypes.c_void_p").

Thanks!!!


Have you tried byref(hico)?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Michael Torrie
On 05/28/2015 05:03 PM, Grant Edwards wrote:
> On 2015-05-28, Grant Edwards  wrote:
>> On 2015-05-28, Michael Torrie  wrote:
>>> On 05/28/2015 03:58 PM, sohcahto...@gmail.com wrote:
 I think the logic you're really looking for is:

 return BotWaitForCooldown or (not (BotWaitForCooldown or CooldownDetected))
>>>
>>> Yes this is the simplest form.
>>
>> Not really.

True enough. My skills from EE are pretty rusty.


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


Re: Getting an image from a file on windows

2015-05-28 Thread IronManMark20
On Thursday, May 28, 2015 at 5:37:07 PM UTC-7, MRAB wrote:
> On 2015-05-29 01:03, IronManMark20 wrote:
> > Hello,
> >
> > I have been working on a function that gets a bitmap of the thumbnail
> > for a file. I have had problems getting a large image (256x256) and I
> > was wondering if someone could help me on one object initialization
> > that is driving me nuts.
> >
> > I have code here:
> > https://gist.github.com/IronManMark20/a83fe7ff7ea9b40c09af
> >
> > I need to initialize a *void pointer for the third argument for
> > SHGetImageList (ref
> > https://msdn.microsoft.com/en-us/library/bb762185).
> >
> > What should the initialization look like (please give me example
> > code, not just "Oh it should be a ctypes.c_void_p").
> >
> > Thanks!!!
> >
> Have you tried byref(hico)?

Thanks so much! That seems to have done it. Now I get to figure out how to get 
the image. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-05-28 Thread Steven D'Aprano
On Fri, 29 May 2015 01:01 am, Marko Rauhamaa wrote:

> Anssi Saari :
> 
>> Do you have an example of state pattern using nested classes and
>> python? With a quick look I didn't happen to find one in any language.
> 
> Here's an sampling from my mail server:


I haven't studied this in close detail, but first impressions is that this
is not well-written Python code. The obvious problems that come to mind:


> class SMTPServerConnection(ServerConnection):
> #: : :
> #: : :
> 
> def __init__(self, server, sock, domain, peer):
> super().__init__(server, sock)
> conn = self
> client_ip = peer[0]
> 
> class STATE:
> def __str__(self):
> return self.__class__.__name__

A minor criticism: each time you instantiate a new SMTP server connection,
it creates new STATE, IDLE etc. classes. That's wasteful and inefficient
unless you have a good reason for it, although you may not care if you only
have a single connection at a time.

More serious problem: by nesting the state classes, it is much harder to
test the state classes in isolation from a connection.


> def handle_command(self, cmd):
> conn.log("handle_command (unexpected): {}".format(cmd))
> assert False

At first glance, this appears to be an abuse of `assert` and risks breaking
your code when running under -O which turns debugging (and hence asserts)
off. Since the intent is to make these abstract methods which must be
overridden, I'd prefer to define an AbstractMethodError, then:

raise AbstractMethodError("unexpected %s" % cmd)

then do the logging elsewhere.

This has the advantage(?) of eliminating the need to refer to conn, which
means that the methods are no longer closures and the entire inner class
can be moved out of the SMTPServerConnection body.

[...]
> class IDLE(STATE):
> def handle_command(self, cmd):
> conn.log("handle_command: {}".format(cmd))

Using a closure for information hiding is a solid functional equivalent to
using private fields in an OOP context. However, "private" should be
considered an anti-testing idiom. I would seriously consider this entire
design to be an anti-pattern, and would prefer to one of two alternate
designs:

(1) Pull the state classes out of the SMTPServerConnection class. On
initialisation, each state takes a conn argument. All references to "conn"
are replaced by "self.conn". That's basically the conventional OOP
approach.

(2) Again, pull the state classes out of the SMTPServerConnection class,
except this time there is no need to instantiate the state classes at all!
Decorate all the methods with @classmethod, and have them take the
connection as an explicit argument. The caller (namely the
SMTPServerConnection  instance) provides itself as argument to the state
methods, like so:

self.state = IDLE  # No need to instantiate.
self.state.process_ehlo_or_helo(self, other, args, go, here)

This reduces implicit coupling, makes it explicit that the state methods
depend on the connection, avoids reference loops, and enables easy mocking
for testing.

The only downsides are that people coming from a conventional (e.g. Java)
OOP background will freak at seeing you using a class as a first class
value (pun intended), and it will be ever-so-slightly tiresome to have to
decorate each and every method with classmethod.

(Perhaps a class decorator is the solution to that second issue?)

The "design pattern" community is dominated by Java, where classes are not
values, so this idiom is impossible in Java and unlikely to have a DP name.
But it really should have one -- in a language where classes are themselves
values, there is no reason why a class *must* be instantiated, particularly
if you're only using a single instance of the class. Anyone ever come
across a named design pattern that involves using classes directly without
instantiating them?

I'm basically looking for a less inelegant term for "instanceless class" --
not so much a singleton as a zeroton.



-- 
Steven

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


Re: refer to xpath attributes generally

2015-05-28 Thread Sayth Renshaw
On Friday, 29 May 2015 09:21:01 UTC+10, Sayth Renshaw  wrote:
> Is there a way to specify to all attributes in xpath? Instead of directly Eg 
> //element/@attr
> 
> So that you could effectively loop and filter if an element had more than one 
> Attribute?
> 
> So items = tree.xpath(@all_attrs)
> 
> From lxml import etree 
> 
> Tree = etree.Xpath(//root)
> 
> For k, v in items:
> Choose your k's
> 
> 
> Thanks for your time in advance
> Please forgive some formatting errors phone auto correct 
> Sayth

It appears this is the best answer

n [17]: with open('C:/Users/Sayth/Desktop/20150530RHIL0.xml', 'rb') as f:
   : tree = etree.parse(f)
   : for attrResult in tree.xpath('/meeting/race/@*'):
   : print(attrResult.attrname)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying

Interestingly enough the shortest I have seen so far is ***:

def TestLogic( BotWaitForCooldown, CooldownDetected ):

# return BotWaitForCooldown or ((not BotWaitForCooldown) and 
CooldownDetected) # this logic is flawed, please improve logic.

# return (not ((not BotWaitForCooldown) and CooldownDetected)) # fixes it.
# return  (BotWaitForCooldown or (not CooldownDetected)) # optimization but 
looks weird :)
return (BotWaitForCooldown >= CooldownDetected) # *** even shorter, wow 
cool, thanks to Jussi Piitulainen


Apperently there is a short-coming/flaw in the reasoning about boolean 
logic, if boolean logic is converted to numbers/0/1 and comparisions allowed 
then apperently there are even shorter forms ?!? Am I correct ? Or am I 
missing something ? Perhaps branching don't count ? H. Is this 
branching ? Or something else... hmmm I think the comparison result 
could be used without requiring branching... so I think my conclusion might 
be correct.


Bye,
 Skybuck.

"Skybuck Flying"  wrote in message 
news:7b1ef$556792ab$5419aafe$58...@news.ziggo.nl...


Ok, problem solved for now, it seems:

I used video tutorial method and inverted it for the false case ;)

But anyway... I would not only need a "thruth table to logic/boolean
operations converter" but also a "boolean operations optimizer" ;)

# loop has to run if:
# while DesiredResult==True:
# Desired truth table for BotWaitForCooldown and CooldownDetected
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# False   FalseTrue
# False   True False
# True FalseTrue
# True True True
# desired/suiting logic:
# (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected))



def TestLogic( BotWaitForCooldown, CooldownDetected ):
# return BotWaitForCooldown or ((not BotWaitForCooldown) and
CooldownDetected) # this logic is flawed, please improve logic.
return (not ((not BotWaitForCooldown) and CooldownDetected))  # fixes it.

if TestLogic( False, False ) == True:
print "test 1 ok"
else:
print "test 1 failed"

if TestLogic( False, True ) == False:
print "test 2 ok"
else:
print "test 2 failed"

if TestLogic( True, False ) == True:
print "test 3 ok"
else:
print "test 3 failed"

if TestLogic( True, True ) == True:
print "test 4 ok"
else:
print "test 4 failed"

Bye,
 Skybuck.

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Skybuck Flying



"Denis McMahon"  wrote in message news:mk884e$gth$1...@dont-email.me... 


On Thu, 28 May 2015 14:58:19 -0700, sohcahtoa82 wrote:


On Thursday, May 28, 2015 at 2:50:18 PM UTC-7, Skybuck Flying wrote:

Hello,


# Desired truth table for BotWaitForCooldown and CooldownDetected 
# BotWaitForCooldown:  CooldownDetected: Desired Result:
# FalseFalse True 
# FalseTrue  False 
# True False True 
# True True  True 



I think the logic you're really looking for is:



return BotWaitForCooldown or (not (BotWaitForCooldown or
CooldownDetected))


"
Nope, it simplifies to:

BotWaitForCooldown or not CooldownDetected
"

Apperently it can be simplied even further:

BotWaitForCooldown >= CooldownDetected

Interesting isn't it ? :)

Bye,
 Skybuck.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table. (thruth table to logic/boolean operations generator sought/needed)

2015-05-28 Thread Skybuck Flying
I am not so sure anymore about my conclusion, I will investigate this 
further tomorrow.


It seems safe to conclude that at least the following operators have their 
own thruth tables:


=
<>



<

=

<=

These are the comparision operators.

Assume True is greater than False allows them to be used as well.

The question that remains is:

How many "gates" or "basic" operations or "wires" would they require.

Are some of these perhaps very "efficient" and could thus lead to even 
shorter gate designs ?


However for my purposes, reducing code, the answer is already: YES

For software logic/boolean reduction the answer is already YES, funny and 
interestingly enough ! ;) :)


Bye,
 Skybuck.



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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread random832
On Thu, May 28, 2015, at 17:50, Skybuck Flying wrote:
> Surpisingly enough I don't think there is a casual/common operator for
> this 
> thruth table.
> 
> AND does not apply.
> OR does not apply.
> XOR does not apply.

All sixteen possible logical operators have formal names. This one is
called "B implies A". It can be implemented, as others have mentioned
with "A or not B".

The possibility of spelling these with the comparison operators, as some
have suggested, is a consequence of Python's implementation where True
== 1 and False == 0. In other languages bool may not be relatable (or at
least not orderable), or False may be == -1.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting an image from a file on windows

2015-05-28 Thread IronManMark20
On Thursday, May 28, 2015 at 5:37:07 PM UTC-7, MRAB wrote:
> On 2015-05-29 01:03, IronManMark20 wrote:
> > Hello,
> >
> > I have been working on a function that gets a bitmap of the thumbnail
> > for a file. I have had problems getting a large image (256x256) and I
> > was wondering if someone could help me on one object initialization
> > that is driving me nuts.
> >
> > I have code here:
> > https://gist.github.com/IronManMark20/a83fe7ff7ea9b40c09af
> >
> > I need to initialize a *void pointer for the third argument for
> > SHGetImageList (ref
> > https://msdn.microsoft.com/en-us/library/bb762185).
> >
> > What should the initialization look like (please give me example
> > code, not just "Oh it should be a ctypes.c_void_p").
> >
> > Thanks!!!
> >
> Have you tried byref(hico)?

Could you suggest how I could get an hIcon from the newly drawn image? I have 
been trying, but I haven't found anything.
-- 
https://mail.python.org/mailman/listinfo/python-list


Fixing Python install on the Mac after running 'CleanMyMac'

2015-05-28 Thread Laura Creighton
webmas...@python.org just got some mail from some poor embarrased
soul who ran this program and broke their Python install.

They are running Mac OSX 10.7.5

They are getting:

 Utility has encountered a fatal error, and will now terminate.  A
 Python runtime could not be located. You may need to install a
 framework build of Python or edit the PyRuntimeLocations array in this
 applications info.plist file.  Then there are two oblong circles. One
 says Open Console. The other says Terminate.

So https://docs.python.org/2/using/mac.html says:

   The Apple-provided build of Python is installed in
   /System/Library/Frameworks/Python.framework and /usr/bin/python,
   respectively. You should never modify or delete these, as they are
   Apple-controlled and are used by Apple- or third-party software.

So, I assume this poor soul has done precisely that.

What do I tell her to do now?

Laura


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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Chris Angelico
On Fri, May 29, 2015 at 1:20 PM,   wrote:
> The possibility of spelling these with the comparison operators, as some
> have suggested, is a consequence of Python's implementation where True
> == 1 and False == 0. In other languages bool may not be relatable (or at
> least not orderable), or False may be == -1.

True. That said, though, using 0 for False and 1 for True is easily
the most common convention in use today, and the next most likely case
is that comparing booleans would give a simple and immediate error. So
it's most likely to be safe to do. Cross-language compatibility is a
tricky thing anyway; there are all sorts of odd edge cases, even with
otherwise-similar languages (Pike and Python, for instance, have
slightly different handling of slice ranges), so anything that's done
in Python is meant to be interpreted with Python semantics.

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Skybuck Flying

wrote in message news:mailman.152.1432869623.5151.python-l...@python.org...

On Thu, May 28, 2015, at 17:50, Skybuck Flying wrote:

Surpisingly enough I don't think there is a casual/common operator for
this
thruth table.

AND does not apply.
OR does not apply.
XOR does not apply.


"
All sixteen possible logical operators have formal names. This one is
called "B implies A". It can be implemented, as others have mentioned
with "A or not B".
"

Ok thanks for this information.

I was just wondering how many thruth table combinations there can be for a 
typical thruth table with 2 inputs and 1 output.


Since there are 2 inputs, this means 4 possible outputs, which means 2 to 
the power of 4 different thruth tables possible, which is indeed 16.


Perhaps you have a link to all possible 16 thruth tables and their formal 
names ? That would help !


Bye,
 Skybuck. 


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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Laura Creighton
You may be interested in PyEda
https://pypi.python.org/pypi/pyeda

It is for electronic design automation.  But it will minimise
truth tables for you.

http://pyeda.readthedocs.org/en/latest/search.html?q=truth+tables&check_keywords=yes&area=default

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


Re:

2015-05-28 Thread Mario R. Osorio
Chris. Este grupo es en Ingles. La verdad no se si existen grupos en español, 
pero juraria que si.

Entiendo que quieres enseñarle python a tu hijo. Aca te envio algunos recursos. 
Espero que te sirvan:

https://silvercorp.wordpress.com/2012/05/27/pasos-de-instalacion-de-python-en-windows/

http://www.slideshare.net/CAChemE/instalar-python-27-y-3-en-windows-anaconda

https://devcode.la/tutoriales/instalacion-de-python-27-en-windows-8/

http://codehero.co/python-desde-cero-instalacion-y-configuracion/

http://codehero.co/series/python-desde-cero.html

http://www.ehowenespanol.com/instalar-python-windows-como_44790/

https://www.youtube.com/watch?v=NEo4tDu6tU8

http://es.diveintopython.net/toc.html

http://mundogeek.net/tutorial-python/

http://pyspanishdoc.sourceforge.net/index.html

https://www.youtube.com/watch?v=GbfXj0iQQH0

https://www.youtube.com/watch?v=W7xZvUQhQWg

https://www.youtube.com/watch?v=DVD17s7hAj8
-- 
https://mail.python.org/mailman/listinfo/python-list


[no subject]

2015-05-28 Thread Laura Creighton
Sabe usted acerca de estas páginas?
https://mail.python.org/mailman/listinfo/python-es
https://wiki.python.org/moin/SpanishLanguage

Laura


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


Re: should "self" be changed?

2015-05-28 Thread Steven D'Aprano
On Fri, 29 May 2015 12:00 pm, Steven D'Aprano wrote:

> I haven't studied this in close detail, but first impressions is that this
> is not well-written Python code. The obvious problems that come to mind:

Well, first impressions can be misleading... I wrote the above, thinking
that there were more problems with the code than there actually are.
(Specifically, I didn't notice that the inner classes used closures for
their methods, then forgot to go back and revise that sentence.) So the
code actually was not as bad as I first thought, not withstanding the
issues that I described in my previous post.



-- 
Steven

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


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Steven D'Aprano
On Fri, 29 May 2015 01:49 pm, Skybuck Flying wrote:

> wrote in message
> news:mailman.152.1432869623.5151.python-l...@python.org...
> 
> On Thu, May 28, 2015, at 17:50, Skybuck Flying wrote:
>> Surpisingly enough I don't think there is a casual/common operator for
>> this
>> thruth table.
>>
>> AND does not apply.
>> OR does not apply.
>> XOR does not apply.
> 
> "
> All sixteen possible logical operators have formal names. This one is
> called "B implies A". It can be implemented, as others have mentioned
> with "A or not B".
> "
> 
> Ok thanks for this information.
> 
> I was just wondering how many thruth table combinations there can be for a
> typical thruth table with 2 inputs and 1 output.

The word is TRUTH not THRUTH. I don't know if you're a native English
speaker, but "thruth" sounds like the name of a bird (thrush) spoken with a
lisp.

> Since there are 2 inputs, this means 4 possible outputs, which means 2 to
> the power of 4 different thruth tables possible, which is indeed 16.
> 
> Perhaps you have a link to all possible 16 thruth tables and their formal
> names ? That would help !

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




-- 
Steven

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


Re: Fixing Python install on the Mac after running 'CleanMyMac'

2015-05-28 Thread Ned Deily
In article <201505290347.t4t3lyjc006...@fido.openend.se>,
 Laura Creighton  wrote:
> webmas...@python.org just got some mail from some poor embarrased
> soul who ran this program and broke their Python install.
> 
> They are running Mac OSX 10.7.5
> 
> They are getting:
> 
>  Utility has encountered a fatal error, and will now terminate.  A
>  Python runtime could not be located. You may need to install a
>  framework build of Python or edit the PyRuntimeLocations array in this
>  applications info.plist file.  Then there are two oblong circles. One
>  says Open Console. The other says Terminate.
> 
> So https://docs.python.org/2/using/mac.html says:
> 
>The Apple-provided build of Python is installed in
>/System/Library/Frameworks/Python.framework and /usr/bin/python,
>respectively. You should never modify or delete these, as they are
>Apple-controlled and are used by Apple- or third-party software.
> 
> So, I assume this poor soul has done precisely that.
> 
> What do I tell her to do now?

It would be helpful to know what utility it is that is encountering the 
fatal error; that message is not familiar and I suspect it is coming 
from trying to run some third-party application.  It may be that the 
application was depending on a third-party framework installation of 
Python (in /Library/Frameworks rather than the system Python in 
/System/Library/Frameworks), such as provided by the python.org OS X 
installers, but without knowing more information, like what particular 
version of Python is needed, it would only be speculation.  Perhaps the 
best thing to do is to suggest the OP to participate directly here or an 
Apple users' forum like http://apple.stackexchange.com.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Creating a reliable sandboxed Python environment

2015-05-28 Thread Stefan Behnel
Chris Angelico schrieb am 28.05.2015 um 20:51:
> On Fri, May 29, 2015 at 4:41 AM, Stefan Behnel wrote:
>> davidf...@gmail.com schrieb am 26.05.2015 um 04:24:
>>> Has anyone on this list attempted to sandbox Python programs in a
>>> serious fashion? I'd be interested to hear your approach.
>>
>> Not quite sandboxing Python, but I've seen people use my Lupa [1] library
>> for this. They're writing all their code in Python, and then let users
>> embed their own Lua code into it to script their API. The Lua runtime is
>> apparently quite good at sandboxing, and it's really small, just some 600KB
>> or so. Lupa then lets you easily control the access to your Python code at
>> a whitelist level by intercepting all Python attribute lookups.
>>
>> It doesn't add much to your application to embed Lua (or even LuaJIT) in
>> Python, and it gives users a nicely object oriented language to call and
>> orchestrate your Python objects.
> 
> Lua's a much weaker language than Python is, though. Can it handle
> arbitrary-precision integers? Unicode? Dare I even ask,
> arbitrary-precision rationals (fractions.Fraction)?

All of those and way more, as long as you use it embedded in Python.


> Security comes at a price, I guess.

Sure, but features aren't the price here.

Stefan


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