Wednesday, 10 July 2013

screen capture on Linux

There are many different ways to do a screen capture of the desktop using various command line utilities which grab a portion of the display such as ImageMagick or utilise built-in functionality of the Window Manager being used. However, I have discovered another cool command line tool to do this called scrot.

With it you can do the usual create an image of the desktop after a certain length of time, but the features I have found useful are the ability to select an area of the screen to save (-s option) and the ability to execute a command on the saved image (-e option).

e.g.
scrot -s <new image file> -e 'gpicview %f'

From the example, scrot also can use some format specifiers for -e and filename options, here I use %f to get the filename.

It would be easy to add a scrot command to scripts for easy quick screen capture.

Tuesday, 9 July 2013

Fun with Fractals

I saw an article on drawing fractals (Julia sets) using the Scratch programming language so I thought I would have a go at doing this in python using the pygame libraries. Program at the bottom of the page.

While playing around with the code and testing different values I came up with some pretty cool images. The first few attempts had it painting black pixels when they should have been coloured.

first test image (incorrect code)
first image zoomed x axis

experimenting with colours
different colours


Favourite colour selection
random 

looks like a chinese dragon
Filled Julia set for c=-1+0.1*i




#!/usr/bin/python

import os, pygame, sys;

from pygame.locals import *

def main():

    pygame.init()

    #set environment variable for SDL to position screen
    os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

    pygame.display.set_caption(os.path.split(os.path.abspath(__file__))[01])

    #windowed mode, 500x500, automatic colour depth
    screen = pygame.display.set_mode([500,500],0,0)

    #equation c=-0.7467+0.3515i
    #some default values
    #c_real = -0.1
    #c_im = 0.651
    c_real = -0.7467

    c_im = 0.3515
    max_It = 20
    col_offset= 5
    x_zoom = 3
    y_zoom = 1
    normalise=255.0/max_It

    #filename to store generated image
    filename='fractal-'+str(os.getpid())+'.png'

    screen.fill((255,255,255))
    pygame.display.flip()

    x = 0
    while x < 200:
        y= 0
        while y < 180:
           z_re = 1.5*(x - 200)/ (0.5 *x_zoom*200)
           z_im = (y - 180 / 2)/(0.5 * y_zoom *180)
           zi2 = z_im*z_im
           zr2 = z_re*z_re
           iterations = 0
           for iterations in range (0, max_It):

           zi = z_im*z_re
                z_re=(zr2-zi2)+c_real
                z_im=(2*zi)+c_im
                zi2 = z_im*z_im
                zr2=z_re*z_re
                iterations+=1
                if (zi2+zr2 >4):
                    break
           print('iterations=%d'%iterations)
           #convert iterations to a colour value [0-255]
           colour=iterations*normalise
           #if zi*zi + zr2*zr2 stays below 4 uptill max iterations, it has
           #'escaped' and pixel is painted black, otherwise paint with 'colour'
           if iterations >= max_It:
                print('colour=black')
                pygame.draw.line(screen, (0,0,0),(x,y),(x,y))
           else:
                print('colour=%d'%colour)
                pygame.draw.line(screen, (255-colour,colour,colour),(x,y),(x,y))
           pygame.display.flip()
           y+=1
        x+=1

    print('fractal drawn')
    while True:
        #exit for loop, e.g. close window
        for event in pygame.event.get():
           if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.image.save(screen, filename)
        pygame.time.wait(10000)

if __name__ == '__main__':
    main()

Friday, 5 July 2013

Remember to define functions before trying to use them...

I was going over a sample piece of C code and I could not understand why it compiled without errors yet did not seem to function as expected.
After a while of head scratching and double checking my code with the listing provided (it was identical), I came to the conclusion that the listing was wrong so I enabled warnings in gcc (-Wall) and up popped the problem.

The error was
testhist.c: In function ‘main’:
testhist.c:9:4: warning: implicit declaration of function ‘initHist’ [-Wimplicit-function-declaration]


So we had an implicit function declared. It appears the original programmer had forgotten to define the function in their header file, doh!
Putting this in solved the issue.

Rather than turn on all warnings I could have just enabled the implicit declaration of function warning (-Wimplicit-function-declaration).

Another point to remember is don't assume the programmer knew what they were doing.

Wednesday, 3 July 2013

Removing files via inode number

While trying out some code, I accidentally created some files containing meta characters in the filename, which in turn causes problems if you want to remove them. So I dug out an old script I wrote many years ago to delete the file using its inode number. The script has absolutely no error handling or sanitisation, use at your own risk.

#!/bin/bash

inum=$1
echo "Inode: $1"

echo "remove `ls -i | grep $inum`"
rm `ls -i | grep $inum | awk '{ print $2 }' `

sysinfo()

I was reminded in an article about sysinfo() on Linux, also gave me a change to remind myself of some basic C programming principles, e.g. bitwise shifts.

#include <stdio.h>
#include <sys/sysinfo.h>


int main() {
   struct sysinfo info;
   float todivideby = 0.00;
   sysinfo(&info);
   printf("Uptime (s) = %ld\n",info.uptime);
   printf("SI_LOAD_SHIFT = %d\n", SI_LOAD_SHIFT);
   todivideby = 1<<SI_LOAD_SHIFT;
   //printf("divide by: %.2f\n", todivideby);
   printf("Load Averages %.2f,%.2f,%.2f\n",info.loads[0]/todivideby, info.loads[1]/todivideby, info.loads[2]/todivideby);
   printf("Totalram = %ld memory units\n",info.totalram);
   printf("Freeram = %ld memory units\n",info.freeram);
   printf("Memory used = %ld memory units\n", info.totalram - info.freeram);
   printf("Sharedram = %ld memory units\n",info.sharedram);
   printf("bufferram = %ld memory units\n",info.bufferram);
   printf("totalswap = %ld memory units\n",info.totalswap);
   printf("freeswap = %ld memory units\n",info.freeswap);
   printf("totalhigh = %ld memory units\n",info.totalhigh);
   printf("freehigh = %ld memory units\n",info.freehigh);
   printf("Memory unit = %d bytes\n", info.mem_unit);
   printf("Number of procs = %d\n", info.procs);
   return 0;
}

Tuesday, 2 July 2013

Learning Ada

I saw an article today about Ada which I have not looked at before, so I decided to try and write a couple of simple programs. It was not that difficult to write some very basic programs having seen Pascal and Oberon before.
The source code is stored in files matching the procedure name and ending in .adb "Ada Body" and to compile them I used gnatmake <filename>.
gnatmake is part of GNAT compiler tools and appears to be a front end to gcc.

Compulsory Hello World program

with Ada.Text_IO;
use Ada.Text_IO;

procedure Hello is
begin
  Put_Line("Hello World");
end Hello;



Program with Basic I/O (plus comments so I don't forget)

with Ada.Text_IO;
use Ada.Text_IO;
--following lines are needed for unbound string
with Ada.Strings.Unbounded;
use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO;
use Ada.Strings.Unbounded.Text_IO;

procedure input is
   Buffer : Unbounded_String;
   --fixed length string
   --S: String(1..10) := (others => ' ');
   --Last: Natural;
begin
   Put("enter some text: ");
   --read in a fixed length string
   --Get_Line(S, Last);
   --read in entire line, careful what is done with it
   Buffer := get_line;
   --output our fixed length string, input truncated
   --Put_Line("text entered: " & S);
   --output unbound string
   Put_Line("text entered: " & Buffer);


end input;

 Note: Lines that start "--" are comments.

Simple animated graphic using pygame

Re-implementation of an exercise that was given to some university students while I worked there, the original was implemented as a Java applet using 2D graphics. I was looking at the pygame libraries and decided to test this out on the RaspberryPi, there are plenty of improvements that could be made, but the libraries seem easy to pick up.

#!/usr/bin/python
#
# draw castle shape using pygame library
# animate castle around the screen, including collision detction of borders
#

import os,pygame,sys

from pygame.locals import *


def main():

    pygame.init()

    #set environment variable for SDL to position screen
    os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

    pygame.display.set_caption(os.path.split(os.path.abspath(__file__))[01])

    #windowed mode, 400x200, automatic colour depth
    screen = pygame.display.set_mode([400,200],0,0)

   #fullscreen mode, same size as screen resolution, auto colour depth
   #screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN,0)

    size = screen.get_size()

    points = [[0,50],[60,50],[60,20],[50,20],[50,30],[40,30],[40,20],[30,20],[30,30],[20,30],[20,10],[10,0],[0,10]]
    points2 = [[50,100],[110,100],[100,70],[100,70],[100,80],[90,80],[90,70],[80,70],[80,80],[70,80],[70,60],[60,50],[50,60]]

    bgcolour = [255,255,255]

    castleSurf = pygame.Surface((60,50))
    castleSurf.set_colorkey((0,0,0))
    pygame.draw.polygon(castleSurf, (0,255,0), points)

    x = 0
    y = 0
    positivex = 1
    positivey = 1

    while True:

       #exit for loop, e.g. close window
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
               if event.key == pygame.K_q:
                  pygame.quit()
                  sys.exit()
            if event.type == pygame.QUIT:
               pygame.quit()
               sys.exit()

        screen.fill(bgcolour)

        #debug
        #print x,y,positivex,positivey

        screen.blit(castleSurf,(x,y))

        pygame.display.flip()

        pygame.time.wait(60)

        #move bounding rectancle and collision detection
        #print size[0], size[1]

        if positivex:
           if (x+60)>=size[0]:
                positivex=0
                x-=5
           else:
                x+=5
        else:
           if x<=0:
                positivex=1
                x+=5
           else:
                x-=5  

        if positivey:
           if (y+50)>=size[1]:
                positivey=0
                y-=5
           else:
                y+=5
        else:
           if y<=0:
                positivey=1


if __name__ == '__main__':
    main()