Archive for the ‘Script’ Category

Python : Basic statistics with the numpy module

The numpy module features some useful functions for statistics, like “mean()” and “median()”:

For example let´s consider a 2D array with age and height of some people and print out some statistics:

#! /usr/bin/env python
import numpy as np

#age, height in meters
person = [[11,1.56],[4, 0.80], [44, 1.88], [23, 1.68], [55, 1.74]]

np_person = np.array(person)


age = np_person[:,0]

height = np_person[:,1]
print("average age: " + str(np.mean(age)))
print("average height: " + str(np.mean(height)))

#the standard deviation is also rounded to two decimals only.
std_height= round(np.std(height),2)

print("standard deviation of the height: "+ str(std_height))

corr = np.corrcoef(np_person[:,0], np_person[:,1])
print("Correlation: " + str(corr))

The code can be also found on github:

Python scripting with Linux: which shebang?

If you want to execute python scripts with Linux you need to add the shebang line: “#! /usr/bin/env python”

It must be added on top of the file.

The shebang will allow you to run the script as any other script. Among the many options to run it, assuming the script name is “script”, one is:

> ./

The file must be made executable:

>  sudo chmod +x

Assuming we want to print an homogenous array created with the numpy module, a script might include the module import too:

#! /usr/bin/env python

import numpy as np

array1 = np.array([1,2,3,4])



It will print the following lines:

[1 2 3 4]
<type ‘numpy.ndarray’>



PL/SQL Transactional single rows locking with cursors

Oracle already provides an automatic exclusive locking mechanism for the rows you want to update. However you can override it to customize the performance (for example, if you need consistent data and/or exclusive access for the duration of a whole and more complex transaction).

When your application requires consistent data for the duration of the transaction, not reflecting changes by other transactions, you can achieve transaction-level read consistency by using explicit locking, read-only transactions, serializable transactions, or by overriding default locking.

Row locking at transactional level can be achieved with “SELECT FOR UPDATE” statement. The lock is released after a commit or rollback only.

If you want to lock single rows in Oracle PL/SQL you can use cursors, pointing at the rows you want to lock.

The following example show you how to lock single rows:

(id_number IN number, system_user IN varchar2)
/*"order_row" is a variable to store the row found by the cursor select statement   */
order_row order_queue%rowtype;
cursor c1 is
    SELECT * 
    FROM order_queue 
    WHERE id=id_number
/* first of all you need to open the cursor */
OPEN c1;
/* then you need to fetch the content in the variable */
      FETCH c1 INTO order_row;
/* the lock will be released after the commit */
      IF (c1%found) THEN
         UPDATE order_queue SET processed=1, user=system_user where CURRENT OF c1;
      END IF;
 /* then you need close the cursor */

The “select for update” statement has two possible variants
– FOR UPDATE NO WAIT, that triggers an error if the row is locked by another user.
– FOR UPDATE SKIP LOCKED, that fastens the execution by skipping the already locked rows

If you need to lock a single row in the database you don´t need a loop.

MySQL CHECK constraint alternative: triggers!

Yesterday I discovered the powerful hibernate check constraint (@org.hibernate.annotations.Check) , which can be directly added in your entity class like this:

@Check(constraints = "age IS NOT NULL")
public class Person{

String firstname;
String lastName;
Integer age;

// valid code

Unfortunately, as you can read in the official MySQL docs, “the CHECK clause is parsed but ignored by all storage engines”.
Yesterday I found out that MySql 5.X doesn´t support the SQL CHECK constraint.
It means that if you are using JPA und HIBERNATE you can´t take advantage of the Check annotation!

In the project I am working on we could successfully export the schema with the maven command “hibernate4:export”. The check constraint was added in the create table statement. So if your DBMS supports it you get the job done in a very elegant way.

The way out I could find by googling a bit is not so elegant, but it allowed me to achieve the same result. I have just written a trigger, like the (simple) following:

IF age is NULL
SET MESSAGE_TEXT = 'Age cannot be null';

MySQL has been bought by Oracle. Is this silent ignoring is a strategy to make people migrate to Oracle DBMS? I am afraid it´s so. Corporation games, my friends!

Ant task to execute a main class with command line args parameters

Yeah, once again another HelloWorld stuff on the web. I was just curious to try to execute a Main class with an Ant script and found out that I couldn´t find the straight working snippets online easily, because I couldn´t get to know how to set the classpath. So I have wasted some minutes to make it work.

Let´s consider a little more than the classic HelloWorld example and pass a command line parameter as well:

package de.demo;

public class HelloWorld {

public static void main(String[] args) {
System.out.println("Hello Main! \n"  + "Parameter: "+ args[0]);


Then run following build.xml script:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<project basedir="." default="run" name="Ant Hello World">
	<property name="src" value="." />

	<path id="classpath">
		<fileset dir="${src}">

	<target name="compile">
		<javac srcdir="." />

	<target name="run" depends="compile">
		<!-- Print directly in the console -->
		<echo message="Hello World!" />
		<!-- Run main class with parameters-->
		<java classname="de.demo.HelloWorld">
			<arg value="10"/>
			<classpath refid="classpath">


In the console you will see something like:

Buildfile: C:\Users\liparulol\workspace\AntDemos\buildHelloWorld.xml
[javac] C:\Users\liparulol\workspace\AntDemos\buildHelloWorld.xml:14: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file
[echo] Hello World!
1 Hello Main!
1 Parameter10
Total time: 745 milliseconds

That´s it!

SSH: key generation and connection with different port number

Lately I’ve purchased a virtual private server hosting (VPS) to deploy my liferay portal. I’ve been assigned a different port number… and I needed to understand the steps to make a ssh connection.
After some hours surfing the web and making experiment, I could make it. So now I’m posting this litte tutorial, for those that want to work by the linux shell B)

Firt of all you need to generate a public and private keys with a cryptographic algorithm:

ssh-keygen -t dsa

I’ve chosen the DSA (digital signature algorithm), but you can choose RSA, etc.

After entering the ssh-keygen command on the shell, under the folder  ~/.ssh/ you will find the following files: id_dsa,, authorized_keys and known_hosts files.

Make sure that you have all the permissions on the folder and that you’re the only one that can read and write the authorized_keys file:

sudo chmod 600 ~/.ssh/authorized_keys

The system will add your host to the lists of the “known hosts”, when you try to login to the remote server for the first time.

Once your keys have been generated, you need to copy the public key in the “authorized_keys” file:

cp ~/.ssh/ ~/.ssh/authorized_keys

Then you need to send your public key to the server. Let’s assume that our ssh port number is 12345:

scp -P 12345 ~/.ssh/  [email protected]:~/.ssh/authorized_keys

The shell will ask you a password:

[email protected]'s password: user's passowrd

Now that you’ve sent your public key to the server you can connect:

ssh -p 12345 [email protected]

After this command you’ll be asked your passphrase password (that you set when you generate the public key),
so you can be authenticated with your private key.

That’s it! 😎

“Hello world” kernel module

Make a directory called “helloM” in your home dir and edit the following .C file, called “hello.c”:

/*hello.c – The simplest kernel module.*/

#include <linux/module.h>  /* Needed by all modules */
#include <linux/kernel.h>  /* Needed for KERN_ALERT */

int init_module(void)
printk("<1>Hello world 1.\n");
// A non 0 return means init_module failed; module can't be loaded.
return 0;

void cleanup_module(void)
printk(KERN_ALERT "Goodbye world 1.\n");

To compile this kernel module you need to edit the following “Makefile” (called “Makefile” !):


# We were called by kbuild

obj-m += hello.o

else  # We were called from command line

KDIR := /lib/modules/$(shell uname -r)/build

#KDIR := /home/cynove/src/kernel/linux-source-2.6.31

PWD  := $(shell pwd)


@echo '    Building target module 2.6 kernel.'


$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules


./ *.ko

endif  # End kbuild check

######################### Version independent targets ##########################


rm -f -r *.o *.ko .*cmd .tmp* core *.i

Then, within our working folder, type make, which will process the Makefile and create a module file, hello.ko.

To install the module,type:

sudo insmod hello.ko

To verify the module has output to the log file in Ubuntu 11.10 type:

 tail /var/log/kern.log

You should read the message of the init_module() method, that is “Hello world 1.”

To remove the module, type:

sudo rmmod hello.ko

In the tail of the kern.log you should find “Goodbye world 1.”.

Funny! By these first steps you can make interesting kernel modules!

Perl and SQLite, free pdf download

You can download “Perl Scripting for SQLite”.
It’s a pdf of the slides I’ve made for the “Linux day 2011” in my hometown.
Have fun!

Perl script using LWP module

Library FOR WWW in Perl (LWP)

In Linux you can istall all the perl modules about the web (LWP, URI, URL, HTTP…) at once:

:~$ sudo apt-get install libwww-perl

LWP is the most used Perl module for accessing data on the web.

LWP::Simple – module to get document by http
its functions don’t support cookies or authorization, setting header lines in the HTTP request; and generally, they don’t support reading header lines in the HTTP response (most notably the full HTTP error message, in case of an error). To get at all those features, you’ll have to use the LWP::UserAgent;

LWP::UserAgent is a class for “virtual browsers,” which you use for performing requests, and HTTP::Response is a class for the responses (or error messages) that you get back from those requests.

There are two objects involved: $browser, which holds an object of the class LWP::UserAgent, and then the $response object, which is of the class HTTP::Response. You really need only one browser object per program; but every time you make a request, you get back ar esponse object, which will have some interesting attributes:

$response->is_success : A HTTP status line, indicating success or failure  (like “404 Not Found”).

$response->content_type A MIME content-type like “text/html”, “image/gif”, “application/xml”, and so on, which you can see with

$response->content : the actual content of the response. If the response is HTML, that’s where the HTML source will be; if it’s a GIF, then $response->content will be the binary GIF data.

Enabling Cookies

A default LWP::UserAgent object acts like a browser with its cookies support turned off.
You can even activate cookies, with the following function:


with “cookie_jar” you can get and save the cookies from Browsers.

The following script gets a url from the shell and print the content of the corresponding web page both to screen and a new file called “code.html” (created by running the script).


#!/usr/bin/perl -w
use LWP::UserAgent;

#browser = instance of the UserAgent class
my $browser = LWP::UserAgent->new;
my $url =$ARGV[0]; # passing the url by command line
my $response = $browser->get($url);

die "Can’t get $url \n", $response->status_line
unless $response->is_success;

# check if the content is html
die "Hey, I was expecting HTML, not ", $response->content_type
unless $response->content_type eq 'text/html';

print "Page content: \n";

#print content to console
print $response->decoded_content;

#print content to a NEW file
open (MYPAGE, '>>code.html');
print MYPAGE $response->decoded_content;
close (MYPAGE);

#REGULAR EXPRESSION: search for a string in the content
if($response->content =~ m/perl/i) {
print " \n \n This page is about Perl!\n \n";
} else {print "\n \n No content about Perl! \n \n"; }

Perl script for a Hollywood Sqlite database

Let’s analyze the following perl scripta “”, to create and populate a simple database about  movies, and “” to execute a simple SELECT-FROM-WHERE query on it.


#!/usr/bin/perl -w

use DBI;
use strict;

my $platform = “SQLite”;
my $database = “hollywood.db”;
my $host = “localhost”;
my $port = “3306”;
my $user = “username”;
my $pw = “password”;

my $dsn = “dbi:$platform:$database:$host:$port”;

my $dbh = DBI->connect($dsn, $user, $pw) or die “Cannot connect: $DBI::errstr”;

# creating the “hollywood” database
$dbh->do(“CREATE TABLE IF NOT EXISTS actors(aid integer primary key, name text)”);

$dbh->do(“CREATE TABLE IF NOT EXISTS  movies(mid integer primary key, title text)”);

$dbh->do(“CREATE TABLE IF NOT EXISTS actors_movies(id integer primary key, mid integer, aid integer)”);

#populating “actors” table
$dbh->do(“INSERT INTO actors(name) VALUES(‘Philip Seymour Hofman’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Kate Shindle’)”);
$dbh->do(“INSERT INTO actors(name) VALUES (‘Kelci Stephenson’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Al Pacino’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Gabrielle Anwar’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Patricia Arquette’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Gabriel Byrne’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Max von Sydow’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Ellen Burstyn’)”);
$dbh->do(“INSERT INTO actors(name) VALUES(‘Jason Miller’)”);

#populating “movies” table

$dbh->do(“INSERT INTO movies VALUES(1,’Capote’)”);
$dbh->do(“INSERT INTO movies VALUES(2,’Scent of a woman’)”);
$dbh->do(“INSERT INTO movies VALUES(3,’Stigmata’)”);
$dbh->do(“INSERT INTO movies VALUES(4,’Exorcist’)”);
$dbh->do(“INSERT INTO movies VALUES(5,’Hamsun’)”);

#populating “actorsMovies” table
$dbh->do(“INSERT INTO actors_movies VALUES(1,1,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(2,2,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(3,3,1)”);
$dbh->do(“INSERT INTO actors_movies VALUES(4,4,2)”);
$dbh->do(“INSERT INTO actors_movies VALUES(5,5,2)”);
$dbh->do(“INSERT INTO actors_movies VALUES(6,6,3)”);
$dbh->do(“INSERT INTO actors_movies VALUES(7,7,3)”);
$dbh->do(“INSERT INTO actors_movies VALUES(8,8,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(9,9,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(10,10,4)”);
$dbh->do(“INSERT INTO actors_movies VALUES(11,8,5)”);

print qq{“Hollywood” database created! \n };



#!/usr/bin/perl -w

use DBI;
use strict;

my $platform = “SQLite”;
my $database = “hollywood.db”;
my $host = “localhost”;
my $port = “3306”;
my $user = “username”;
my $pw = “password”;

my $dsn = “dbi:$platform:$database:$host:$port”;

my $dbh = DBI->connect($dsn, $user, $pw) or die “Cannot connect: $DBI::errstr”;

my $query = “SELECT , movies.title  FROM actors,movies,actors_movies WHERE actors.aid=actors_movies.aid and

my $sth=$dbh->selectall_arrayref($query);

print “Actor                                                          Movie \n” ;
print “======================  ====================\n”;

foreach my $row (@$sth) {
my ($name, $title) = @$row;

### Print out the table metadata…
printf “%-23s %-23s \n”, $name, $title;




Make the perl scripts executable like:
$ sudo chmod +x

And run them liket:
$ ./

The result of the query is:

Actor                                   Movie
====================  ====================
Philip Seymour Hofman     Capote
Philip Seymour Hofman     Scent of a woman
Philip Seymour Hofman     Stigmata
Kate Shindle                      Exorcist
Kate Shindle                      Hamsun


Very nice script, isn’t it?
I guess the DBI deserves further attention…