mardi 4 août 2015

Print series of lists with aligned columns

I have a function that is passed a list of ints, and the desired row length. It is assumed that the length of the data is evenly divisible by the row length. All the ints in the list represent bytes, so they are no longer than 3 digits, and no smaller than 0. Here is my function:

    def pprint(data, rowlen):
    # Prints out the list in a nice grid format
    print '-' * 50
    for index in range(0, len(data), rowlen):
        print data[index:(index+rowlen)]
    print '-' * 50
    return data

The output looks something like this:

[0, 0, 2, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0, 0]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0, 0, 0, 0, 0, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0]

As you can see, this sort of works, but I'd like something more like this:

[0  , 0  , 2  , 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0  , 0  ]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0  , 0  , 0  , 0  , 0  , 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139]
[139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 0  ]

That way, all the data is aligned in a grid format and it is easy to see where everything is.

Is there an easy way to achieve this without having to iterate through every entry and inserting spaces.



via Chebli Mohamed

TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given

I have hit a problem with one of the examples in the book Beginning Python Games Development Second Edition.

It has me setting up a vector class (full code at the end of the Q) with the following __init__ function:

def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

It then asks me to run this code snippet against it:

from Vector2 import *

A = (10.0, 20,0)
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
step = AB * .1
position = Vector2(A, B)
step = AB * .1
print(*A)
position = Vector2(*A)
for n in range(10):
    position += step
    print(position)

The result is the following error:

Traceback (most recent call last):
  File "C:/Users/Charles Jr/Dropbox/Python/5-14 calculating positions.py", line 10, in <module>
    position = Vector2(*A)
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given

When I put a print on the *A, it comes up as just 2 numbers, as you would expect. Why is it somehow turning this into 4?

Full Vector2 code:

import math

class Vector2:

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)

    def from_points(P1, P2):
        print("foo")
        return Vector2( P2[0] - P1[0], P2[1] - P1[1])

    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )

    def normalise(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

    # rhs stands for right hand side
    def __add__(self, rhs):
        return Vector2(self.x + rhs.x, self.y + rhs.y)

    def __sub__(self, rhs):
        return Vector2(self.x - rhs.x, self.y - rhs.y)

    def __neg__(self):
        return Vector2(-self.x, -self.y)

    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)

    def __truediv__(self, scalar):
        return Vector2(self.x / scalar, self.y / scalar)



via Chebli Mohamed

hash() in Python [duplicate]

This question already has an answer here:

How does hash function works in Python? Why is hash('\0b') = hash('\0\0c') even though '\0b' is not equal to '\0\0c'?

>>>print hash('\0b') == hash('\0\0c')
True
>>>print hash('\0b'),hash('\0\0c'),hash('\0\0\0d'),hash('\0\0\0\0e')
96 96 96 96



via Chebli Mohamed

"Start External Program" Debugging option not appearing in VS

I'm trying to run my python script in debug mode via ArcMap. I tried to follow instructions here, but when I get to the debug window, I don't see and option for "Start External Program". What's up with that?

Btw, using VS'13.



via Chebli Mohamed

Execute Python script from Php

I have a PHP webpage on my raspberry pi with 2 buttons (on and off) The on button button redirects to On.php The off button redirects to Off.php In "/usr/lib/cgi-bin" I have a python script that I would like to execute (script.py) I can perfectly execute it from the terminal by typing

cd /usr/lib/cgi-bin
sudo python script.py

It works if I do it from the terminal.

The problem is the PHP file (On.php) in my "/var/www" folder. This is what I wrote:

<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>

Why is the script executing from the terminal, but not from my PHP?



via Chebli Mohamed

python - unable to add image to the GUI(tkinter) on windows

I am using python( my version is 2.7 ). I want to add an image to GUI (Tkinter) and then convert into executable format using pyinstaller. I did followed as on SO, and also as said on ActiveState

When i mention the image's path on the code, it works only if i run it directly. If i convert it to exe it doesnt open.

Changing the code as mentioned from other solutions, like by converting it into encoded string, it runs fine on linux. But on windows it throws error

code:

from Tkinter import *
from PIL import ImageTk, Image

logo = '''
----- encoded string -----
'''

root = Tk()
logoimage = Tkinter.PhotoImage(master=root, data=logo)
Label(root, image=logoimage).pack()
root.mainloop()

Change 1: The above code works on linux. On windows i get error on the line logoimage = Tkinter.PhotoImage(master=root, data=logo) as

NameError: name 'Tkinter' is not defined

Change 2: So i tries changing the line as logoimage = ImageTk.PhotoImage(master=root, data=logo). The error i get is

File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 88, in __init__
    image = Image.open(BytesIO(kw["data"]))
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2330, in open
    % (filename if filename else fp))
IOError: cannot identify image file <_io.BytesIO object at 0x00000000024BB150>
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage object at 0x00000000024D49E8>> ignored

Change 3: But, if i change the line as iconImage= ImageTk.PhotoImage(Image.open('path_to_image.png')). It works only if i run directly. If i convert it to executable, then console opens for 2-3 seconds and displaying error something like Unable to locate the image file



via Chebli Mohamed

What is a Pythonic way for Dependency Injection?

Introduction

For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a class that implements the defined interface.

Now for Python, you are able to do the same way, but I think that method was too much overhead right in case of Python. So then how would you implement it in the Pythonic way?

Use Case

Say this is the framework code:

class FrameworkClass():
    def __init__(self, ...):
        ...

    def do_the_job(self, ...):
        # some stuff
        # depending on some external function

The Basic Approach

The most naive (and maybe the best) way is to require the external function to be supplied into the FrameworkClass constructor, and then be invoked from the do_the_job method.

Framework Code:

class FrameworkClass():
    def __init__(self, func):
        self.func = func

    def do_the_job(self, ...):
        # some stuff
        self.func(...)

Client Code:

def my_func():
    # my implementation

framework_instance = FrameworkClass(my_func)
framework_instance.do_the_job(...)

Question

The question is short. Is there any better Pythonic way to do this?



via Chebli Mohamed