Archive

Archive for March, 2012

autopy

March 26, 2012 Leave a comment

autopy is a simple, cross-platform GUI automation toolkit for Python

Installation

sudo apt-get install libxtst-dev
sudo pip install autopy

Some mouse actions

import time
import autopy as ap
from autopy.mouse import LEFT_BUTTON

def leftClick():
    ap.mouse.click(LEFT_BUTTON)
    time.sleep(.1)
    print "# click"
    
def leftDown():
    ap.mouse.toggle(True, LEFT_BUTTON)
    time.sleep(.1)
    print '# left down'

def leftUp():
    ap.mouse.toggle(False, LEFT_BUTTON)
    time.sleep(.1)
    print '# left release'
    
#############################################################################
    
if __name__ == "__main__":
    time.sleep(1)
    leftClick()
    leftDown()
    time.sleep(3)
    leftUp()

Related work (20130903)

See also pyrobot: @github, @reddit. Note that pyrobot is for Windows only.

Categories: python, windows Tags: , ,

Generate the lexicographically next permutation of a sequence

March 21, 2012 Leave a comment

Problem
You have the permutation of some elements and you want to generate its lexicographically next permutation.

Example
Take the elements [a,b,c]. Their permutations in lexicographical order:

['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
['c', 'b', 'a']

Let’s compare ‘abc‘ and ‘acb‘. Their first characters (‘a‘) are the same. Now compare the second characters: since ‘b‘ < 'c‘, ‘abc‘ is lexicographically smaller than ‘acb‘.

Algorithm

#!/usr/bin/env python

"""
Generate the lexicographically next permutation of a sequence
of elements.

Pseudo-code:

1. Find the largest index k such that a[k] < a[k + 1]. 
   If no such index exists, the permutation is the last permutation.
2. Find the largest index l such that a[k] < a[l]. 
   Since k + 1 is such an index, l is well defined and satisfies k < l.
3. Swap a[k] with a[l].
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

# from jabbapylib.math import permutation as perm
"""

def lexicographically_next_permutation(a):
    """
    Generates the lexicographically next permutation.
    
    Input: a permutation, called "a". This method modifies
    "a" in place. Returns True if we could generate a next
    permutation. Returns False if it was the last permutation
    lexicographically.
    """
    i = len(a) - 2
    while not (i < 0 or a[i] < a[i+1]):
        i -= 1
    if i < 0:
        return False
    # else
    j = len(a) - 1
    while not (a[j] > a[i]):
        j -= 1
    a[i], a[j] = a[j], a[i]        # swap
    a[i+1:] = reversed(a[i+1:])    # reverse elements from position i+1 till the end of the sequence
    return True

#############################################################################

if __name__ == "__main__":
    li = ['a', 'b', 'c']
    print li    # process
    while lexicographically_next_permutation(li):
        print li    # process

This code is part of my jabbapylib library.

Reverse a part (slice) of a list

March 21, 2012 Leave a comment

Problem
You have a list and you want to reverse a part (slice) of it.

Solution
Let our list be [1,2,9,6,5] and say we want to reverse its end from element 9, i.e. we want to get [1,2,5,6,9].

a = [1,2,9,6,5]
i = 2    # reverse from this index position
j = 4    # reverse until this index position (included)
a[i:j+1] = reversed(a[i:j+1])
print a    # [1, 2, 5, 6, 9]
Categories: python Tags: ,

amix’s blog

March 20, 2012 Leave a comment

I just found amix’s blog. He has several interesting Python posts, worth checking out.

Categories: python

pyp – Python Power at the Prompt (The Pyed Piper)

March 17, 2012 Leave a comment

Pyp is a Linux command-line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment. Pyed Pyper was developed at Sony Pictures Imageworks to facilitate the construction of complex image manipulation “one-liner” commands during visual effects work on Alice in Wonderland, Green Lantern, and the upcoming The Amazing Spiderman.” (source)

Installable via jabbatron.

This post is a reminder for me. As soon as I go through its documentation, I will write some notes about it.

Categories: python Tags: , , ,

Elite Planet Name Generator

March 6, 2012 Leave a comment

Elite is a seminal space trading video game, originally published by Acornsoft in 1984 for the BBC Micro and Acorn Electron computers. The game’s title derives from one of the player’s goals of raising their combat rating to the exalted heights of ‘Elite’. It was written and developed by David Braben and Ian Bell.” (source)

I met Elite as a child when I had a Commodore Plus/4. I also tried it on my Commodore 64 later but I could never play with it :) This game was a mystery for me: I didn’t know what to do, and when I tried to shoot another ship, I got killed in no time.

Several years passed… About two years ago I came across this blog post (in Hungarian) and I gave it another try. I downloaded a modern version of Elite called Oolite and I couldn’t stop playing for two weeks… This game is truly amazing.

I’ve read that all planet information (name, description, etc.) was generated since the creators only had 32 KByte RAM available. I was always interested in this name generator and finally I could find a Python implementation of the algorithm.

At http://automaticromantic.com/static/misc/pytxtelite.txt you can find a command-line version of Elite. pytxtelite, written by Ian Sparks, is a Python conversion of Ian Bell’s txtelite.c 1.2 (and parts of 1.4), containing the trading engine of the game. Since this includes the name generator (besides lots of other things), I decided to remove everything from it except the name generator part.

The result is available here.

Thanks Füli for the link of pytxtelite.

Categories: python Tags: , ,

call python in a shell script

March 5, 2012 Leave a comment

Problem
Floating point arithmetic in bash is problematic, expr supports integers only for instance.

Solution
Not an optimal solution but it works:

$ python -c "print 5.5*3"
16.5

$ num=`python -c "print 5.5*3"`
$ echo $num
16.5
Categories: python Tags: ,