echo Impossible|sed 's/Im/To be /'

May 16, 2011

Tip. Telnetd inetd bind IP address

Telnetd 如何 bind IP address


近來在 Linux 上開 vserver 開很兇,而有些沒有辦法聽 IP address 的服務,在 vserver 上會造成管理上的問題。 要在設定上想辦法讓它只聽或綁特定的 IP address。


Telnetd 透過 inetd.conf 的設定,可以只聽特定的 IP address,設定方法如下。其它相關的服務也可比照辦理。

cat /etc/inetd.conf | grep in.telnetd

127.0.0.1:telnet stream tcp nowait telnetd /usr/sbin/tcpd /usr/sbin/in.telnetd

December 22, 2010

Tip. PDF watermart

在 PDF 上加浮水印


最近寫文件比寫 code 多。自從用了 ReStructuredText 配合 Trac 後更是大大便利,兼顧 wiki 共筆網頁方便瀏覽的特性以及 Latex PDF 文件印刷美觀輸出,只要訂好 Latex 格式,輸出品質絕不輸 MS Word Office.


這幾日為了在文件上加上浮水印 (watermark) ,花了點時間 google 爬網。得到了兩個作法。

  1. 由 Latex 直接印上浮水印,生成 PDF。
  2. 後製作,在即有的 PDF 上透過列印或程式合成製作有浮水印的 PDF。

兩種方法各有優點,在測試過考量作法及用途後,最後採用第二種方法,而用的工具則是 pdftk 。輸出結果如下,如你所見, 一種是以背景方式出現,但會被圖蓋過去。另一種是戳印,但會把字及圖直接蓋掉。

$ pdftk INPUT.pdf background Watermark.pdf output OUTPUT-1.pdf  # background 背景
$ pdftk INPUT.pdf stamp Watermark.pdf output OUTPUT-2.pdf       # stamp 戳印

wm1 wm2

看了幾個範列大部份的都採用背景方式出現,浮水印就讓圖蓋過去。但無意中我抓到了這個浮水印圖檔 logo.pdf ,它打開了我一線曙光。

$ pdfinfo logo.pdf
Title:          NCTU LOGO_10
Creator:        Adobe Illustrator CS2
Producer:       Adobe PDF library 7.77
CreationDate:   Mon Jul 27 17:07:13 2009
ModDate:        Mon Jul 27 17:11:55 2009
Tagged:         no
Pages:          1
Encrypted:      no
Page size:      107.49 x 105.676 pts
File size:      360988 bytes
Optimized:      no
PDF version:    1.5

是的這是張具有透明度的 pdf 檔,而這個透明度讓事情變得不一樣了。在數日的嘗試後,我總算是找到了在 Linux 上生成 具透明度 pdf 與簍空字的工具及方法,於是效果如下。

$ inkscape watermark.svg -A watermark.pdf
$ pdftk INPUT.pdf stamp watermark.pdf output OUTPUT-3.pdf

$ mkbitmap -s 1 -t 0.2 watermark.bmp ; potrace watermark.pbm ; epstopdf watermark.eps
$ pdftk INPUT.pdf stamp watermark.pdf output OUTPUT-4.pdf

wm3 wm4

作法是用 inkscape 作出具透明度的 pdf 或是由 svg 轉 pdf。而簍空字則是爬網 google 找到的方法,用 mkbitmappotrace 再用 inkscape 或是 epstopdf 作成 pdf 再交由 pdftk 處理。

December 05, 2010

Tip. zlib crc32 function

zlib crc32 function howto


crc32 常用來作為驗証通訊資料,zlib 也提供了這個功能,簡單方便好用。


crc.c howto

#include <zlib.h>
#include <stdio.h>

int main () {
  unsigned long crc;

  crc = crc32 (0L, Z_NULL, 0);
  crc = crc32 (crc, (unsigned char *) "lloyd\n", 6);
  printf ("%x\n", (unsigned int) crc);
  crc = crc32 (0L, Z_NULL, 0);
  crc = crc32 (crc, (unsigned char *) "lloyd huang\n", 12);
  printf ("%x\n", (unsigned int) crc);
  return (0);
}

Makefile

gcc -o crc crc.c -lz -g -Wall

驗証方法

$> ./crc
4b1707f9
359cde0d
$> echo lloyd > testfile; crc32 testfile
4b1707f9
$> echo "lloyd huang" > testfile; crc32 testfile
359cde0d

December 05, 2010

Tip. libcurl example

libcurl http example code


curl 是 Unix 上的 power tools,常用來作 http https ftp 連接。libcurl 是 curl 的 library 提供了好用的 API, 好好運用可以省去不少瑣事。


以下範例由 libcurl examples code fopen.c sepheaders.c 節錄並稍作整理作為記錄

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

struct fcurl_data {
    char *buffer;             /* buffer to store cached data */
    int buffer_len;           /* currently allocated buffers length */
    int buffer_pos;           /* end of data in buffer */
};

typedef struct fcurl_data URL_FILE;

static size_t
write_callback(char *buffer, size_t size, size_t nitems, void *userp)
{
    char *newbuff;
    int rembuff;

    URL_FILE *url = (URL_FILE *) userp;
    size *= nitems;

    rembuff = url->buffer_len - url->buffer_pos;      /* remaining space in buffer */

    if (size > rembuff) {
      /* not enough space in buffer */
      newbuff = realloc(url->buffer, url->buffer_len + (size - rembuff));
      if (newbuff == NULL) {
          fprintf(stderr, "callback buffer grow failed\n");
          size = rembuff;
      } else {
          /* realloc suceeded increase buffer size */
          url->buffer_len += size - rembuff;
          url->buffer = newbuff;
      }
    }

    memcpy(&url->buffer[url->buffer_pos], buffer, size);
    url->buffer_pos += size;

    return size;
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    URL_FILE *htmlbody, *htmlheader;

    htmlbody = malloc(sizeof(URL_FILE));
    htmlheader = malloc(sizeof(URL_FILE));
    memset(htmlbody, 0, sizeof(URL_FILE));
    memset(htmlheader, 0, sizeof(URL_FILE));

    curl = curl_easy_init();
    if (curl) {
      curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
      curl_easy_setopt(curl, CURLOPT_PORT, 80);
      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, htmlbody);
      curl_easy_setopt(curl, CURLOPT_WRITEHEADER, htmlheader);
      res = curl_easy_perform(curl);
      printf("body: %s\n\n", htmlbody->buffer);
      printf("header: %s\n", htmlheader->buffer);

      /* always cleanup */
      curl_easy_cleanup(curl);
    }
    return 0;
}

Makefile

gcc -o curlsample curlsample.c -l curl

October 26, 2010

Tip. File tree walk

在 Unix 上走遍目錄樹


這幾日看了幾個人寫的走目錄樹找檔案的方法,感想是難到沒有比較容易的方法嗎? 何苦一定要自已刻呢? Google 及 man 了一下果然有答案。


C 的方法 nftw ftw ,截錄 man ftw 的範例

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    printf("%-3s %2d %7jd   %-40s %d %s\n",
        (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :
        (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :
        (tflag == FTW_NS) ?  "ns"  : (tflag == FTW_SL) ?  "sl" :
        (tflag == FTW_SLN) ? "sln" : "???",
        ftwbuf->level, (intmax_t) sb->st_size,
        fpath, ftwbuf->base, fpath + ftwbuf->base);
    return 0;           /* To tell nftw() to continue */
}

int
main(int argc, char *argv[])
{
    int flags = 0;

    if (argc > 2 && strchr(argv[2], 'd') != NULL)
        flags |= FTW_DEPTH;
    if (argc > 2 && strchr(argv[2], 'p') != NULL)
        flags |= FTW_PHYS;

    if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags)
            == -1) {
        perror("nftw");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

Python os.walk 的方法

#!/usr/bin/python
import os

for root, dirs, files in os.walk ("/etc") :
    for i in files :
        print root, i, "<-- FILE"
    for i in dirs :
        print root, i, "<-- DIR"

Python 上另一個用 Generator 的方法

#!/usr/bin/python
from __future__ import generators

import os, sys

def dirwalk(dir):
    "walk a directory tree, using a generator"
    try:
        for f in os.listdir(dir):
            fullpath = os.path.join(dir,f)
            if os.path.isdir(fullpath) and not os.path.islink(fullpath):
                for x in dirwalk(fullpath):  # recurse into subdir
                    yield x
            else:
                yield fullpath
    except OSError:
        pass

if __name__ == "__main__":
    a = dirwalk ("/etc")
    for i in a:
        print i

October 16, 2010

Tip. Files intersection union difference

檔案內容的交集,聯集,差集

Files Sample :

$ cat file1
file1_only
We_are_the_same

$ cat file2
We_are_the_same
only_file2

Using Shell :

聯集 intersection
$ cat file1 file2 | sort | uniq
file1_only
only_file2
We_are_the_same

交集 union
$ cat file1 file2 | sort | uniq -d
We_are_the_same

差集 xor
$ cat file1 file2 | sort | uniq -u
file1_only
only_file2

file1 only, difference
$ cat file1 file2 file2 | sort | uniq -u
file1_only

file2 only, difference
$ cat file1 file2 file1 | sort | uniq -u
only_file2

Python code :

#!/usr/bin/python

f1=open("file1",'r').readlines()
f2=open("file2",'r').readlines()
sf1, sf2 = set(f1), set(f2)

print "difference", sf1.difference (sf2)
print "difference", sf2.difference (sf1)
print "intersection", sf1.intersection (sf2)
print "union", sf1.union (sf2)

Python Code exec Output :

difference set(['file1_only\n'])
difference set(['only_file2\n'])
intersection set(['We_are_the_same\n'])
union set(['only_file2\n', 'file1_only\n', 'We_are_the_same\n'])

June 27, 2010

Tip. Emacs flyspell-mode orgtabl-mode

Emacs 的特異功能 flyspell-mode 及 orgtbl-mode


  • flyspell-mode 是個自動檢查英文拼字,可作到錯誤提示,單字補齊的功能
  • orgtbl-mode 是 org-mode 的其中一個可以獨立的子項目,它可以作到簡單繪製表格,以及試算表功能

昨天跟 Qerter Silice CYJ Louis 約在外閒聊,其間聊了許多如游泳,攝影,軟體專案管理工具等等, 當然還有 Qerter Silice 在 console 下過生活系列篇 -- 正妹 msn pidgin notification。 這麼有趣的事情,當然要留給原作者來親身解說。簡言之就是在 console 版本的 pidgin 額外加上*來訊通知*。 這果然是有需求有動力。 :-)

席間在聊 軟體專案管理工具Qerter 向我推薦 Emacs ORG-mode,看了 youtube 上的 Google 演講 功能果然強大,有空該花時間仔細研究。

我對於其中某個在 youtube 的 影片 特別感興趣,他展示了 org-mode 的其中一個獨立子項目 orgtbl-mode 加 flyspell-mode。 它可以作到簡單繪製表格,試算表及自動檢查英文拼字功能,功能強大很棒。


| <cursor遊標位置> |

C-c |
Table size Columns x Rows [e.g. 5x2]:

C-c -

|   |   |   |   |   |
|---+---+---+---+---|
|   |   |   |   |   |
|   |   |   |   |   |
|---+---+---+---+---|
|   |   |   |   |   |
| Student  | Maths | Physics | Mean |
|----------+-------+---------+------|
| Bertrand |    13 |       9 |   11 |
| Henri    |    15 |      14 | 14.5 |
| Arnold   |    17 |      13 |   15 |
#+TBLFM: $4=vmean($2..$3)

June 25, 2010

Tip. grep egrep or sed?

用 grep 用 egrep 還是用 sed ?


前幾日跟 smills 及 timchen119 使徒提姆@Python 分別聊到了極限與極艱困的環境下可用的程式語言,席間 談到了不少可能性,在時間壓力下有限時間,快速開發,flashrom 及 ram size 極少的情況下,我們到底還有什麼 工具可以使用,談論範圍由 python, perl, lua, bash, ash, C, awk, 到 sed。

閒聊當然是沒有結論,但我在 timchen119 提點下,找到了個用 sed 作 類似 grep/egrep 小技巧,怕忘作個記錄。


110碼$> cat /etc/passwd | sed -r '/root|nobody|sys/!d'
root:x:0:0:root:/root:/bin/bash
sys:x:3:3:sys:/dev:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh

ll0碼$> cat /etc/passwd | sed '/nobody\|sys/{s/:/-/g;p};d'
sys-x-3-3-sys-/dev-/bin/sh
nobody-x-65534-65534-nobody-/nonexistent-/bin/sh

ll0碼$> cat /etc/passwd | nl | sed 's/^\(.*\)\(nobody\|sys\).*$/\1\2/p;d'
 4  sys:x:3:3:sys
18  nobody:x:65534:65534:nobody

June 09, 2010

Tip. Linux Bluetooth transfer files.

Linux 下藍芽與手機互傳檔案

要藍芽測試啊?那就跟手機對傳檔案吧?


ll0碼#> apt-get install obexftp obexpushd
ll0碼#> hcitool inq
Inquiring ...
        00:15:83:15:A3:27       clock offset: 0x23a3    class: 0x1a2100

# scanning one Bluetooth device. name is "00:15:83:15:A3:27"

ll0碼#> obexftp -b 00:15:83:15:A3:27 --channel 9 --put UPLOADFILE

June 09, 2010

Intro. Conkeror Emacs like brower.

Conkeror : 將 Firefox Emacs 化


最近 KaLUGQerter 及 Silice 正在迷戀如何用 console 文字介面過生活。他們作了不少神奇的組合及搭配了不少工具,以近乎純文字的介面來達成類似 Gnome KDE 的桌面使用習慣及功能。其中他們介紹了一個 Firefox 的 plugin,好像是 Vimperator ,由於我不是 vi 使用者所以不是很在意。主要的概念是用 vi 的使用習慣及鍵盤來操作瀏灠器(browser)。

由於 Vimperator 看來還真的很犀利好用,這讓我想起了 timchen119 使徒提姆@Python 之前跟我介紹的 Conkeror ,裝起來試用了幾天後發現還真的很好用。

Conkeror 概念與 Vimperator 相同,差別在於它是針對 Emacs 的使用習慣設計,推薦給同是 Emacs 的愛好者使用。

About Conkeror


Conkeror is a keyboard-oriented, highly-customizable, highly-extensible web browser based on Mozilla XULRunner, written mainly in JavaScript, and inspired by exceptional software such as Emacs and vi. Conkeror features a sophisticated keyboard system, allowing users to run commands and interact with content in powerful and novel ways. It is self-documenting, featuring a powerful interactive help system.

/~lloyd/bblog/img/Conkeror_Emacs.jpg

Posted by Lloyd Huang in on June 09, 2010