Installing CouchDB 2.0 on Debian Stretch

CouchDB 2.0 released on September 2016 has clustering support.

#cd /usr/src
#wget http://www-eu.apache.org/dist/couchdb/source/2.0.0/apache-couchdb-2.0.0.tar.gz
#tar xvzf apache-couchdb-2.0.0.tar.gz
#cd apache-couchdb-2.0.0
#./configure
#make release

By any chance you encounter this error,

ERROR: Unable to generate spec: read file info /usr/lib/erlang/man/man1/gcc-ar.1.gz failed 
ERROR: Unexpected error: rebar_abort   
generate failed while processing  rebar_abort 

You need to install erlang-base-hipe instead of erlang-base

#aptitude install erlang-base-hipe
#rm /usr/lib/erlang/main
#make clean
#make release

Debugging and logging in OpenResty

There is a few key point to ease the development of lua in OpenResty environment.

Turn lua code caching off

Restarting nginx everytime there is a code changes is painful. The easier way is to load external lua code using content_by_lua_file as opposed to have lua code inside nginx configuration files and then turn off the cache.

location /hello {
  default_type text/html;
  lua_code_cache off; #development
  content_by_lua ./hello.lua;
}

Read nginx log as it is written

Set the error_log configuration directive to output log on easily accessable directory.

error_log /home/away/tmp/hello.log

And read the log interactively in a separate terminal as it been written using

tail -f /home/away/temp/hello.log

Output the log file in the terminal

Redirect all error log to the terminal where nginx is running

error_log /dev/stderr;

Log event or variable

Output debugging info using ngx.log

ngx.log(ngx.ERR, "hello world here")

References
OpenResty website
Definintely an OpenResty Guide

Nodejs gotcha on heroku

Use environment variable process.env.PORT instead of requesting for fixed port. Heroku will assign random port everytime the application bootup. This lead to some misleading error like strange Redis too many connection error and error H10.

app.listen(process.env.PORT || 5000);

Another gotcha when we upgrade the PostgreSQL to the bigger plan, yet another misleading error

error: no pg_hba.conf entry for host 

The paid plan (standard-0) only accept ssl connection:

postgres://user:seckrit@pghost:5432/dbname?ssl=true

Couchapp on Debian Stretch

I have been developing application using Qooxdoo for years. It works great so far, except when the internet very slow, which is quite common problem. It make the application behave unexpectedly weird because user will randomly click anywhere while data loading from the server.

One way to solve this problem is to design using offline first concept. That is where i get to know about PouchDB and CouchDB. Couchapp is a convinient way to develop application on CouchDB.

Installing couchapp is pretty easy,

#aptitude install python-pip
#pip install couchapp

Then creating a new project,

$couchapp generate hello

Related
Couchapp on github
Couchapp documentation
Building couchapp

Validate malaysian phone number in javascript

My pull request just accepted by chriso author of validator.js, now you can use validator.js to validate malaysian phone number using ‘ms-MY’ locale.

Probably will take sometime before the npm and bower package updated.
You can install via npm,

$npm install --save https://github.com/chriso/validator.js.git

On nodejs,

const v = require('validator')
v.isMobilePhone('+60128747889', 'ms-MY')

On browser,

<script type="text/javascript" src="validator.min.js"></script>
<script type="text/javascript">
  validator.isMobilePhone('+60128747889', 'ms-MY') //true
</script> 

Btw, i wish the locale is en-MY but there is no such thing. So, i think ms-MY will do.

Related
Telephone number in malaysia
Github validator.js

Beautify javascript code

Some of my javascript code indent contain mixed of tab and space
and only aware of the code ugly indent when i open in github.

There is a few cli program to format code and my favorite so far is js-beautify

#npm install -g js-beautify

Go to the source code do

$js-beautify -h
$js-beautify -s 2 -r *js

You can make vim to display space character on the editor by using the command

:set list

Install php7.0 on debian jessie

The latest PHP7.0 come with huge speed improvement. PHP7.0 debian package is available from dotdeb repository.

deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all

Then install the key

#wget https://www.dotdeb.org/dotdeb.gpg
#sudo apt-key add dotdeb.gpg
#aptitude install php7.0-fpm php7.0-pgsql php7.0-cli

Please note that some extension not yet available.

Related
PHP 7.0.3 for jessie
Dotdeb install instruction

Ghost blog mail configuration using Amazon SES

Ghost is a blogging platform written in nodejs.
Edit the config.js file at the ghost root directory

mail: {
   from: 'from@email.com',
   transport: 'SMTP',
   options: {
     host: "your-amazon-host",
     port: 465,
     service: "SES",
     auth: {
       user: "your-amazon-user",
       pass: "your-amazon-password"
     }
   }
}

Amazon SES credential can be generated from amazon control panel.
From address must be registered and verified as sender.

Related
Mail configuration on a self hosted ghost
Mail github source

Block ads using /etc/hosts in debian

We can avoid ads from loading by serving 0.0.0.0 or 127.0.0.1 for the ads domain.
There is a few website that provide such list and one of them is from mvps.org.

The installation is rather simple. Just copy and paste the list to /etc/hosts file.

#wget http://winhelp2002.mvps.org/hosts.txt
#cp /etc/hosts /etc/hosts.old
#cat hosts.txt >> /etc/hosts

The host file come from window enviroment. So there will be some extra line ugly line
ending that look like ^M in vim. To fix it

#vim /etc/hosts

Then on the vim command mode run

:%s/<CTRL-V><CTRL-M>//g

Related
Block unwanted advertisements with /etc/hosts file on Linux
Amalgamated hosts file

Compile mupdf in debian

#aptitude install libgl-dev libxcursor-dev libxrandr-dev libxinerama-dev
$git clone git@github.com:paragasu/mupdf.git
$cd mupdf
$git submodule init
$git submodule update
$make

Merge git repo as another branch

I have two local repository on my directory api-php and api-nodejs. I want to have one repo called api with two branch php and nodejs.

$cd api-php
$git remote add nodejs ../api-nodejs
$git remote update
$git checkout -b nodejs
$git rm -f *
$git merge nodejs/master 
$git push -f

By the way, both php and node js implement the same api but the language is totally differnet.
It is best to put both project on separate repository.

Related
Merge git repo into branch of another repo

Generate SSL certificates using letsencrypt

Letsencrypt provide free ssl certificate. The only downside is that the certificate only valid
for 3 months and then you have to renew the certificate again.

#git clone https://github.com/letsencrypt/letsencrypt
#cd letsencrypt
#./letsencrypt certonly --manual -d mydomain.com

On my debian server, The command will update packages and ask for root if you run as normal user and it will require you to put some key file in the root domain for verification.

http://mydomain.com/.well-known/acme-challenge/random-key-filename

You have to make sure the content-type is text/plain for the verification to work. The certificate will be available at /etc/letsencrypt. The latest cert will be inside the /etc/letsencrypt/live folder.

You need to update your server configuration to point to the cert file.

Related
Letsencrypt github
Letsencrypt user guide

Https on Nodejs

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

Related
Nodejs doc

Install gin.io in Debian Jessie

Openresty is nginx with embeded lua. High performance with low memory footprint.
Gin is a small and elegant lua framework build on top of Openresty.

Install Openresty framework

#aptitude install lua-dbi-postgresql-dev  
#aptitude install luajit  
#aptitude install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl make build-essential
#aptitude install libpq-dev
#cd /usr/src
#wget https://openresty.org/download/ngx_openresty-1.9.7.2.tar.gz
#cd ngx_openresty*
#./configure --with-luajit --with-http_postgres_module

Install gin framework

#aptitude install luarocks  
#luarocks install --server=http://gin.io/repo gin  

Related
OpenResty
Gin JSON API framework

PostgreSQL ENUM type

To create enum type

CREATE TYPE colors AS ENUM (‘grey’, ‘skyblue’, ‘black’);

To list enum values

SELECT ENUM_RANGE(null::colors); or  
SELECT UNNEST(ENUM_RANGE(null::colors)) AS colors;  

To add new item on the enum list

ALTER TYPE colors ADD VALUE 'orange' AFTER 'skyblue';

To delete item from enum list

ALTER TYPE colors DROP attribute 'orange';

To drop enum type

DROP type colors

There is a more elegant way using domain to enforce value from David E. Wheeler post

CREATE DOMAIN eye_color AS TEXT
CONSTRAINT valid_eye_colors CHECK (
	VALUE IN ( 'blue', 'green', 'brown' )
);

CREATE TABLE faces (
	face_id SERIAL PRIMARY KEY,
	name TEXT NOT NULL DEFAULT '',
	eye_color eye_color NOT NULL
);

Related
Enum support function
Alter type
Enforce set of values

Nodemon failed to start process, possible issue with exec arguments

Nodemon will crashed with this error when the exec comman return error code 2

[Nodemon] failed to start process, possible issue with exec arguments
events.js:146
	throw err;
	^

Error: Uncaught, unspecified "error" event. (2)
	at emit (events.js:144:17)

Error code 2 is reserved for bash. Command line tools like mocha or jshint sometimes will throw error 2. When jshint or mocha executed as argument to -x in nodemon. Nodemon crash.

A simple workaround is to put exit 1 in the -x

$nodemon --e js -w ./ -d 1 -x 'mocha ./test || exit 1'

Related
Nodemon code
JSHint integration on github
Nodejs exit code

Migration from wordpress.com to github.io in Debian

Login to wordpress and export all pages

#aptitude install ruby ruby-dev
#gem install jekyll jekyll-import hpricot open_uri_redirections
$jekyll new paragasu.github.io
$cd paragasu.github.io
$jekyll serve

Disable ipv6 in debian

Edit /etc/sysctl.conf and add config

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.eth0.disable_ipv6 = 1

#sysctl -p

Debian IPV6

Setting up nfs in debian stretch

On nfs server

#aptitude install nfs-kernel-server

Edit /etc/exports configuration file

/home/me/public 192.168.1.2(rw,no_root_squash,subtree_check)<br />

Restart nfs

#exportfs -a
#/etc/init.d/nfs-kernel-server start

On nfs client

#aptitude install nfs-common
#/etc/init.d/nfs-common start

To list available nfs

#showmount -e 192.168.1.2

To mount nfs

#mount -t nfs /home/me/public /mnt/public<br />

Related
Basic nfs configuration on debian 7

Basic tmux command

  • Ctrl+b " - split pane horizontally.
  • Ctrl+b % - split pane vertically.
  • Ctrl+b arrow key - switch pane.
  • Hold Ctrl+b, don't release it and hold one of the arrow keys - resize pane.
  • Ctrl+b c - (c)reate a new window.
  • Ctrl+b n - move to the (n)ext window.
  • Ctrl+b p - move to the (p)revious window.\

Tmux tutorial
Tmux the terminal multiplexer

Calculate distance between two point on earth in PostgreSQL

Come across nice function by Merlin Moncure posted on grokbase.

CREATE OR REPLACE 
FUNCTION calculate_distance(lat1 float8, lon1 float8, lat2 float8, lon2 float8)
RETURNS float8 AS
$$
	SELECT ACOS(SIN(RADIANS($1)) * SIN(RADIANS($3)) 
		 + COS(RADIANS($1)) * COS(RADIANS($3)) 
		 * COS(RADIANS($4) - RADIANS($2))) * 6371;

$$ LANGUAGE 'sql' IMMUTABLE;

More details
Calculating distance between longitude and latitude
Calculate distance, bearing and more

Migrating from MySQL to PostgreSQL

Encounter some issue along the way

1.MySQL DATE_SUB & DATE_ADD

(DATE_ADD(NOW(), INTERVAL 30 MINUTES)
(DATE_SUB(NOW(), INTERVAL 30 MINUTES)
(NOW() - INTERVAL '30' MINUTE)
(NOW() - INTERVAL '30' MINUTE) or
(NOW() - INTERVAL '30 MINUTES') or
(NOW() - '30 MINUTES'::INTERVAL)

2.MySQL RADIANS
Need to cast to real

SELECT RADIANS(lat::real);

3.DISTINCT on json field (v9.4.5)

SELECT DISTINCT id, json_field FROM driver;

Throw could not identify an equality operator for type json error.
Converting the json field to jsonb solve the problem

Firefox 40+ slow right click in Debian Linux

Just installed latest firefox on debian linux streetch.
Right click on link popup very slow.

SOLVED: [blfs-support] Firefox - slow menu and right-click response

The right click menu in Firefox is now fast again. I disabled Pulseaudio which
tried to load ConsoleKit. This did not work sine I have unstalled ConsoleKit.

=== details ===

I found this:

/var/log/sys.log
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] module-console-kit.c:
GetSessionsForUnixUser() call failed:
org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.ConsoleKit
was not provided by any .service files
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] module.c: Failed to load
module "module-console-kit" (argument: ""): initialization failed.
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] main.c: Module load failed.
Jan 25 09:13:47 lfs pulseaudio[2565]: [pulseaudio] main.c: Failed to
initialize daemon.
Jan 25 09:13:47 lfs pulseaudio[2562]: [pulseaudio] main.c: Daemon startup
failed.

I commented out the text below in /etc/pulse/default.pa
#.ifexists module-console-kit.so
#load-module module-console-kit
#.endif

I restarted and then the problem with the Firefox menus disappeared.

The root cause is probably that I uninstalled ConsoleKit. This was
intentional, but I failed to recognize the side effects.

Magnus

Qooxdoo change global application font size

setFontSize: function(size)
{
	var doc         = this.getRoot();  
	var manager     = qx.theme.manager.Font.getInstance();  
	var defaultFont = manager.resolve(doc.getFont());
	var newFont     = defaultFont.clone().setSize(parseInt(size));
	doc.setFont(newFont);
},  

How to use genymotion emulator

Start the emulator. Then find out the genymotion assigned IP address

$ps ax | grep geny

Then connect using adb

$adb connect 192.168.1.3

ADB android over wireless connection

Connect using USB.

$adb tcpip 5555

Disconnect USB.

Reconnect using wireless connection. You can find out the IP address from wireless config

$adb connect 192.168.1.3:5555

tns debug android --debug-brk in linux

The nativescript cli

$tns debug android --debug-brk

The command expect your google chrome executable name is “chrome”.
But in my debian jessie workstation. The executable name is “google-chrome”

$ln -s /usr/bin/google-chrome ~/bin/chrome

will fix the problem.

Centos 6 No package php-fpm available

After installing epel and remi repository and enable remi-php56, the php packages still not available.
The issue is i just uninstall Cpanel from my Centos 6 server. Cpanel disable php packages from showing up in you.

#vim /etc/yum.conf


[main]
exclude=php* ..

Just remove php packages from the exclude section of the /etc/yum.conf.
It waste 3 hours of my time to figure this out.. :(

Powerdns unable to find backend willing to host for potential supermaster

I got this error when i setup powerdns superslave in debian using sqlite3 backend.
The condition to get the superslave working.

  • The supermaster must carry a SOA record for the notified domain.
  • The supermaster IP must be present in the ‘supermaster’ table.
  • The set of NS records for the domain, as retrieved by the slave from the supermaster,
    must include the nameserver that goes with the IP address in the supermaster table.

A very usefull command to test if the setup is working. To send the notification to the slave and

#pdns_control notify mydomain.com

To request for supermasters zone

#pdns_control retrieve mydomain.com

Related
PDNS slave operation

Phonegap add android error

On the phonegap 3.4 running to command

$phonegap add android

Give an error like this

/bin/node_modules/q/q.js:126
                throw e;
                      ^

The problem is the android sdk still not configured properly you need to configure the environment ANDROID_HOME, ANDROID_HOME/tools and ANDROID_HOME/platform-tools add this in your ~/.bash_profile

export ANDROID_HOME=$HOME/android-sdk-linux
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

ALSA lib ctl_oss.c Cannot open device /dev/mixer

It happen recently on my debian workstation

ALSA lib ctl_oss.c:398 (_snd_ctl_oss_open) Cannot open device /dev/mixer
Cannot open mixer: No such file or directory

When you try to run alsamixer. The reason is the the module snd-pcm-oss not loaded. To fix

#modprobe snd-pcm-oss

Qooxdoo wrong icon path after migrate from 2.0 to 3.5

It must be in the form below, start by “/*” and end by “/” and in between start by “*”.

/**
* @assert(sumisi/*)
*/

Otherwise assert will not be read by JsDoc and give an error.

qx.ui.basic.Image[90-0]: Image could not be loaded: sumisi/login.png
ImageLoader: Not recognized format of external image 'sumisi/login.png'

Mssql not a valid ss_sqlsrv_stmt resource

It happen when i have a code like below

function connect()
{
    return sqlsrv_connect(..);
}
..

$result = sqlsrv_query(connect(), $sql);  

The error mysteriously went away when i change the code to this

$connect = connect();
$result  = sqlsrv_query($connect, $sql);

nokia n9 no mobile network error

It happen when i put my DiGi simcard with the original number switch from Maxis network. Fix the problem when i swith my phone number back to Maxis.

Maybe there N9 not compatible with Mobile Number Portability implementation in Malaysia.

nginx + php-cgi on window server 2008

php-cgi.php just hang and die on a very low load. To fix this, use spawn-php

Install

ActivePython-2.7.2.5-win64-x64.msi
pywin32-217.win-amd64-py2.7.exe

Change nginx configuration worker_processes 1;

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  sendfile        on;
  keepalive_timeout  65;

  upstream php_farm {
   server 127.0.0.1:9000 weight=1;
   server 127.0.0.1:9001 weight=1;
   server 127.0.0.1:9002 weight=1;
   server 127.0.0.1:9003 weight=1;
   server 127.0.0.1:9004 weight=1;
   server 127.0.0.1:9005 weight=1;
   server 127.0.0.1:9006 weight=1;
   server 127.0.0.1:9007 weight=1;
   server 127.0.0.1:9008 weight=1;
   server 127.0.0.1:9009 weight=1;
  }


server {
  listen       80;
  server_name  localhost;
  location / {
   root   html;
   index  index.php index.html index.htm;
  }

  error_page   500 502 503 504  /50x.html;
   location = /50x.html {
   root   html;
  }
 
  location ~ \.php$ {
   root           html;
   fastcgi_pass   php_farm;
   fastcgi_index  index.php;
   fastcgi_param  SCRIPT_FILENAME  c:/nginx/html/$fastcgi_script_name;
   include        fastcgi_params;
  }
}

PHP linux vs window version

Come across interesting fact: In linux

echo $_SERVER['SERVER_NAME']; //somedomain.org
echo $_SERVER['HTTP_HOST']; //somedomain.org

In window

echo $_SERVER['SERVER_NAME']; //localhost
echo $_SERVER['HTTP_HOST']; //somedomain.org

Change associated array to indexed array

Sometimes i want to change this form of array

array(
  'position' => array('data1', 'data2'..)
  'year'     => array('year1', 'year2'..)
)

to this

array(0 => array('position' =>'data1',
                 'year' => 'year1'),

      1 => array('position' => 'data2',
                 'year' => 'year2')

Here is how i do it.

function array_group($data)
{
  $result = array();

  foreach($data as $key=>$rows)
     foreach($rows as $i=>$value)
         $result[$i][$key] = $value;
  
   return $result;
}

Virtualbox look ugly

Virtualbox made with qt library. To fix the ugly win95 looking theme,

#aptitude install qt4-qtconfig
$qtconfig

and change the Gui Style to GTK+

vim config

Edit the configuration files _vimrc

set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set smartindent
set textwidth=0
set nowrap
set number
set scrolljump=5
colorscheme koehler
set guifont=Consolas
set guioptions-=m "remove menubar
set guioptions-=T "remove toolbar
set guioptions-=r "remove scrollbar

MSSQL last insert id

Using SCOPE_IDENTITY(),

$result = sqlsrv_query($conn, 'INSERT INTO mytable(name) values ('hello world') ; 
                               SELECT SCOPE_IDENTITY() AS ID', array(), $option);
sqlsrv_next_result();

$row = sqlsrv_fetch_object($result);
echo $row->ID; //last insert id

PHP gotcha

Some unexpected stuff

var_dump('f' == 0); //bool(true)

From PostgreSQL to MSSQL

I love postgresql but my client request specifically for MSSQL.

1. PGSQL boolean column return 't' and 'f' for true and false
MSSQL bit column return 1 and 0 for truen and false

2. PGSQL text column is special it can be use for any size of text
MSSQL varchar column to be able to use operator in where clause and varchar(max) for long string

3. PGSQL use pg_* functions
MSSQL use sqlsrv_* driver supplied by Microsoft and this driver can only be use in windows.

4. PGSQL pg_fetch_object return string for datetime column value
MSSQL sqlsrv_fetch_object return DateTime object for datetime column value.
I have to pass 'ReturnDatesAsString' option in the connection string to turn if off.

5. Paging in PGSQL is straight forward using LIMIT .. OFFSET
In MSSQL i have to use CTE function to enable to use my existing paging library.

6. PGSQL pg_affected_rows()
MSSQL sqlsrv_rows_affected()

MSSQL paging with CTE

No LIMIT OFFSET as in PostgreSQL or MySQL.

WITH cte AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY country ASC) AS RowNumber
  FROM company WHERE country='Malaysia'
)
SELECT * FROM cte
WHERE RowNumber > 0 AND RowNumber < 100

Sqlsrv driver return datetime colum as datetime object

MSSQL’s PHP driver sqlsrv_fetch_object return DateTime object by default.
To disable this, pass parameter ReturnDatesAsString on the connection string.

$param = array('Database' => 'db',
               'UID' => 'uname',
               'PWD' => 'secret',
               'ReturnDatesAsStrings' => 'true');

$conn = sqlsrv_connect('localhost\sqlexpress', $param);

Qooxdoo disable tabview page

Here is a way to disable the tabview page. Turn it grey and unclickable.

var page = new qx.ui.tabview.Page("page");
page.set({enabled: false});

Wheezy php5-fpm and nginx

Debian wheezy version of php5-fpm (5.4.4-7) using socket instead of server running on local port 9000. Need to update nginx configuration files to point to php5-fpm socket.

location ~.\.php$ {
  #fastcgi_pass 127.0.0.1:9000;
  fastcgi_pass unix:/var/run/php5-fpm.sock;
}

Openerp set default value of popup form from one2many field parent

class definition (shop.py), please note the magic active_id

class item(osv.osv):
_name = "shop.item"
_columns = {
  "item_id": fields.many2one("shop.cart", "Cart"),
}

_defaults = {
  "item_id": lambda self, cr, uid, c: c.get('item_id', False),
}


class cart(osv.osv):
_name = "shop.cart"
_columns = {
  "item_ids": one2many("shop.item", "item_id", "Items"),
}

In the view definition for the one2many field (shop_view.xml)

<field name="item_ids" domain="['item_id', '=', active_id]" context="{'item_id': active_id}">

Oss4 no sound in iceweasel flash

flashplugin-nonfree only support Alsa. Thus, extra package required to support OSS4

#aptitude install flashplugin-nonfree-extrasound
#mkdir /usr/lib/oss/lib
#cd /usr/lib/oss/lib
#ln -s /usr/lib/flashplugin-nonfree-extrasound/libflashsupport.so

Restart iceweasel

qooxdoo typeerror .. is not a constructor

very tricky error. the problem lies somewhere in the defined class structure. in my case, i put the function inside the main method instead inside the members method .

Global variables in qooxdoo

Declare the variables in your Application class:

qx.Class.define("custom.Application",
{
  extend  : qx.application.Standalone,
  members :
  {
  /** My global variable */
   bGlobal : true
   main : function()
   {
  // access to global variable from within this class using "this"
     this.bGlobal = false;
   }
  }
}

Then you can access that main application class using qx.core.Init.getApplication() so in some other class, you can read the global like this:

qx.Class.define("custom.SomeArbitraryClass",
{
  extend  : qx.core.Object,
  construct : function()
  {
    /** Access the global variable */
    if(qx.core.Init.getApplication().bGlobal)
    {
      alert("The global is TRUE");
    }
  }
}

You could also have made that global be a property of the Application class:

qx.Class.define("custom.Application",
{
  extend  : qx.application.Standalone,
  properties :
  {
  /** My global variable */
   global : true
   ...

In which case you’d reference it from the other class using the property’s getter:

qx.core.Init.getApplicaiton().getGlobal()

Install sun-java6-jdk in debian wheezy

Install sun-java6-jdk in debian wheezy

sun-java6-jdk no longer available in debian wheezy due to some licencing issues.

Download the binary called Java SE 6 Update 30 at
http://www.oracle.com/technetwork/java/javase/downloads/index.html

unpack it to /opt/jvm/

#update-alternatives --install /usr/bin/java java  /opt/jvm/jdk1.6.0_30/jre/bin/java 3
#update-alternatives --config java

select the option 3 and you are done

common openerp beginner error

This code <field name="type"> form</field> produce the error below


The value " form " for the field "type" is not in the selection

make sure no space between "form"


the field(s) res_model,src_model: Invalid model name in the action definition.

if the code seem rights. restart the openerp-server.

Add menu on fbpanel

If you install binary manually eg: eclipse. Most likely you end up without entries in FBpanel the start menu. Just create a file appname.desktop in then ~/.local/share/applications

[Desktop Entry]
Type=Application
Name=Eclipse
Exec=/opt/eclipse/eclipse
Icon=/opt/eclipse/icon.xpm
NoDisplay=false
Categories=Development

Clearlooks configuration option "sunkenmenu" is not supported and will be ignored.

$android
/usr/share/themes/Taqua/gtk-2.0/gtkrc:55: Clearlooks configuration option "sunkenmenubar" is not supported and will be ignored.
/usr/share/themes/Taqua/gtk-2.0/gtkrc:56: Clearlooks configuration option "menuitemstyle" is not supported and will be ignored.
/usr/share/themes/Taqua/gtk-2.0/gtkrc:57: Clearlooks configuration option "listviewitemstyle" is not supported and will be ignored

To fix it, uncomment the sunkenmenubar, menuitemstyle and lastviewitemstyle
in the /usr/share/themes/Taqua/gtk-2.0/gtkrc

engine "clearlooks"
{
  #sunkenmenubar = 0
  #menuitemstyle = 0
  #listviewitemstyle =0
}

e220 digi broadband in linux debian wheezy

I am using debian Wheezy
Linux 2.6.32-5-686


#aptitude install usb-modeswitch
#aptitude install wvdial

edit the /etc/wvdial.conf

[Dialer defaults]
Phone=*99#
Stupid Mode=1
Dial Command=ATDT
Modem=/dev/ttyUSB0
Baud=230400
Init2=AT+CGDCONT=1, "IP", 3gdgnet"
Init3=
Username=digi
Password=digi
AskPassword=0
ISDN=0
Compuserve=0
Force Address =0
Idle Seconds=0
Auto DNS=1
Check Def dRoute=1

plug in the Huawei E220

#wvdial

resume transfer of large ssh file

you need to install rsync on both client and server


apt-get install rsync
rsync -P -r -e ssh username@server: <serverfile> <localfile>

PCManfm Not Authorized

create a file /etc/polkit-1/localauthority/50-local.d/55-storage.pkla

with the content

[Storage Permissions]
Identity=unix-group:plugdev
Action=org.freedesktop.udisks.filesystem-mount;org.freedesktop.udisks.drive-eject;org.freedesktop.udisks.drive-detach;org.freedesktop.udisks.luks-unlock;org.freedesktop.udisks.inhibit-polling;org.freedesktop.udisks.drive-set-spindown
ResultAny=yes
ResultActive=yes
ResultInactive=no

more info

©

It happen when the page is in UTF8 but the browser display in iso-8859-1.
Add this meta on the head to fix this.

acer aspire d255e card reader driver in debian squeeze

Build in multi card reader in acer aspire one is from ENE Technology.
Here is an instruction to compile the kernel module driver

Download the driver

unzip to /usr/src/keucr-0.0.1
create /usr/src/keucr-0.0.1/dkms.conf file

PACKAGE_NAME="keucr"
PACKAGE_VERSION="0.0.1"
CLEAN="rm -f *.*o"
BUILT_MODULE_NAME[0]="keucr"
MAKE[0]="make -C $kernel_source_dir M=$dkms_tree/$PACKAGE_NAME/$PACKAGE_VERSION/build"
DEST_MODULE_LOCATION[0]="/extra"
AUTOINSTALL="yes"


#dkms add -m keucr -v 0.0.1
#dkms build -m keucr -v 0.0.1
#dkms install -m keucr -v 0.0.1
#cat keucr >> /etc/modules


more info

debian lenny and canon canoscan lide 110

Installing canoscan lide 110 scanner in debian


#cd /usr/src
#git clone git://git.debian.org/sane/sane-backends.git
#cd sane-backends
#./configure --prefix=/usr --sysconfdir=/etc/ --localstatedir=/var
#make
#make install
#adduser scanner

edit /etc/udev/rules.d/z60_libsane.rules


# Canon CanoScan Lide 110
ATTRS{idVendor}=="04a9", MODE="0664", GROUP="scanner", ATTRS{idProduct}=="1909", ENV{libsane_matched}="yes"

make sure you put the scanner to unlock mode (there is a button on the bottom) otherwise it make a loud cracking sound and it is not working.

#aptitude install xsane

mount directory over ssh

#aptitude install sshfs
#modprobe fuse
#sshfs user@server:/remote/dir /local/dir/

Error wireless request set encode 8b2a


iwconfig wlan0 set s:passphrase

It only works on WEP. WPA is not supported.
You need to install wicd or wpa_supplicant.
Edit the /etc/network/interfaces and remove any references to wlan0


#apt-get install wicd
$wicd-client

more

linux convert youtube to mp3

#aptitude install youtube-dl ffmpeg libmp3lame

a simple bash script called youtube

#!/bin/bash
x=/tmp/youtube-dl-$RANDOM-$RANDOM.flv
youtube-dl --output=$x --format=18 "http://www.youtube.com/watch?v=$1"
echo "convert flv to mp3"
ffmpeg -i $x -acodec libmp3lame -ac 2 -ab 128k -vn -y "/home/paragasu/mp3/youtube/$2"
rm $x
echo "done"

The fun begin

$youtube linkname fileoutput.mp3

Related
Youtube to mp3 on ubuntu linux

burn cd


$genisoimage -vJV "name" -o isoname.iso list_folder_or_file
$wodim -v isoname.iso

upgrade debian etch 4.0 to lenny 5.0

Debian drop security support for etch.
Edit /etc/apt/sources.list & change all etch to lenny


#apt-get update
#apt-get install apt dpkg aptitude
#aptitude keep-all
#aptitude full-upgrade

FATAL: module fbcon not found

Recent debian upgrade cause my X server failed to start.

linux-image-2.6.32
xserver-xorg 7.5
i915 intel graphics

you can ignore the error FATAL: module fbcon not found.
the real problem might be in

$cat ~/.xsession-errors

In my case the problem is the im-switch missing default configuration files.
reinstalling im-switch solved the problem.

php anonymous object


$obj = (object) array('hello' => 'world', 'sumandak' => 'tamparuli');

echo $obj->hello; //world

creating a pdf preview


$im = new imagick('test.pdf[0]'); //1st page
$im->setImageFormat('png');
header('Content-Type: image/png');
echo $im;


more

preload images with jQuery


var photos = [ {img:'img1.jpg'}, {img: 'img2.jpg'}];

$(photos).each(function() {
(new Image()).src = this.img;
});

Centos 5.4 MySQL only 480 error messages, but it should contain at least 641 error messages.


Error message file '/usr/share/mysql/english/errmsg.sys' had only 480 error messages,
but it should contain at least 641 error messages.


#yum list installed | grep mysql

In my case, the both package mysql.i386 and mysql.x86_64 is installed. So, i have to remove the mysql.i386 package (old version) and reinstall mysql.x86_64.


#yum remove mysql.i386
#yum install --enablerepo=remi mysql.x86_64
#service mysqld start

problem solved

How to install PostgreSQL 8.3 into CentOS 5.4

PostgreSQL 8.1 is currently the default version in CentOS 5.4 which do not support INSERT.. RETURNING

remove PostgreSQL 8.1

#yum remove postgresql postgresql-server


# vi /etc/yum.repos.d/CentOS-Base.repo
[base]
exclude=postgresql*
[updates]
exclude=postgresql*


#wget http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-7.noarch.rpm
#rpm -ivh pgdg-centos-8.3-6.noarch.rpm
#yum install postgresql postgresql-server

Debian Etch pg_dumpall cron problem

Debian Etch default postgresql's superuser is postgres. And cron run as root.
Hence, pg_dumpall not working as expected in cron job. Workaround is to create user name root with superuser privilege.


postgres# create role root with superuser login

p/s: you have to create database root

debug php file_get_contents($url)

there is one special variable available $http_response_header.
the output is the header array reply by the server


$r = file_get_contents($url);
var_dump($http_response_header);

how to save file into postgresql database

you need a column in a postgresql table with the type OID

create table files(
file_id serial primary key,
file oid not null
);

to insert file

INSERT INTO files(file) values(lo_import('/tmp/filename.ext');

to read the file

SELECT lo_export(file, '/tmp/filename.ext') WHERE file_id=2;

you can get the file in the /tmp/filename.ext.

store upload image postgresql

autologin with startx

edit /etc/inittab
comment out the line

#1:2345:respawn:/sbin/getty 38400 tty1

add the line

1:2345:respawn:/bin/login -f YOUR_USER_NAME tty1 /dev/tty1 2>&1

edit the .bash_profile and add

startx

autologin in debian

debian testing + iceweasel install flash player


#apt-get install flashplugin-nonfree

should be working. but in my debian testing it isn't. I have to manually create a symlinks


#ln -s /usr/lib/flashplugin-nonfree/libflashplayer.so /usr/lib/iceweasel/plugins/libflashplayer.so

to make it work.

jquery click li to activate a

<ul class="menu">
<li><a href="/"> Home </a></li>
</ul>

to activate the link when user click on li

$('.menu li').click(function(e){
location.href = $(this).find('a').attr('href');
});

Now, user doesn't have to click on the "Home" to activate the link.

mysql cache SQL_NO_CACHE

enable query cache (maybe default depends of the server configuration)

SELECT SQL_CACHE SUM(points) FROM account;

turn off mysql query cach

SELECT SQL_NO_CACHE SUM(points) FROM account;


the mysql query cache

Debian usb mouse freeze

you should have

Option "SendCoreEvents" "true"

inside the Section "Input Device", Driver "mouse"

ncftp - upload recrusive files

to upload the whole directory and subdirectory


$ncftpput -u <username> -p <password> -R <host> <remotedir> <localdir>

Bucardo - Asynchronous PostgreSQL Replication System

Bucardo is an asynchronous PostgreSQL replication system, allowing for both multi-master and multi-slave operations. It was developed at Backcountry.com by Jon Jensen and Greg Sabino Mullane of End Point Corporation, and is now in use at many other organizations.


bucardo

css rounded corner


.roundcorner{
border-radius:6px; /*css3 - but not supported yet*/
-webkit-border-radius: 6px; /*mozila - firefox, iceweasel */
-moz-border-radius: 6px; /*webkit - google crome, midori, safari */
}

and more

-moz-border-radius-topleft / -webkit-border-top-left-radius

postgresql add on delete cascade to foreign key


ERROR: update or delete on table "page" violates foreign key constraint "info_page_id_fkey" on table "info" DETAIL: Key (page_id)=(106) is still referenced from table "info"

you have to drop cascade and recreating the new one.

psql> \d info


psql> alter table info drop constraint info_page_id_fkey;
psql> alter table info add constraint "info_page_id_fkey" foreign key(page_id) references page on delete cascade;

chess in debian

Crafty, developed by Robert Hyatt, is a descendant of the Cray Blitz chess engine that was the World Computer Chess Champion from 1983 to 1989.

to install

#apt-get install crafty xboard

start the game with

$xboard -fcb 'crafty' -fd crafty_directory

book off -- This options disables the use of opening book for crafty.
ponder off - Crafty can't think while you are playing your move.
st 1 -- Make the maximum thinking time for Crafty just one second.
sd n -- Crafty won't think more than n moves ahead.
If you are able to beat crafty too often, you can also make it more stronger with these options:
hash nK -- Makes the hash table bigger
hashp n -- Makes the hash table for pawns as large as possible

it hard to bet.


more info

fix Firefox 3 & jquery bug

It is the problem when the $(document).ready() executed before the CSS loaded.
Make sure all CSS come before the scripts


<script type="text/javascript" src="">
<link rel="stylesheet" type="text/css" href="">

to


<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript" src="">

fix ff3 issues

fix pidgin & yahoo messenger Error 1013

you must upgrade to pidgin 2.5.8 which is available in debian unstable (sid).
add to /etc/apt/sources.list

deb http://ftp.debian.org/debian/ sid main contrib non-free


#apt-get update
#apt-get install -t sid pidgin

change the pager server to

scsa.msg.yahoo.com

Error 1013 - just remove the @yahoo.com on your pidgin login username

make all image clickable

make all image in a page to have a direct link.


$content = ''; //content of a page with <img tag
$content = preg_replace('/<img alt=".*" \/>/',
'<a href="\\1">\</a>', $content);

preg_replace manual

dns with minimum downtime

it is important to change the TTL setting of the domain to a short time (60s) before migrating to new server.
and wait for the dns record to propagate before changing the dns records.

powerdns + postgresql on debian


#apt-get install pdns-server
#apt-get install pdns-backend-pgsql

install required postgresql database table.
using /usr/share/doc/pdns-backend/pgsql/pgsql.sql

edit /etc/powerdns/pdns.d/pdns.local ( /usr/share/doc/pdns-backend-pgsql/examples/pdns.local.pgsql)

gpgsql-host=localhost
gpgsql-port=5432
gpgsql-dbname=powerdns
gpgsql-user=
gpgsql-password=

edit /etc/powerdns/pdns.conf

launch=gpgsql


postgresql + mysql

pdns everydns.net as secondary dns

in /etc/powerdns/pdns.conf

allow-axfr-ips=71.6.202.218,66.240.223.182
disable-axfr=no
disable-tcp=no
master=yes

make sure you insert the value 'MASTER' on the column 'type' in the domains table

add the domain with advance option "make secondary using", and specify the primary dns (server ip where you install powerdns).

the last thing to do is to modify the domain dns records to

ns1.everydns.net
ns2.everydns.net
ns3.everydns.net
ns4.everydns.net


powerdns on debian lenny

nginx www to non www

redirect url with www to non www. edit /etc/nginx/nginx.conf or /etc/nginx/sites-enabled/default

if ($host ~* www\.(.*)){
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent;
}

how to change timezone and UTC in debian

to change timezone

#dpkg-reconfigure tzdata

UTC time mean, you computer will display time related to GMT. To use local time instead of UTC
edit /etc/default/rcS

UTC=no

ssh - iptable rule to accept only streamyx users.

I got ssh brute force attack almost every day :p, which is almost all originated from somewhere outside malaysia (china, taiwan etc). A simple iptables rules that only allowed tcp traffic from streamyx IP range.

#iptables -P INPUT DROP
#iptables -A INPUT -p tcp --dport 80 -j ACCEPT
#iptables -A INPUT -p tcp --dport 22 -m iprange --src-range 60.0.0.0-60.255.255.255 -j ACCEPT


iptables - how to specify a range of ip address

iptables quick howto-

postgresql complete backup

run command under user postgres

to backup

$pg_dumpall > db.sql

to restore

$psql -f db.sql template1

display battery information on fbpanel

i wrote a simple plugin to display the percentage of battery on fbpanel (i am using openbox + debian)

put this code inside ~/.config/fbpanel/default

Plugin {
type=genmon
config {
Command = echo $(acpi -b | cut -d, -f2)
PollingTime = 2
TextSize = small
TextColor = red
}
}

this is how it look like
fbpanel battery status

simple iptables rule to block ip address

block an ip address

#iptables -A INPUT -s 192.168.2.3 -j DROP

block outgoing TCP traffic from the server

#iptables -A OUTPUT -p tcp -d 192.168.2.3 -j DROP

upgrade postgresql-8.1 to postgresql-8.3 in debian etch

postgresql-8.3 available for etch on backports repositories. Add to /etc/apt/sources.list

deb http://www.backports.org/debian etch-backports main contrib non-free

then install postgresql-8.3

#apt-get -t etch-backports install postgresql-8.3
#pg_dropcluster --stop 8.3 main
#pg_upgradecluster 8.1 main
#pg_dropcluster --stop 8.1 main
#apt-get remove postgresql-8.1


read more

extract text from ms office

Interesting program to extract text

  • catdoc - extract text from ms word
  • xls2cvs - extract text from ms excell
  • pdftotext - extract text from pdf
  • ppthtml - extract text from ms. power point

Then a simple php function can capture the output eg:

function extractWord($word_file)
{
if (file_exists($word_file)
{
// prevent malicious command execution
exec("/usr/bin/catdoc -w ' . escapeshellarg($word_file), $output);

// $output is an array corresponding to lines of output
return join("\n", $output);
}
}

extracting text from office and pdf file

inverting value in mysql table

It is possible to invert the value in mysql table without knowing the present value. This working on mysql and may not work on postgresql.


UPDATE table_name SET column = NOT column

ie6,ie7 min-height bug and margin bug fixed

I come across this stupid IE bug and it really waste a lot of my time. The worst thing is, my client use IE6 in his office computer and whenever i went to his office showing him his website. Everything look terrible.

it should look like this
iceweasel

Image offset to the right
ie7

Image offset to the right and the web page is too short
ie6

I am not sure it is fixed or it just a dirty workaround. But here it is

ul.innerfade li {
_margin-left:-425px; /*ie6 fix*/
*margin-left:-425px; /*ie7 fix */
}

and another one in the td (html)

style="_height:350px;"


CSS hacks
IE7 only hacks

IE bug fix

IE bug fix

1. no min-height
_height:auto !important;

2. preventing step down
float:left; display:inline;

3. haslayout


/* style for IE6 + IE5.5 + IE5.0 */
.gainlayout { height: 0; }

.gainlayout { zoom: 1; }

4. peekaboo bug fix

position: relative; /* peekaboo bug fix for IE6 */
min-width: 0; /* peekaboo bug fix for IE7 */

list of IE7 bugs

i hate IE. it took me a week just to fix a web page that works perfectly fine on other browsers even my web page is already pass w3c xhtml validation tests. I come across this a page with complete detailed of all IE7 related problem. In case you don't know how terrible IE7 browser it. read

MSIE7 bugs

display new icon based on db timestamp

this works in mysql5+. we want to display a small icon if the post_date is less than 2 days old. Unix timestamp is second. so for 2 days

60 * 60 * 24 * 2 = 172800

SQL query

SELECT IF((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(post_date)) < 172800, 1, 0) AS is_new FROM tbl_news

then the php code will be

$p = mysqli_fecth_object($sql)
$p->is_new ? echo '<img src="new.gif">' : '';

gui wireless utility

you may try wicd as a wireless manager

debian install howto
edit /etc/apt/sources.list and add

deb http://apt.wicd.net lenny extras

then

#apt-get update
#apt-get install wicd

to start simply

#wicd-client

wicd project homepage

print a-z

I need to create a link from a to z. I come up with a simple way to do it.

/* a-z */
$str = '';
for($i = 65; $i < 91; ++$i)
echo ''.chr($i).'';

another way

$a = range('a', 'z');
foreach($a as $chr) echo $chr;

mysql prepared statement

Prepared statement is one good way to avoid sql injection.

mysql> PREPARE stmt_name FROM "SELECT name FROM Country WHERE code = ?";
Query OK, 0 rows affected (0.09 sec)
Statement prepared

mysql> SET @test_parm = "FIN";
Query OK, 0 rows affected (0.00 sec)

mysql> EXECUTE stmt_name USING @test_parm;
+---------+
| name |
+---------+
| Finland |
+---------+
1 row in set (0.03 sec)

mysql> DEALLOCATE PREPARE stmt_name;
Query OK, 0 rows affected (0.00 sec)


More

copy files 100 times

Some interesting question asked on mailing list. A few interesting solutions in bash script.

$for x in $(seq -w 1 100); do cp file.jpg file${x}.jpg; done


for I in {1..100}; do cp file.jpg file$I.jpg ; done


$ seq -w 1 1 10 | xargs -i -n1 cp file.jpg file{}.jpg

css blueprint generator

CSS is quite simple if you only use firefox. But, thing get complicated when you considering IE.
I found a very useful css grid generator. click here

very low memory mysql 5 my.cnf configuration

on VPS server with very limited memory it is good to tweak mysql5. In /etc/mysql/my.cnf

# Main MySQL server options
[mysqld]
port = 3306
socket = /var/run/mysqld/mysqld.sock

# No locking at all!
skip-locking

# Set internal buffers, caches and stacks very low
key_buffer = 16K
max_allowed_packet = 16K
table_cache = 1
sort_buffer_size = 16K
read_buffer_size = 16K
read_rnd_buffer_size = 1K
net_buffer_length = 1K
thread_stack = 16K

# Don't listen on a TCP/IP port at all.
# Will still work provided all access is done via localhost
skip-networking
server-id = 1

# Skip Berkley and Inno DB types
skip-bdb
skip-innodb

# Set the query cache low
query_cache_limit = 1048576
query_cache_size = 1048576
query_cache_type = 1

# Set various memory limits very low, disable memory-hogging extras
[mysqldump]
quick
max_allowed_packet = 16K
[mysql]
no-auto-rehash
[isamchk]
key_buffer = 16K
sort_buffer_size = 16K
[myisamchk]
key_buffer = 16K
sort_buffer_size = 16K
[mysqlhotcopy]
interactive-timeout


More info

Wireless in Linux

you have to install the package wireless-tools

#apt-get install wireless-tools

iwconfig - manipulate the basic wireless parameters
iwlist - allow to initiate scanning and list frequencies, bit-rates, encryption keys...
iwspy - allow to get per node link quality
iwpriv - allow to manipulate the Wireless Extensions specific to a driver (private)
ifrename - allow to name interfaces based on various static criteria

Interesting wireless scripts

NEC Versa S5500 + Intel PRO/wireless 4695 AG driver

you must install the kernel 2.6.26-1-686, wpasupplicant and firmware-iwlwifi, wireless-tools to get intel pro/wireless 4695 to work.

then in /etc/network/interfaces

#auto wlan0
iface wlan0 inet dhcp
pre-up (echo ‘Modprobing iwl4965′) && /sbin/modprobe iwl4965
post-down (echo ‘Removing iwl4965′) && /sbin/modprobe -r iwl4965
wpa-ssid YOURNETNAMEAKASID
wpa-key_mgmt WPA-PSK
wpa-proto WPA
wpa-pairwise TKIP
wpa-group TKIP
wpa-psk “yourpassphrase”
wpa-driver wext

to activate the wireless driver

#ifup wlan0

more info

How to install dig?

dig is a little program to query dns records. dig belong to the package dnsutils.

#apt-get install dnsutils

usefull x window utility

xdpyinfo - you can check resolutions
xrandr - check current screen resolution and refresh rate
lspci or lshw - check what is your graphic card
gtf - generate modeline for xorg.conf

fast debian mirror

i found a fast debian mirror that can archive up to 160kBps (on peak time around 60kBps) compared to the ftp.debian.org (11kBps). I am using streamyx 1Mbps and staying in kota kinabalu.


deb http://mirror.pacific.net.au/debian lenny main contrib non-free

how to avoid ssh timeout

i always face with this problem every time i use ssh client from new installed debian system. Edit the /etc/ssh/sshd_config


ClientAliveInterval 300
ClientAliveCountMax 10

On client side, in $HOME/.ssh/config or /etc/ssh/ssh_config

ServerAliveInterval 30
ServerAliveCountMax 10

Make sure the ssh server using Protocol 2
Check man ssh_config and sshd_config for more info

howto install window codecs

You cannot play *.avi files with win32codecs. You definitely need one.

edit you /etc/apt/sources.list

deb http://ftp.tw.debian.org/debian-multimedia/ stable main


#apt-get update
#apt-get install win32codecs

you can use any mirror from debian-multimedia.org. I am using Taiwan mirror servers because it is quite fast, considering that i am in kota kinabalu.

Local dns cache with dnsmasq

local cache for faster internet browsing.


#apt-get install dnsmasq

in /etc/dnsmasq.conf

listen-address=127.0.0.1

in /etc/dhcp3/dhclient.conf

prepend domain-name-server 127.0.0.1;

in /etc/resolv.conf

nameserver 127.0.0.1

The last thing you need to do

#/etc/init.d/dnsmasq restart
#/etc/init.d/networking restart

Another interesting package that does the same thing is pdnsd. The best thing about pdnsd is, it saves the dns cache in disk which is still available even after you reboot.


More info on dnsmasq

pdnsd info
How to setup pdnsd

tagged by sandra. something about me

i am relatively new on this blogging world. and honestly i am not really good in writing. LOL, i should write something about me supposed to be a month ago. But i am relative slow to pick up what it mean by tagged. Anyway, better late than never. so here is a 7 funny or weird fact about me.

wait. i don't even know where i should start. LOL

pwgen - password generator

from the project homepage, it says

password generator which creates password which can be easily memorized by human


#apt-get install pwgen

It does have a -y switch to include special characters in the generated password. try

$pwgen -syB
m=g_L3on
\d?7ans^
[J7\{xwo

nice!
pwgen homepage

resize photo using imagick

i use a very old laptop - VIA C3 1Ghz + 256MB memory with broken fan.
I have about 200MB photos in one folder with 1MB size each. Resizing with Gimp is not an option because it takes few minutes to even show or display the content of the folder.
I wrote simple but practical bash script resize.sh


#!/bin/bash
for i in *.JPG
do
if [-e "thumbs/$i"]; then
echo "$i exists"
else
echo "resize $i"
convert "$i" -resize 600x450 "thumbs/$i"
fi
done
echo "finish"

I simply run the script and go outside watching movie. It takes almost hours to finish
Sometime it just stop half way. Have to re-run the scripts to make the whole thumbnails.

The best solutions might be to get a new computer.

delete all gedit backup files

by default gedit will maintain a copy of files being edited with the prefix ~.

it is irritating sometimes to have this files uploaded to the server. a simple way to delete this file will be

$find . -name *~ -exec rm '{}' \;

postfix + postgresql

we can use postgresql to store postfix configuration.

#apt-get install postfix postfix-pgsql

edit the configuration /etc/postfix/main.cf

alias_maps = pgsql:/etc/postfix/pgsql-aliases.cf

then in /etc/postfix/pgsql-aliases.cf

host =
username=
password=
db_name=
query=
select_field=
table=
where_field=
additional_conditions=

more from postfix documentation

multiple ip address on linux

debian etch


#ifconfig eth0:1 192.168.1.7
#ifconfig eth0:2 192.168.1.8


restart the networking service

#/etc/init.d/networking restart

ifup eth0 vs ifconfig eth0 up


#ifup eth0
#ifconfig eth0 up

both work the same way. ifup will configure network based on /etc/network/interfaces.
ifconfig use to configrue kernel resident network interfaces

forex exchange rate

one of my client asking me to write a software for his money changer company. The current exchange rates can
be downloaded from

http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
http://www.bnm.gov.my/statistics/exchangerates.php

convert video to flv

ffmpg and memcoder


hardy2@hardy2-laptop:~$ cat .bin/video-flv_png
#!/bin/bash
filename="$@"
filename=${filename%.*}
ffmpeg -sameq -i "$@" -s 640x480 -ar 44100 -r 25 $filename.flv -pass 2
ffmpeg -itsoffset -0 -i "$@" -vcodec png -vframes 1 -an -f rawvideo
-s 640x480 $filename.1.png
ffmpeg -itsoffset -0.5 -i "$@" -vcodec png -vframes 1 -an -f
rawvideo -s 640x480 $filename.2.png
ffmpeg -itsoffset -1 -i "$@" -vcodec png -vframes 1 -an -f rawvideo
-s 640x480 $filename.3.png

by dotanchoen.com

Vagrind

a memory error detector, a thread error detector, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler, a data race detector, and an instant memory leak detector

valgrind project homepage

new gtkimageviewer

From Dov Grobgeld

a major rewrite (using gob2 actually) where the image annotation model has been changed so that the image is provided to the user of the widget before it is drawn to the screen.

gtkimageviewer tutorial

magical square root


/*
================
SquareRootFloat
================
*/
float SquareRootFloat(float number) {
long i;
float x, y;
const float f = 1.5F;

x = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( f - ( x * y * y ) );
y = y * ( f - ( x * y * y ) );
return number * y;
}

Original article from code maestro

How to find not unique row in the table


test=*# select * from dup;
a | b
---+---
1 | 1
1 | 2
2 | 1
1 | 1
3 | 3
3 | 3
(6 rows)

test=*# select * from dup where (ctid,a,b) not in (select distinct on (a,b) ctid,* from dup);
a | b
---+---
1 | 1
3 | 3
(2 rows)

another approach:

select a,b from dup group by a,b having count(*) > 1;

pgsql-general mailing list

How to display busy cursor

Interesting post on gtk-app-devel-list@gnome.org mailing list

void busy_stuff ()
{
  GdkDisplay *display;
  GdkCursor *cursor;
  GdkWindow *window;
  gint x, y;

  cursor = gdk_cursor_new(GDK_WATCH);
  display = gdk_display_get_default();
  window = gdk_display_get_window_at_pointer(disp, &amp;x, &amp;y);
		gdk_window_set_cursor(window, cursor);
  gdk_display_sync(display);
  gdk_cursor_unref(cursor);

  /* do time-consuming stuff here */
  gdk_window_set_cursor(window, NULL);

}

gdk_cursor_unref() prevent memory leak

More on Mailing list archive

Using g_value_get_*

Using GValue related function is quite tricky. It is not working if you do

GdaDataModel *dm;
gint i;
i = g_value_get_int ( gda_data_model_get_value_at (dm, 0, 0));

For upcomming Version 4.0 (the main difference is at GdaDataModel API)

GdaDataModel *model;
const GValue *integer;
GError *error = NULL;
integer = gda_value_new (G_TYPE_INT);
integer = gda_data_model_get_value_at  (model, 0, 0, &error);

All values in a Data Model must be unmodificable then use const GValue, this will avoid compilation warnings. Or can use (gda_value_new makes this for you :-)

integer = g_new0 (GValue. 1);
g_value_init (inteteger, G_TYPE_INT);

Thanks to Daniel Espinosa

Gtk undefine reference

Header file and function on separate file should not have the static function declaration.

static void loan_new_record (gpointer data);
static void loan_display_reset ( GtkWidget *data); 

to

void loan_new_record (gpointer data);
void loan_display_reset ( GtkWidget *data);

Read more

Align gtk label using gtk_misc_set_alignment()

When packing a gtk label inside gtk table. I come across one problem. All the label as aligned center.
As a result i just made one ugly form. To fix the problem, use gtk_misc_set_alignment().

Gtk screenshot

See code example

#include <gtk/gtk.h>
int main (int argc, char **argv)
{
  GtkWidget *window;
  gtk_init( &amp;argc, &amp;argv);
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  GtkWidget *table = gtk_table_new( 4, 1, TRUE );
  GtkWidget *label;
  label = gtk_label_new("Normal label");
  gtk_table_attach_defaults ( GTK_TABLE(table), label, 0, 1, 0, 1)
  label = gtk_label_new( "left" );
  gtk_misc_set_alignment( GTK_MISC(label), 0.0, 0.0 );
  gtk_table_attach( GTK_TABLE(table), label, 0, 1, 1, 2,
                    GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
  label = gtk_label_new( "center" );
  gtk_misc_set_alignment( GTK_MISC(label), 0.5, 0.0 );
  gtk_table_attach_defaults( GTK_TABLE(table), label, 0, 1, 2, 3
                             GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
  label = gtk_label_new( "right" );
  gtk_misc_set_alignment( GTK_MISC(label), 1.0, 0.0 );
  gtk_table_attach_defaults( GTK_TABLE(table), label, 0, 1, 3, 4
                             GTK_EXPAND|GTK_FILL, GTK_SHRINK, 0, 0 ); /*important*/
  gtk_widget_set_size_request (GTK_WIDGET (table), 200, 100);
  gtk_container_add( GTK_CONTAINER (window), GTK_WIDGET(table));
  gtk_widget_show_all(window);
  gtk_main();
  return 0;
}

Thanks to owl102 from gtkforums.com

Select row in GnomeDbRawGrid

GnomeDbRawGrid come from GtkTreeView widget. So we can select row using gtk_tree_view_selection_select_iter() and get the current selected row gtk_tree_view_get_selection().

GnomeDbRawGrid *grid;
GtkTreeView *tree_view;
tree_view = GTK_TREE_VIEW (grid);

Related
Gnome db raw grid

save image and display image from postgresql

There is several way to save image into postgresql database. Using oid, blob and bytea data types.bytea column type recommended.

To store image

gdk_pixdata_from_pixbuf(),
gdk_pixdata_serialize()

To display image

gdk_pixdata_deserialize(),
gdk_pixbuf_from_pixdata(),
gtk_image_new_from_pixbuf() 

Thanks to vivien and Yann Droneaud for great help

Related
Gdk Pixbuf inline
Libgnomedb example

alternative nameserver

Just found one free domain name server run by one of malaysian open source supporter angch.

DNS IP: 202.190.85.116

It should be better than TM dns because not too many people use it or OpenDNS since it is located in malaysia.

Visit Angch blog

String with dinamicaly growing buffer

String is where buffer overflow always occur. GLIB supports doing this much more easily:

/* portable asprintf() */
char *str = g_strdup_printf("string%s%d", str_variable, int_variable);

Or if you wanted a modifyable buffer:

GString *str = g_string_new(NULL);
g_string_append(str, "string");
g_string_append(str, str_variable);
g_string_sprintfa(str, "%d", int_variable); /* no g_string_append_int() */

Related
Secure, Efficient and Easy C programming

C variable definition

extern - Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.

static - The static data type modifier is used to create permanent storage for variables. Static variables keep their value between function calls. When used in a class, all instantiations of that class share one copy of the variable.

const - The const keyword can be used to tell the compiler that a certain variable should not be modified once it has been initialized.

More C definition here

Using Makefile

If you writing gtk application. You will have to use more than one source file to make the code more manage able. To compile the application you need to use make. Makefile image

It is all you need to compile a c code with libgnomedb. This code will output an executable file with name ekoken. A more complicated makefiles using variable is like this

CC = gcc
LD = gcc
CFLAGS =
RM = rm -f
LDFLAGS = `pkg-config --libs gtk+-2.0`
PROG =
OBJS =

all : $(PROG)
%.o : %.c
$(CC) $(CFLAGS) -c $&lt; -o $@
$(PROG) : $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(PROG)

clean :
$(RM) $(OBJS) $(PROG)

Where PROG is the executable output and OBJS is the object file output with .o suffix.

Related
Makefile in C or C++
A simple makefile tutorial

Design pattern

Design pattern is somehow overlook in many newbie tutorial. But it is very important to know before even writing the code. I found a list of design pattern for PHP

Design Pattern

Hello world!

I think it is better to start with

<?
php echo "hello world";
?>