Fork me on GitHub
14 5 2013

Perl的redis读取

Posted by kunlun on 2013-05-14


    
先安装Redis.pm

#!/usr/bin/perl -w

use strict;
use warnings;
use Redis;

my $r = Redis->new (server => '127.0.0.1:6379', encoding => undef)
        || die "Redis connection failed";

$r->set('aa' => '11');

# Test
# $r->ping || die "Ping failed. No server?";

my $value = $r->get('aa');
print "$value\n";

$r->quit;
more
14 5 2013

Executing perl code on PostgreSQL triggers

Posted by kunlun on 2013-05-14


        This document describes a way to execute external perl code each time an
 INSERT, DELETE or SELECT happens in a postgres 
database. It is an example, nothing is said here about securing the database; 
do not do this on a public server. 
In this example, we are using a database 
with 2 tables. One table will only get INSERTs while 
the other will act as a work queue for the actions to be taken. 

Software installation 

These examples were done on a FreeBSD 7.2 server. 
To get all the required software simply execute the 
following commands: 
# pkg_add -r postgresql82-server
# pkg_add -r p5-DBD-Pg

Setting up the database 

When above mentioned packages are installed, we have to start the postgresql
 server and

 create a database for testing. 
# echo "postgresql_enable=YES" >>/etc/rc.conf
# /usr/local/etc/rc.d/postgresql initdb
# /usr/local/etc/rc.d/postgresql start
# createdb test -U pgsql
# psql -d test -U pgsql
Now we create two simple tables :
CREATE TABLE requests (
        id SERIAL NOT NULL,
        package_id INTEGER,
        project_nr CHARACTER(10),
        request_date DATE
);
CREATE TABLE workqueue (
        id SERIAL NOT NULL,
        package_id INTEGER,
        project_nr CHARACTER(10),
        request_date DATE
);
The idea is to save a history of all requests in the requests table. On receiving a request, some action should be taken by an external perl program though, therefore each new entry should also go in the workqueue table from where it will be deleted when the action has been done. 
The duplication of new entries to the queue table will be done by a stored procedure and a trigger in the plpgsql language. These will also send a notification to the external perl script. 
Before we can write anything in plpgsql we may need to add the language:
CREATE OR REPLACE FUNCTION plpgsql_call_handler () RETURNS OPAQUE AS
'/usr/local/lib/postgresql/plpgsql.so' LANGUAGE 'C';

CREATE TRUSTED PROCEDURAL LANGUAGE 'plpgsql'
HANDLER plpgsql_call_handler
LANCOMPILER 'PL/pgSQL';
Now we can add the stored procedure and the trigger :
CREATE FUNCTION queue_request() RETURNS trigger AS '
BEGIN
INSERT INTO workqueue ( id, package_id, project_nr, request_date )
       VALUES ( NEW.id, NEW.package_id, NEW.project_nr, NEW.request_date );
NOTIFY request;
RETURN NULL;
END;
' LANGUAGE plpgsql;

CREATE TRIGGER requesttrigger AFTER INSERT ON requests
  FOR EACH ROW EXECUTE PROCEDURE queue_request();
From now on, every insert into the requests table will be duplicated in the workqueue table. Also, postgres will raise a "request" notification. This will be used by an external program written in perl. 

Perl program 

The following example perl code opens a connection to the database, LISTENs for notifications, and then acts upon them.
#!/usr/bin/perl -w

# -------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42 - bzerk)
 wrote this file. As long as you retain this notice
# you can do whatever you want with this stuff. If we meet some day,
# and you think this stuff is worth it, you can buy me a beer in 
# return. Ruben de Groot
# -------------------------------------------------------------------

# This script will wait for notifications from a postgres database.
# Upon such notifications, it will iterate through a queue of 
# requests, perform some action and then remove the request from
# the work queue.

use strict;
use warnings;
use DBI;
use IO::Select;

my $dbcon_test = "dbi:Pg:dbname=test;host=127.0.0.1";
my $dbuser = "pgsql";
my $dbpass = "";
my $dbattr = {RaiseError => 1, AutoCommit => 1};

my $dbh = DBI->connect($dbcon_test, $dbuser, $dbpass, $dbattr);
my $select_handle = $dbh->prepare("select id, package_id, project_nr from workqueue");
my $delete_handle = $dbh->prepare("delete from workqueue where id = ?");

$dbh->do("LISTEN request");

my $fd = $dbh->func("getfd");
my $sel = IO::Select->new($fd);

while (1) {
    print "waiting...\n";
    $sel->can_read;
    my $notify = $dbh->func("pg_notifies");
    if ($notify) {
        $select_handle->execute();
        while (my $h = $select_handle->fetchrow_hashref()) {
            my ($id, $package_id, $project_nr) = ($h->{id}, $h->{package_id}, $h->{project_nr});

#####################################################################
#           Here the code to be executed upon each request          #
#####################################################################

            $delete_handle->execute($id);
        }
    }
}

from http://www.bzerk.org/documents/postgresperl/
  
  
more
26 12 2012

替换img标签

Posted by kunlun on 2012-12-26


    “
替换成 "![](/picture.jpg)"
  html_str.gsub((//, "![](#{$1})")
或者html_str.gsub!(/]+>/, "![](\\1)")
  
7 12 2012

shell批量修改文件名

Posted by kunlun on 2012-12-07


 #!/bin/bash
  for files in `ls`
  do 
filename=`echo $files|tr "[A-Z]" "[a-z]"` #大写变小写
        mv $files `echo  "_$filename"` #加下划线
  done
23 11 2012

隐藏webview上下阴影

Posted by kunlun on 2012-11-23


  for (UIView *subview in [webView subviews]) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            for (UIView *shadowView in [subview subviews]) {
                if ([shadowView isKindOfClass:[UIImageView class]]) {
                    shadowView.hidden = YES;
                }
            }
        }
    }
22 11 2012

DOS/Windows和Linux/Unix间的文档格式转换

Posted by kunlun on 2012-11-22


把Dos/Windows下的文件移至Linux/Unix系统
$ sed -e 's/.$//' mydos.txt > myunix.txt

把Linux/UNIX 文本移至 Windows 系统
$ sed -e 's/$//r/' myunix.txt > mydos.txt
15 11 2012

Centos 启动了SElinux

手动关掉
vim /etc/selinux/config

SELINUX=disable
19 10 2012

IOS assign retain copy atomic nonatomic 区别

Posted by kunlun on 2012-10-19


  assign就是直接赋值,当数据为int, float等原生类型时,可以使用assign。retain使用了引用计数,retain引起引用计数加1, release引起引用计数减1,当引用计数为0时,dealloc函数被调用,内存被回收。 
  copy是在你不希望a和b共享一块内存时会使用到。a和b各自有自己的内存。 
  atomic和nonatomic用来决定编译器生成的getter和setter是否为原子操作。在多线程环境下,原子操作是必要的,否则有可能引起错误的结果。 
24 9 2012

chromium 导入证书

Posted by kunlun on 2012-09-24


安装libnss3-tools:sudo apt-get install libnss3-tools
然后导入证书(这里假定证书ca.crt位于"/goagent/local/ca.crt"):certutil -d sql:$HOME/.pki/nssdb -A -t TC -n "goagent" -i '/goagent/local/ca.crt' 
5 9 2012

只使用landscape横屏显示

Posted by kunlun on 2012-09-05


        
  在shouldAutoRotateToInterfaceOrientation里,  return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) 
|| (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
  
15 8 2012

定制to_json的默认时间格式

Posted by kunlun on 2012-08-15


class ActiveSupport::TimeWithZone
    def as_json(options = {})
        strftime('%Y-%m-%d %H:%M:%S')
    end
end
加到config/initializers中
27 7 2012

DDOS 屏蔽ip地址

Posted by kunlun on 2012-07-27


    
for i in `netstat -an | grep -i ‘:80 ‘|grep ‘EST’ | awk ‘{print $5}’ | cut -d : -f 1 | sort | uniq -c | awk ‘{if($1 > 50) {print $2}}’`
echo $i
echo $i >> /tmp/banip
/sbin/iptables -A INPUT -p tcp -j DROP -s $i
done
19 7 2012

IOS POST

Posted by kunlun on 2012-07-19


    
   NSURL *url = [NSURL URLWithString:@"http://192.168.0.108:3000/productions"];
    NSMutableURLRequest *myrequest = [NSMutableURLRequest new];
    [myrequest setURL:url];
    [myrequest setHTTPMethod:@"POST"];
    NSString *poststring = @"production[code]=2342&production[name]=wewdfsd";
    [myrequest setHTTPBody:[poststring dataUsingEncoding:NSUTF8StringEncoding]];


    NSHTTPURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:myrequest returningResponse:&response error:nil];
    NSString *strRet = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(strRet);
19 7 2012

IOS GET 方法

Posted by kunlun on 2012-07-19


    
    NSURL *url = [NSURL URLWithString:@"http://192.168.0.108:3000"];
    NSMutableURLRequest *myrequest = [NSMutableURLRequest new];
    [myrequest setURL:url];
    [myrequest setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:myrequest returningResponse:&response error:nil];
    NSString *strRet = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(strRet);
29 5 2012

lsof常用法

Posted by kunlun on 2012-05-29


1. lsof -C mysql或 lsof -C ruby 查看应用程序所打开的文件
2. lsof -u username 某用户当前打开的文件
3. lsof -p pid_of_ruby 通过进程号查看打开文件
4. lsof -i 列出所有链接端口号
5  lsof -i :3306或lsof -i tcp:80 列出使用端口号的程序
14 5 2012

如何监视mysql的性能

Posted by kunlun on 2012-05-14


- mysqladmin extended (绝对值)
- mysqladmin extended -i10 -r (相对值)
- mysqladmin processlist
- mysql -e "show innodb status"
- OS data. vmstat/iostat
- MySQL error log
- InnoDB tablespace info.

摘自 http://hi.baidu.com/xuwanbest/blog/item/91e1adc4960a3daa8326ac2f.html
11 5 2012

前端优化建议

Posted by kunlun on 2012-05-11


更少的http请求  Make fewer HTTP requests
使用CDN  Use a CDN
添加过期时间  Add an Expires header
设置Gzip Gzip components
在头部引用stylesheets  Put stylesheets at the top
在尾部引用javascripts  Put scripts at the bottom
避免CSS过期  Avoid CSS expressions
js和css都要外部引用  Make JS and CSS external
减少dns查找次数  Reduce DNS lookups
压缩js  Minify JS
避免重定向  Avoid redirects
减少重复的脚本  Remove duplicate scripts
使用ETags  Configure ETags
AJAX请求缓存  Make AJAX cacheable
11 5 2012

mysql设置query cache

Posted by kunlun on 2012-05-11


query_cache_size = 268435456
query_cache_type = 1
query_cache_limit = 1048576 

查询
show status like 'Qca%';

memlock
innodb_buffer_pool_size = 1G  
innodb_log_file_size = 64M  
innodb_log_files_in_group = 2  
innodb_flush_method=O_DIRECT 
  
  
9 5 2012

LVS keepalived 主从配置

Posted by kunlun on 2012-05-09


ubuntu上会报错  
Keepalived_healthcheckers: IPVS: Can't initialize ipvs: Protocol not available

需要先加载下
modprobe ip_vs
7 5 2012

原型设计工具

Posted by kunlun on 2012-05-07


在线UI原型设计 Balsamiq Mockups
  http://builds.balsamiq.com/b/mockups-web-demo/
Next Page