Switch Host – local/remote hostname lookup

April 27th, 2009

Switch_host is a tool that let you handle and configure a hostname lookup. Configuring the makefile, you tell switch_host what is the IP address to work with.
Switch_host is useful when you have a local server, and you want to use it either when you are at home or when you are out. Instead of modifing /etc/hosts by hand, switch_host will do it for you.

Usage: switch_host [options]

Options:
-a | --actual      Show current setting
-d | --dynamic     Set dynamic host
-h | --help        Print this message
-s | --static      Set static host

Check out the README file for any helps.

Follow the project in the repository under the name: switch_host.

Hotkeysd – hotkeys daemon

April 27th, 2009

Running dwm, i needed a piece of code for the management of fn-keys. So i ended with a client/daemon application capable of doing stuff such as disabling wifi, toggle the lvds backlight, increase/decrease volume ecc ecc. The communication method is always the same: a shared fifo placed in /tmp.
Because of the need of running commands with root privileges, i added a small c launcher (hotkeys_launcher), which makes use of the ’s’ bit for invoking the daemon as super-user.
In order to use the scripts you need these programs: xrandr, amixer, xbacklight, system_info (previous post), osdc/osdd (previous post), hibernate, hibernate-ram.
Just for taste, here is the help message displayed with the client-side app:

usage: hotkeysc [option]

option:
B+	increase brightness
B-	decrease brightness
Bt	turn off/on brightness
G	change cpu governor
H	hybernate
h	print this message
I	displays general informations (cpu-load, temperature..)
M	switch to external monitor
R	restart the daemon
S	suspend
Td	disable trackpad
Te	enable trackpad
V+	increase volume level
V-	decrease volume level
Wt	enable/disable wifi interface

Before using the launcher inside your .xinitrc file, try the daemon in a shell in order to debug errors due to programs not found ecc ecc.
Here is my .xbindkeysrc file configured for hotkeysc/d:

# Brightness Up
"hotkeysc B+"
	m:0x0 + c:233
	XF86MonBrightnessUp

# Brightness Down
"hotkeysc B-"
	m:0x0 + c:232
	XF86MonBrightnessDown

# Brightness Toggle
"hotkeysc Bt"
	m:0x0 + c:156
	XF86Launch1

# Governor
(xbindkey "hotkeysc G")
	m:0x0 + c:210
	XF86Launch3

# Info
(xbindkey "hotkeysc I")
	m:0x0 + c:244
	NoSymbol

# Monitor switch
(xbindkey "hotkeysc M")
	m:0x0 + c:235
	XF86Display

#--------------------------------------------------
# # Suspend
# (xbindkey "hotkeysc S")
# m:0x0 + c:223
#-------------------------------------------------- 

# Trackpad toggle
xbindkey "hotkeysc Tt")
	m:0x0 + c:200
	NoSymbol

# Volume Up
"hotkeysc V+"
	m:0x0 + c:123
	XF86AudioRaiseVolume

# Volume Down
"hotkeysc V-"
	m:0x0 + c:122
	XF86AudioLowerVolume

# Volume Toggle
"hotkeysc Vt"
	m:0x0 + c:121
	XF86AudioMute

# Wifi toggle
(xbindkey "hotkeysc Wt")
	m:0x0 + c:246
	NoSymbol

You can grab the source from the repository under the project name hotkeysd.

OSDD – on screen display daemon

April 26th, 2009

While working with minimal windows manager (awesome, dwm), i created a simple client/daemon system useful for showing text on screen; i used it for temperature, cpu-usage, battery life remaining and stuff like that.
The communication system is based on a fifo placed by default in /tmp directory.
The daemon (osdd) could be invoked with some options that let you configure the appeal of the window.
The client is invoked considering that each argument will be printed on screen as a new line, i mean:

$ osdc "first line" "second line" foo3 foo4

has as effect an osd message composed by 4 lines.

You can get the sources from the repository: project name osdd.

System info from command-line

April 26th, 2009

I often had come into the need of knowing informations from the running system (i.e. cpu load, memory usage or temperature).
One for all, i wrote down a script that collects few fuctions for grabbing these infos from the linux proc/sys file-system.
Remember to edit the script before the installation, in order to match your needs.

Usage: /usr/bin/system_info [-bdhlmnt]
    -b    prints battery info
    -d    prints date
    -h    prints this help
    -l    prints system load
    -m    prints memory usage
    -n    prints network stats
    -t    prints temperature

Take it from the svn repository: the project name is system_info.

Wordpress: avoid texturizer

April 25th, 2009

Texturizer is a wordpress tool that give your post a sexier appealing.
Because of my frequent use of pre/code html tags for posting code, i decided to disable this wp feature: here is a small diff to show you how to achieve that.

--- wp-includes/formatting.php.old  2009-04-25 13:28:24.000000000 +0200
+++ wp-includes/formatting.php      2009-04-25 13:28:55.000000000 +0200
@@ -41,7 +41,7 @@
                $output .= $curl;
        }

-       return $output;
+       return $text;
 }

 // Accepts matches array from preg_replace_callback in wpautop()

Hope it is helpful for someone!

Synaptics patch for Samsung NC10

February 25th, 2009

Here is a small patch for make the NC10’s touchpad a bit more comfortable.
There is still something to edit, but for the moment it’s kinda ok.

--- old/synaptics.c	2009-02-25 13:40:26.000000000 +0100
+++ new/synaptics.c	2009-02-25 15:39:40.000000000 +0100
@@ -1299,7 +1299,7 @@
     }

     *dxP = dx;
-    *dyP = dy;
+    *dyP = dy < 2 && dy > 0 ? 1 : dy > -2 && dy < 0 ? -1 : dy*.5;

     /* generate a history of the absolute positions */
     store_history(priv, hw->x, hw->y, hw->millis);

I would like to thank Slacy’s Blog: he suggested to put a `hw.y *= 0.6′ inside the loop event handler, but i noticed that doing so my edge orizontal scroll was gone.
After playing a bit with the code, i found the above solution. I hope it could help someone!

Update:
the latest drivers from debian’s unstable repository seem to fix the problem.

Webcam viewer

January 3rd, 2009

Basic webcam viewer written in python + gtk + gstreamer.
I spent time making the gst pipe to work properly because I was finding a way to both display the stream on the screen and analyze it.
The latter would be interesting because of the use one can do with it in terms of patter recognition or motion tracking (maybe one day ..).
Anyway here is the resulting gst-pipe even tought only the first branch is implemented in the script below:

v4l2sr
|
ccaps(image/jpeg)
|
videoflip
|
videobalance
|
tee-------------+
|               |
queue1          ffmpegcolorspace
|               |
xvimagesink     caps(video/xraw-rgb)
                |
                fakesink

Implemented pipe:

v4l2sr ---> ccaps(image/jpeg) ---> videoflip ---> videobalance ---> xvimagesink

The script contains few hardcoded settings such as device number, width .. You can manipulate these during application startup:
let’s suppose i want to display /dev/video2 with a resolution of 640×480 pixels and a framerate of 15fps:

$ python webcam.py 2 640 480 15

Attention: the script doesn’t check whether the device exists or it supports the specified settings.
Here is the code:

#!/usr/bin/env python

import sys
import gtk
import gst

# Webcam settings
DEVICE = 0
WIDTH = 320
HEIGHT = 240
FRAMERATE = 15

# Widget params
VIDEO_PROPERTIES = [("contrast", 0, 2, 1),
                ("brightness", -1, 1, 0),
                ("hue", -1, 1, 0),
                ("saturation", 0, 2, 1)]

class Webcam:
        def __init__(self):
                # Gui init
                window = gtk.Window(gtk.WINDOW_TOPLEVEL)
                window.connect("destroy", self.destroy_cb)
                darea = gtk.DrawingArea()
                darea.set_size_request(WIDTH, HEIGHT)
                controls = gtk.VBox()
                labels = gtk.VBox()
                for prop, lower, upper, default in VIDEO_PROPERTIES:
                        adj = gtk.Adjustment(default, lower, upper)
                        widget = gtk.HScale(adj)
                        label = gtk.Label(prop)
                        widget.connect("value-changed", self.value_changed_cb, prop)
                        controls.pack_start(widget, True, True)
                        labels.pack_start(label, True, False)
                configs = gtk.HBox()
                configs.pack_start(labels, False, False)
                configs.pack_end(controls, True, True)
                layout = gtk.VBox()
                layout.pack_start(darea)
                layout.pack_end(configs, False, False)
                window.add(layout)

                # Pipeline configuration
                self.pipeline = gst.Pipeline()
                source = gst.element_factory_make("v4l2src")
                source.set_property('device', "/dev/video%d" % DEVICE)
                decoder = gst.element_factory_make("jpegdec")
                flip = gst.element_factory_make("videoflip")
                flip.set_property('method', 'horizontal-flip')
                self.balance = gst.element_factory_make("videobalance")
                videosink = gst.element_factory_make("xvimagesink")
                videosink.set_property('force-aspect-ratio', True)
                self.pipeline.add(source, decoder, flip, self.balance, videosink)
                window.show_all()

                # Pipeline blocks linking
                caps = "image/jpeg,width=%d,height=%d,framerate=%d/1" %
                                (WIDTH, HEIGHT, FRAMERATE)
                source.link(decoder, gst.caps_from_string(caps))
                decoder.link(flip)
                flip.link(self.balance)
                self.balance.link(videosink)

                # Callback for display the webcam over the darea
                bus = self.pipeline.get_bus()
                bus.add_signal_watch()
                bus.enable_sync_message_emission()
                bus.connect('sync-message', self.sync_message_cb, darea)

                # Start the flow
                self.pipeline.set_state(gst.STATE_PLAYING)

        def destroy_cb(self, widget):
                self.pipeline.set_state(gst.STATE_NULL)
                gtk.main_quit()

        def value_changed_cb(self, widget, prop):
                self.balance.set_property(prop, widget.get_value())

        def sync_message_cb(self, bus, message, darea):
                if message.structure is None:
                        return
                message_name = message.structure.get_name()
                if message_name == 'prepare-xwindow-id':
                        # Assign the viewport
                        imagesink = message.src
                        imagesink.set_xwindow_id(darea.window.xid)

if __name__ == '__main__':
        i = 1

        for arg in sys.argv[1:]:
                if i == 1: DEVICE = int(arg)
                elif i == 2: WIDTH = int(arg)
                elif i == 3: HEIGHT = int(arg)
                elif i == 4: FRAMERATE = int(arg)
                else: break
                i += 1
        Webcam()
        gtk.main()

Rotating cube

January 3rd, 2009

Simulation of a rotating cube using python + GTk.
Moving the mouse while the button1 is pressed will produce a rotation of the cube along XZ, and YX axis. Otherwise you will shift the point of view on the XY plane. Still looking for a more efficient way of drawing on the screen.

#!/usr/bin/env python

import gtk
import gobject
from math import pi, cos, sin

# perspective
ZOOM = 100.0
FOCUS = 100.0

# misc
FPS=60
DEPTH = 16
PALETTE = {
        'black': (0, 0, 0),
        'blue': (0, 0, 65535),
        'green': (0, 65535, 0),
        'cyan': (0, 65535, 65535),
        'red': (65335, 0, 0),
        'magenta': (65535, 0, 65535),
        'yellow': (65535, 65535, 0),
        'white': (65535, 65535, 65535),
}
ZSHIFT = 3
ZMOD = 200/DEPTH

class Scene():
        def __init__(self):
                window = gtk.Window()
                window.set_size_request(640, 480)
                window.add_events(gtk.gdk.BUTTON_PRESS_MASK
                                | gtk.gdk.POINTER_MOTION_MASK
                                | gtk.gdk.POINTER_MOTION_HINT_MASK)
                window.connect('delete_event', self.delete_event_cb)
                window.connect('button_press_event', self.button_press_event)
                window.connect('motion_notify_event', self.motion_notify_event)
                self.darea = gtk.DrawingArea()
                self.darea.connect('configure_event', self.configure_event)
                self.darea.connect('expose_event', self.expose_event)
                window.add(self.darea)
                self.darea.show()
                window.show()
                self.refresh = 0
                self.refresh = gobject.timeout_add(1000/FPS, self.draw_scene)

        def delete_event_cb(self, widget, event):
                if self.refresh != 0:
                        gobject.source_remove(self.refresh)
                        self.refresh = 0
                gtk.main_quit()
        def button_press_event(self, widget, event):
                if event.button == 1:
                        x, y, state = event.window.get_pointer()
                        self.oldx, self.oldy = self.convert_dev_to_user(x, y)
                return True

        def motion_notify_event(self, widget, event):
                if event.is_hint:
                        x, y, state = event.window.get_pointer()
                else:
                        x = event.x
                        y = event.y
                        state = event.state
                # the origin is in the middle of the windonw
                x, y = self.convert_dev_to_user(x, y)
                if state & gtk.gdk.BUTTON1_MASK:
                        angle_xz = angle_yz = 0
                        if x > self.oldx:
                                angle_xz = .05
                        elif x < self.oldx:
                                angle_xz = -.05
                        if y > self.oldy:
                                angle_yz = .05
                        elif y < self.oldy:
                                angle_yz = -.05
                        self.cube.rotate(angle_xz, angle_yz)
                        self.oldx = x
                        self.oldy = y
                else:
                        self.vx = x
                        self.vy = y
                return True

        def configure_event(self, widget, event):
                x, y, self.width, self.height = widget.get_allocation()
                self.cx = self.width/2
                self.cy = self.height/2
                self.unit = min(self.cx, self.cy)/2
                self.vx = self.vy = 0
                self.oldx = self.oldy = 0
                self.pixmap = gtk.gdk.Pixmap(widget.window, self.width,
                                self.height)
                self.cube = Cube(self)
                self.draw_scene()
                return True

        def expose_event(self, widget, event):
                x , y, width, height = event.area
                self.darea_realize(x, y, width, height)
                return False

        def darea_realize(self, x, y, width, height):
                self.darea.window.draw_drawable(
                                self.darea.get_style().fg_gc[gtk.STATE_NORMAL],
                                self.pixmap, x, y, x, y, width, height)

        def convert_dev_to_user(self, x, y):
                return x - self.cx, (self.height - 1 - y) - self.cy

        def z_scale(self, z):
                return ZOOM/(FOCUS + z)

        def convert_3d_to_2d(self, point):
                px, py, pz = point
                px *= self.unit
                py *= self.unit
                z = (pz + ZSHIFT)*ZMOD
                x = self.cx + self.vx + (px - self.vx)*self.z_scale(z)
                y = self.cy + self.vy + (py - self.vy)*self.z_scale(z)
                return int(x), int(y)

        def color_shading(self, color, z):
                z += ZSHIFT
                r, g, b = PALETTE[color]
                # quadratic shading
                ratio = (float(DEPTH) - z)**2/(DEPTH**2)
                r = int(r*ratio)
                g = int(g*ratio)
                b = int(b*ratio)
                return r, g, b

        def draw_line(self, src, dst, color='white', dashed=False):
                gc = self.darea.window.new_gc()
                r, g, b = self.color_shading(color, src[2])
                gc.foreground = self.darea.get_colormap().alloc_color(r, g, b)
                if dashed:
                       gc.set_line_attributes(1, gtk.gdk.LINE_DOUBLE_DASH,
                                       gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_BEVEL)
                x0, y0 = self.convert_3d_to_2d(src)
                x1, y1 = self.convert_3d_to_2d(dst)
                self.pixmap.draw_line(gc,
                                x0, self.height - 1 - (y0),
                                x1, self.height - 1 - (y1))

        def draw_scene(self):
                self.pixmap.draw_rectangle(self.darea.get_style().black_gc,
                                True, 0, 0, self.width, self.height)
                self.cube.draw()
                self.darea_realize(0, 0, -1, -1)
                return True

class Cube(Scene):
        def __init__(self, scene):
                self.scene = scene
                self.front = [(-1, 1, -1), (1, 1, -1), (1, -1, -1), (-1, -1, -1)]
                self.rear = [(-1, 1, 1), (1, 1, 1), (1, -1, 1), (-1, -1, 1)]

        def rotate(self, angle_XZ, angle_YZ):
                scene = self.scene
                for i in range(4):
                        # Front face
                        x, y, z = self.front[i]
                        theta = angle_XZ
                        x, y, z = (x*cos(theta) - z*sin(theta), y, x*sin(theta) + z*cos(theta))
                        theta = angle_YZ
                        x, y, z = (x, y*cos(theta) - z*sin(theta), y*sin(theta) + z*cos(theta))
                        self.front[i] = (x, y, z)
                        # Rear face
                        x, y, z = self.rear[i]
                        theta = angle_XZ
                        x, y, z = (x*cos(theta) - z*sin(theta), y, x*sin(theta) + z*cos(theta))
                        theta = angle_YZ
                        x, y, z = (x, y*cos(theta) - z*sin(theta), y*sin(theta) + z*cos(theta))
                        self.rear[i] = (x, y, z)

        def draw(self):
                scene = self.scene
                for i in range(4):
                        scene.draw_line(self.front[i], self.front[(i + 1)%4])
                        scene.draw_line(self.rear[i], self.rear[(i + 1)%4])
                        scene.draw_line(self.front[i], self.rear[i])

if __name__ == '__main__':
        Scene()
        gtk.main()

Pmv: mv with progress bar

December 26th, 2008

Bash script which display a progress bar dugin a mv operation.

#!/usr/bin/env bash

[ $# != 2 ] && printf "usage: $0  n" && exit 1
trap 'rm -rf $2' 1 2 15 # HUP INT TERM

width=$(tput cols)
length=$(($width -6))
i=1; eq=''; ws=''
while [ $i -lt $length ]; do
        eq="$eq="
        ws="$ws "
        i=$(($i + 1))
done
cur=0; tot=$(stat -c %s $1 2>/dev/null)
(mv $1 $2) &
[ -z $tot ] && wait && exit 1
while [ $cur -le $tot ]; do
        i=$(( $cur*$length/$tot ))
        percentage=$(( $cur*100/$tot ))
        printf "r[${eq:0:$i}${ws:$i}] %3d%%" $percentage
        [ $cur -eq $tot ] && break
        sleep 0.1
        cur=$(stat -c %s $2 2>/dev/null)
        [ -z $cur ] && cur=0
done
printf "n"

Save it inside ~/bin, or /usr/bin.
Make it executable.
Enjoy.

Autoscatto support poetry, please support Autoscatto.

December 9th, 2008

Nothing but a small example of what “Obfuscated C” means:

char o,k,h[0x18],s[]={'x54','x48','x49','x53','x20','x49',
'x53',32,'x41',040,'x53','x51','x55','x41','x52','x45' ,
'x00' }; void space(int i){ i=i%5; i=(i==0)?42:i==1?43:i==2?35:
i==3?64:i==4?94:126 ; k=0; while(k!='O'-'2'){putchar(i);  k++;} }
void m(int l, int b,...){int i=b&&putchar(10)&&(1==0);putchar(9);
for(;(i<=l);i++){ putchar((b)?*(s+i):*(s+l-i)); putchar(*(s+7));}
putchar(10);} main(){char $[]={99,0,0,*(s+0x0D)+040,1?'r':(1),0};
*($+2)=*($+1)=*$+9,o=0; *($+2)-=7;int j,i=(1==2);for(j=0;j<'6'/2;
j++){*(h+j)=040;}int l= 0x0F;k=1;for(;;){o++;i=0;system($);for(;
i<l;i++){(i==0)?(m(l,1)):(putchar(9), putchar(*(s+i)),space(o+1),
putchar(*(s+l-i)),putchar(10) );}m(l,0);usleep(('}'-'2')*1000);}}
/* {}  Autoscatto support poetry, please support Autoscatto {} */

It has not been written by me, I'm just supporting Autoscatto.

Compile it with:

gcc -o [] [].c