CSS Skills

1. CSS Reset

http://meyerweb.com/eric/tools/css/reset/index.html

http://meyerweb.com/eric/tools/css/reset/reset.css

 

2. CSS Hack

.test {
    padding:10px;
    padding:9px\9; /* all ie */
    padding:8px\0; /* ie8-9 */
    *padding:5px; /* ie6-7 */
    +padding:7px; /* ie7 */
    _padding:6px; /* ie6 */
}
Posted in CSS | Tagged | Leave a comment

Simple Wrapper of Zend Controller

My simple wrapper of Zend Controller. It has 5 features including getParam, redirector, json and flash message.

 

/**
 * class App_Controller_Abstract
 *
 * @author kim
 */

class App_Controller_Abstract extends Zend_Controller_Action
{
    /**
     * wrapper of _getParam
     *
     * @return mixed|string
     */

    protected function _g($key, $default = null)
    {
        return $this->_getParam($key, $default);
    }

    /**
     * redirect URL of the form /module/controller/action/params
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */

    protected function _r($action, $controller = null, $module = null, array $params = array())
    {
        $this->_helper->redirector($action, $controller, $module, $params);
    }

    /**
     * output json
     *
     * @return void
     */

    protected function _j($data, $isReturn = false, $params = array())
    {
        if ($isReturn) {
            return $this->_helper->json($data);
        } else {
            $this->_helper->json->sendJson($data, $params);
        }
    }

    /**
     * set flash message by namespace and content
     *
     * @param string $namespace
     * @param string $message
     * @return void
     */

    protected function _setFlashMessage($namespace, $message)
    {
        $flashMessenger = $this->_helper->flashMessenger;
        $flashMessenger->setNamespace($namespace);
        $flashMessenger->addMessage($message);
    }

    /**
     * get flash message
     *
     * @param string $namespace - namespace for message
     * @return string
     */

    protected function _getFlashMessage($namespace)
    {
        $flashMessenger = $this->_helper->flashMessenger;
        $flashMessenger->setNamespace($namespace);
        $messages = $flashMessenger->getMessages();
        if (count($messages) > 0) { return $messages[0]; }
        else { return ''; }
    }

}
Posted in Zend Framework | Tagged , | Leave a comment

Flow Flash AD using JavaScript and SWFObject

This article shows how to create a flow flash ad by using javascript together with swfobject.

@see getScroll.js
@see http://code.google.com/p/swfobject/

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <title>flash flow ad using swfobject</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="getScroll.js"></script>
    <script type="text/javascript" src="swfobject.js"></script>
</head>
<body>
    <!--main content-->
    <div style="height:2000px;">content</div>

    <!--ad-->
    <div id="ad-flow" style="top:5px; left:100px; position:absolute;">
        <div id="ad-test"></div>
        <a style="text-align:left; display:block; background:#eee; width:120px;" href="javascript:void(0)" onclick="javascript:closeAd();" hidefocus="true">关闭</a>
    </div>

    <!--the flow ad script -->
    <script type="text/javascript" src="ad-flow.js"></script>
</body>
</html>


The ad-flow.js goes here :

// to close the ad and stop interval heart beat
function closeAd(id)
{
    document.getElementById('ad-flow').style.visibility = "hidden";
    document.getElementById('ad-test').style.visibility = "hidden";
    window.clearInterval(int);
}

// global value to log the last position
var lastY = 0;

// the heart beat function
function heartBeat()
{
    // get current top position
    var curY = getScroll().t;

    // speed : the bigger the faster
    var speed = 0.05;
    percent = speed * (curY - lastY);
    if (percent > 0) percent = Math.ceil(percent);
    else percent = Math.floor(percent);

    // keep stay there!
    document.getElementById("ad-flow").style.top = parseInt(document.getElementById("ad-flow").style.top)
                                                                   + percent + "px";

    // log last position
    lastY = lastY + percent;
}

// beat every 1 microsecond
window.setInterval("heartBeat()", 1);

// flash ad embed by swfobject
var flashvars = {};
var params = {
    // important for getUrl() in flash
    allowscriptaccess : "always"
};
var attributes = {};
swfobject.embedSWF(
    "http://static.kimbs.cn/ad-test.swf",
    "ad-test",
    "120",
    "270",
    "9.0.0",
    "expressInstall.swf",
    flashvars,
    params,
    attributes
);

Posted in Flash, JavaScript | Tagged , | Leave a comment

JavaScript Get Scroll Information

The script goes here : getScroll.js

// get scroll information (cross-browser compatibility)
function getScroll()
{
    // t for top, l for left, w for width, h for height
    var t, l, w, h;
    if (document.documentElement && document.documentElement.scrollTop) {
        // IE6 standards compliant
        t = document.documentElement.scrollTop;
        l = document.documentElement.scrollLeft;
        w = document.documentElement.scrollWidth;
        h = document.documentElement.scrollHeight;
    } else if (document.body) {
        // DOM compliant
        t = document.body.scrollTop;
        l = document.body.scrollLeft;
        w = document.body.scrollWidth;
        h = document.body.scrollHeight;
    } else if (typeof(window.pageYOffset) == 'number') {
        // Netscape compliant
        t = window.pageYOffset;
        l = window.pageXOffset;
        w = window.innerWidth;
        h = window.innerHeight;
    } else {
        alert('Error!');
    }
    return {t: t, l: l, w: w, h: h};
}

Posted in JavaScript | Tagged | Leave a comment

Introduction to MongoDB

Installation on Windows :



1. Download and install

http://fastdl.mongodb.org/win32/mongodb-win32-i386-1.6.5.zip

unzip mongodb-win32-i386-1.6.5.zip to D:\mongodb

2. Create folder where database located

$ mkdir D:\mongodb\data
$ mkdir D:\mongodb\data\db


3. Start mongodb server

$ cd D:\mongodb\bin
$ mongod.exe --dbpath=D:\mongodb\data\db --rest

4. Web tool : http://localhost:28017/

 

 

5. Client tool for mongodb

$ mongo.exe


6. Create collection called mytestdb and limit the size (in fact we must use client tool)
> db.createCollection("mytestdb", {capped:true, size:100000})
> show collections


7. Driver for windows

https://github.com/mongodb/mongo-php-driver/downloads

https://github.com/downloads/mongodb/mongo-php-driver/mongo-1.1.3.zip

unzip mongo-1.1.3.zip
put mongo-1.1.3\mongo-1.1.3-php5.3vc6ts\php_mongo.dll to D:\xampp\php\ext\php_mongo.dll

# modify php.ini
extension=php_mongo.dll




Installation on Linux :



1. Download and install

$ curl http://downloads.mongodb.org/linux/mongodb-linux-i686-1.6.4.tgz > mongo.tgz
$ tar xzf mongo.tgz


2. Create folder where database located
$ sudo mkdir -p /data/mongo/db/
$ sudo chown `id -u` /data/mongo/db/


3. Help and Launch
$ ./mongo/bin/mongod --help
$ ./mongo/bin/mongod --dbpath=/data/mongo/db/


4. Client tool for mongodb
$ ./mongo/bin/mongo



Operations :



1. Mongo instance and database connection

// connect to database server
$mongo = new mongo("192.168.0.132:27017");
// select database to handle
$db = $mongo->selectDB("mytest");
// select collection (just like table in mysql)
$collection = $db->selectCollection("cartoons");


2. Insert
$myinfo = array(
    'name' => 'Kim',
    'email' => 'xqpmjh@gmail.com',
    'sessions' => 0,
);
$safe_insert = true;
// $person is passed by reference
$collection->insert($person, $safe_insert);
echo $myid = $myinfo['_id'];


3. Query
// find the person by both email and sessions exists
$filter = array(
    'email' => 'xqpmjh@gmail.com',
    'sessions' => array('$exists' => true),
);
// order by sessions desc
$cursor = $collection->find($filter)->sort(
    array('sessions' => -1)
);
// show total docs
echo $total = $cursor->count();
// skip the first one and limit 3 docs
$cursor->limit(3)->skip(1);
foreach ($cursor as $user) {
    var_dump($user);
}


4. Create index
$collection->ensureIndex(
    array('email' => 1),
    array('unique' => true, 'background' => true)
);


5. Update
$filter = array('email' => 'xqpmjh@gmail.com');
$new_document = array(
    // increase sessions by one
    '$inc' => array('sessions' => 1),
    // set new name
    '$set' => array(
        'name' => 'kimho',
    ),
    // unset second address
    '$unset' => array('address.1' => 1),
);
// for duplicated records
$options['multiple'] = false;
$collection->update(
    $filter,
    $new_document,
    $options
);


6. Store big file (like video)
$grid = $db->getGridFS();
$metadata = array(
    "filename" => "foo.avi",
    "comment" => "wooooooo!",
    "permissions" => array(
        "kim" => "write",
        "everybody" => "read",
    )
);
$grid = $db->getGridFS();
$grid->storeFile("/data/video/avatar.avi", $metadata);


7. Remove
// remove document which sessions equ 8
$filter = array('sessions' => 8);
$single = true;
$collection->remove($filter, $single);




References :

http://us.php.net/manual/en/book.mongo.php
http://www.mongodb.org/display/DOCS/Home
http://www.phpclasses.org/blog/post/118-Developing-scalable-PHP-applications-using-MongoDB.html

Posted in MongoDB | Tagged | Leave a comment

Version Control with SVN

1. Create trunk from proj_src(source code) :

$ mv /root/proj_src /home/projects/
$ cd /home/projects/
$ svn import proj_src svn://192.168.1.119/proj/trunk -m "create proj trunk"


2. To checkout the project :
$ svn co svn://192.168.1.119/proj


3. Add tags and first release :
$ cd /home/projects/proj/
$ svn mkdir tags
$ svn cp trunk tags/release_0.1.0


4. Generate working copies for developers, special offer or someone else :
$ svn mkdir branches
$ svn cp tags/release_0.1.0 branches/kim
$ svn cp tags/release_0.1.0 branches/cat
$ svn cp tags/release_0.1.0 branches/special-x


5. When finished :
$ svn ci -m "everything is ready"


6. Delete ?
$ svn delete svn://192.168.1.119/branches/special-x -m "delete branch"


7. Merge revisions of branches into trunk
$ svn merge -r 50:100 svn://192.168.1.119/vtigercrm/branches/kim ./trunk/
$ svn ci -m "merge 50-100 from branches/kim to trunk"


8. Revert merge
$ cd trunk/
$ svn log
$ svn merge -r 101:50 .
$ svn ci -m "revert merge 100-50 from trunk"

Posted in SVN | Tagged | Leave a comment

Introduction to NodeJS

1. What is node.js and what does it do?
Evented I/O for V8 JavaScript.
To provide a purely evented, non-blocking infrastructure to script highly concurrent programs.

2. Basic concept : blocking and non-blocking

// blocking
result = query('select * from t');
some_function(result);

// non-blocking
query('select * from t', function(result) {
    // callback
});


3. Amazing Video by Ryan Dahl – Introduction to NodeJS



4. Download and install

$ wget http://nodejs.org/dist/node-v0.2.6.tar.gz
$ tar zxf node-v0.2.6.tar.gz
$ cd node-v0.2.6
$ ./configure --prefix=/usr/local/node
$ make
$ make install


5. Make the doc and read (optional)
$ make doc
$ man doc/node.1


6. Server side test script

// hello_world.js :
var sys = require('sys');
setTimeout(function() {
    sys.puts('world');
}, 2000);
sys.puts('hello');


7. “hello world”
$ /usr/local/node/bin/node hello_world.js


8. Resources
Online chat room example written in node.js : https://github.com/ry/node_chat
NodeJS Quick Tour : Node-JS_Quick_Tour_V2.pdf
Slides from JSConf 2010 : jsconf2010.pdf

Posted in JavaScript | Tagged , | Leave a comment

Master-Slave MySQL-5.1 Replication

Environment:
RHEL: 5.3
MySQL: 5.1.54



Master :

1. MySQL user and group

$ groupadd mysql
$ useradd -g mysql mysql


2. Download and install MySQL

$ wget http://mysql.ntu.edu.tw/Downloads/MySQL-5.1/mysql-5.1.54.tar.gz
$ tar xzf mysql-5.1.54.tar.gz
$ cd mysql-5.1.54
$ ./configure --prefix=/usr/local/webserver/mysql-5.1.54-master --enable-assembler --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static --with-extra-charsets=all --enable-thread-safe-client --with-big-tables --with-readline --with-ssl
$ make
$ make install


3. Create database
$ cd /usr/local/webserver/mysql-5.1.54-master/
# database data located at
$ ./bin/mysql_install_db --datadir=/data/mysql-5.1.54/master


4. Master config
$ cp /data/soft_misc/mysql-5.1.54/support-files/my-huge.cnf /data/mysql-5.1.54/master/my.cnf
$ vi /data/mysql-5.1.54/master/my.cnf
port            = 3406
socket          = /tmp/mysql.sock
datadir         = /data/mysql-5.1.54/master
# databases that need to backup
binlog-do-db     = appdb1
binlog-do-db     = appdb2
binlog-ignore-db = mysql
binlog-ignore-db = test


5. Password for root
$ /usr/local/webserver/mysql-5.1.54-master/bin/mysqladmin -uroot -hlocalhost -P3406 -p password root


6. Launch master
$ chown -R mysql.mysql /data/mysql-5.1.54/master/
$ /bin/sh /usr/local/webserver/mysql-5.1.54-master/bin/mysqld_safe --defaults-file=/data/mysql-5.1.54/master/my.cnf &


7. Create account for replication
$ mysql -hlocalhost -uroot -p
mysql> GRANT REPLICATION SLAVE ON *.* TO 'mysqlrepl'@'localhost' IDENTIFIED BY '123456';
mysql> FLUSH PRIVILEGES;




Slave :

1. Copy master application and data as slave

$ cd /usr/local/webserver/
$ cp -Rp mysql-5.1.54-master/ mysql-5.1.54-slave1/
$ cd /data/mysql-5.1.54/
$ cp -Rp master/ slave1/


2. Slave Config
$ vi /data/mysql-5.1.54/slave1/my.cnf
port            = 3416
socket          = /tmp/mysql-slave1.sock
datadir         = /data/mysql-5.1.54/slave1

server-id            = 11
master-host          = localhost
master-port          = 3406
master-user          = mysqlrepl
master-password      = 123456
# connection retry time
# master-connect-retry = 60
# read only for slave if needed
# read-only           = 1

# databases which need to backup
replicate-do-db     = appdb1
replicate-do-db     = appdb2

# databases ignored
replicate-ignore-db = mysql
replicate-ignore-db = test


3. Launch Slave
$ /bin/sh /usr/local/webserver/mysql-5.1.54-slave1/bin/mysqld_safe --defaults-file=/data/mysql-5.1.54/slave1/my.cnf &



Test :

1. Check both master and slave were launched
$ ps aux | grep mysql


2. Try creating something in master
# go to master
$ mysql -hlocalhost -uroot -p
mysql> SHOW MASTER STATUS;
mysql> CREATE DATABASE IF NOT EXISTS appdb1;
mysql> USE appdb1;
mysql> CREATE TABLE abc (id int(4));


3. Check slave to see table ‘abc’
$ mysql -hlocalhost -uroot -P3416 -S /tmp/mysql-slave1.sock -p
mysql> SHOW DATABASES;
mysql> USE appdb1;
mysql> SHOW TABLES;

Posted in MySQL, RHEL | Tagged , | 2 Comments

Example of nginx.conf

Download example of nginx config file : nginx.conf

# nobody nobody but you ...
user  nobody;

# max concurrent requests = worker_processes * worker_connections
worker_processes  8;

# 4 cpus (double core)
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

# max opened files of each process
worker_rlimit_nofile 51200;

# only open for dev environment
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

# pid number for nginx
pid        logs/nginx.pid;

events {
    # for large I/O
    use epoll;
    # max connections for each process
    worker_connections  51200;
}

# handle http requests
http {
    # map of files and mime-types
    include       mime.types;

    # default file type of http (can be text/html)
    default_type  application/octet-stream;

    # format of log file
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    # access log
    #access_log  logs/access.log  main;

    # timeout of keepalive connection
    keepalive_timeout  650;

    # efficient file transfer mode, using both sendfile and TCP_CORK, only for unix
    sendfile        on;
    tcp_nopush      on;

    # start gzip
    gzip  on;
    # min size of file
    gzip_min_length  1000;
    # buffer size
    gzip_buffers     4 8k;
    # file types which need gzip
    gzip_types       text/* text/css application/javascript application/x-javascript;
    # compression ratio (1 for least, 9 for most)
    gzip_comp_level  9;
    # whether allow compression for proxy request
    gzip_proxied     any;
    # header of "Vary: Accept-Encoding"
    gzip_vary        on;
    # gzip version (use 1.0 for squid)
    gzip_http_version 1.1

    # output buffer size
    output_buffers   4 32k;

    # size of output package
    postpone_output  1460;

    # for big http header (especially large cookies)
    client_header_buffer_size 128k;
    large_client_header_buffers 4 256k;

    # default charset
    charset utf-8;

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

    # deny access of default
    server {
        listen 80;
        server_name null;
        location / {
            root /dev/null;
            log_not_found off;
        }
    }

    # for magento-1.4.2-stable ################################################
    server {
        listen       80;
        server_name  www.mglocal.com;

        root /data/vhosts/mglocal/public_html;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        location / {
            index  index.php index.html index.htm;
            if (-f $request_filename) {
                expires 30d;
                break;
            }
            if (-d $request_filename) {
                break;
            }
            if (!-e $request_filename) {
                # redirect all requests to magento
                rewrite ^(.+)$ /index.php last;
            }
        }

        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

            # type of project you are running
            fastcgi_param  MAGE_RUN_TYPE website;
            # the code you set in backend
            fastcgi_param  MAGE_RUN_CODE ft;

            include        fastcgi.conf;
        }

        # any access to /app/etc is forbidden
        location /app/etc {
            deny all;
        }

        access_log  /data/weblog/www.mglocal.com.access.log;
        error_log  /data/weblog/www.mglocal.com.error.log;
    }
    ###########################################################################

    # upsteam polling for www.kimbs.cn ########################################
    upstream www.kimbs.cn  {
        server  127.0.0.1:8000;
        server  127.0.0.1:8001;
    }

    server {
        listen  80;
        server_name  www.kimbs.cn;
        location / {
            # proxy
            proxy_pass  http://www.kimbs.cn;
            proxy_set_header    Host    $host;
            proxy_set_header    X-Real-IP   $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        access_log  /data/weblog/www.kimbs.cn.access.log  access;
        error_log  /data/weblog/www.kimbs.cn.error.log  crit;
    }

    # 1st server
    server {
        listen       8000;
        server_name  127.0.0.1;
        root /data/vhosts/kbs/public_html;
        error_page   500 502 503 504  /50x.html;

        location = /50x.html {
            root   html;
        }

        location / {
            index  index.php index.html index.htm;
            if (-f $request_filename) {
                break;
            }
            if (-d $request_filename) {
                break;
            }
            rewrite ^(.+)$ /index.php last;
        }

        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi.conf;
        }

        access_log  /data/weblog/www.kimbs.cn.access.log  access;
        error_log  /data/weblog/www.kimbs.cn.error.log  crit;
    }

    # 2nd server
    server {
        listen       8001;
        server_name  127.0.0.1;
        root /data/vhosts/kbs2/public_html;
        error_page   500 502 503 504  /50x.html;

        location = /50x.html {
            root   html;
        }

        location / {
            index  index.php index.html index.htm;
            if (-f $request_filename) {
                break;
            }
            if (-d $request_filename) {
                break;
            }
            rewrite ^(.+)$ /index.php last;
        }

        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi.conf;
        }

        access_log  /data/weblog/www.kimbs.cn.access.log  access;
        error_log  /data/weblog/www.kimbs.cn.error.log  crit;
    }
    ###########################################################################

    # for drupal ##############################################################
    server {
        listen 80;
        server_name myproj.local;

        access_log /data/weblog/myproj.local.access.log access;
        error_log /data/weblog/myproj.local.error.log crit;

        root /data/vhosts/myproj/public_html;

        # prevent '413 Request Entity Too Large'
        client_max_body_size 32m;

        # rewrite
        location / {
            index index.php index.html index.htm;
            if (!-e $request_filename) {
                rewrite ^/(.*)$ /index.php?q=$1 last;
            }
        }

        # hide protected files
        location ~* .(engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(.php)?|xtmpl)$|^(code-style.pl|Entries.*|Repository|Root|Tag|Template)$ {
            deny all;
        }

        # hide backup_migrate files
        location ~* ^/files/backup_migrate {
            deny all;
        }

        # serve static files directly
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
            access_log  off;
            expires     30d;
        }

        # js and css files
        location ~ .*\.(js|css|xml)?$ {
            expires     1h;
        }

        # serve php
        location ~ \.php$ {
            fastcgi_pass                   127.0.0.1:9000;
            fastcgi_index                  index.php;
            fastcgi_param                  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_split_path_info        ^(.+\.php)(.*)$;
            fastcgi_param PATH_INFO        $fastcgi_path_info;

            # prevent timeout
            fastcgi_send_timeout           1800;
            fastcgi_read_timeout           1800;
            fastcgi_connect_timeout        1800;
            fastcgi_buffers                8 128k;

            include                        fastcgi.conf;
            include                        fastcgi_params;
        }
    }
    ###########################################################################

}

Posted in Nginx | Tagged , , , | Leave a comment