Wednesday, September 19, 2012

计算两个日期间隔,用X年X月X日表示

自己用golang写了一个短代码用来计算两个日期间隔,间隔用X年X月X日表示出来,比如2010-07-19到2012-09-18的间隔就是2年1月30天。写这个程序是用来具体算小孩的年龄,闰年也有考虑在内,比如 2010-07-19到2012-03-18是1年7个月28天,因为2012年2月有29天。

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
    "strings"
    "time"
)

type DateDiff struct {
    years, months, days int
}

var DAYS = map[time.Month]int{
    time.January:   31,
    time.February:  28,
    time.March:     31,
    time.April:     30,
    time.May:       31,
    time.June:      30,
    time.July:      31,
    time.August:    31,
    time.September: 30,
    time.October:   31,
    time.November:  30,
    time.December:  31,
}

func LeapYear(year int) bool {
    ret := false
    if year%4 == 0 {
        if year%100 != 0 {
            ret = true
        } else if year%400 == 0 {
            ret = true
        }
    }
    return ret
}

// passed in strings hould be in either of the following two format:
//    yyyy-mm-dd
//    yyyy/mm/dd
func ParseDate(s string) time.Time {
    var it []string
    if strings.Index(s, "-") > 0 {
        it = strings.Split(s, "-")
    } else if strings.Index(s, "/") > 0 {
        it = strings.Split(s, "/")
    } else {
        fmt.Printf("Error: wrong date format\n")
        flag.Usage()
        os.Exit(-1)
    }
    y, err := strconv.ParseInt(it[0], 10, 64)
    if err != nil {
        panic(err)
    }
    m, err := strconv.ParseInt(it[1], 10, 64)
    if err != nil {
        panic(err)
    }
    d, err := strconv.ParseInt(it[2], 10, 64)
    if err != nil {
        panic(err)
    }
    return time.Date(int(y), time.Month(int(m)), int(d), 0, 0, 0, 0, time.UTC)
}

func main() {
    var ds, de string
    flag.StringVar(&ds, "start", "", "[*]Start Date in format of yyyy/mm/dd or yyyy-mm-dd")
    flag.StringVar(&de, "end", "today", "End Date in format of yyyy/mm/dd or yyyy-mm-dd")
    flag.Parse()
    if ds == "" {
        fmt.Printf("Error: No start date is specified\n")
        flag.Usage()
        os.Exit(-1)
    }

    var start, end time.Time
    start = ParseDate(ds)
    if de == "today" {
        end = time.Now()
    } else {
        end = ParseDate(de)
    }

    var diff DateDiff
    var borrowed bool = false
    var daysBorrowed int = 0
    // Days difference
    if end.Day() >= start.Day() {
        diff.days = end.Day() - start.Day()
    } else {
        daysBorrowed = DAYS[end.Month()-1]
        if LeapYear(end.Year()) && end.Month() == time.March {
            daysBorrowed++ // February in leap year is 29 days
        }
        diff.days = end.Day() + daysBorrowed - start.Day()
        borrowed = true
    }

    // Month Difference
    endMonth := end.Month()
    if borrowed == true {
        if endMonth == time.January {
            endMonth = time.December
        } else {
            endMonth--
        }
        borrowed = false
    }
    if endMonth >= start.Month() {
        diff.months = int(endMonth) - int(start.Month())
    } else {
        diff.months = int(endMonth) + 12 - int(start.Month())
        borrowed = true
    }

    // Year difference
    if borrowed {
        diff.years = end.Year() - 1 - start.Year()
    } else {
        diff.years = end.Year() - start.Year()
    }

    // Output
    if diff.years < 0 || diff.months < 0 || diff.days < 0 {
        fmt.Printf("Error: end date should after start date\n")
    } else {
        fmt.Printf("Difference of %d Years %d Months %d Days\n", diff.years, diff.months, diff.days)
    }
}

Friday, August 24, 2012

用golang生成key不是大写的json数据

前一段时间用go写了一个查看perforce的history的小程序,go没有什么成熟的ui包,所以我选用web界面,程序本身做两件事情,一个后台更新perforce的history到本地的sqlite数据库,另外一个后台当作web服务器,处理client的request,生成json数据。

在写这个程序的时候,发现要生成json数据的结构里field名字首字母要大写。因为是一个自己用的小程序,也没有去深究到底可不可以生成首字母是小写的json数据。今天逛stackoverflow的时候看到有人问这个问题,看了看,原来go的json包有解决办法,只是自己看文档的时候没有怎么注意罢了。要加tag来做这件事情。

下面这段示例代码就的output:

{"field_a":1234,"field_b":"hello"}

package main

import "fmt"
import "encoding/json"

func main() {
    type Test struct {
        A int `json:"field_a"`
        B string `json:"field_b"`
    }
    A := Test{1234, "hello"}

    b, _ := json.Marshal(A)
    fmt.Println(string(b))
}

Thursday, August 23, 2012

个人第一个github项目

今天终于在github上有了一个真正的自己的项目,虽然是一个很简单,很小的项目,不过还是值得纪念一下。

项目地址: https://github.com/yongzhy/goploticus

这个是libploticus的Go语言封装。

ploticus的主页:

A free, GPL, non-interactive software package for producing plots, charts, and graphics from data. It was developed in a Unix/C environment and runs onvarious Unix, Linux, and win32 systems. ploticus is good for automated or just-in-time graph generation, handles date and time data nicely, and has basic statistical capabilities. It allows significant user control over colors, styles, options and details. Ploticus is a mature package, available since 1999, and version 2.40 has more than 12,000 downloads to date. Ploticus was discussed in this 2008 review on Linux.com.

因为是第一次封装C的API,折腾了一阵子才发现要让cgo编译代码,import “C” 必须是单独一行.

可以编辑的代码:

  1. //#cgo LDFLAGS: -lploticus

  2. //#include <libploticus.h>

  3. //#include <stdlib.h>

  4. import "C"

不可以被编辑的代码:

  1. //#cgo LDFLAGS: -lploticus

  2. //#include <libploticus.h>

  3. //#include <stdlib.h>

  4. import (

  5. "C"

  6. )

什么东西,都要试了才真正知道。

Friday, August 10, 2012

TextMate开源了

Mac下面无比NB的文件编辑器TextMate开源了,代码已经放在github上了。
因为TextMate只支持Mac,曾经让我这个只有Linux和Windows的用户无比羡慕。在羡慕加嫉妒TextMate用户的时候,我发现了Sublime Text 2,这个也是一个强大的编辑器,很容易上手,也很容易定制。因为TextMate作者长时间没有更新,Sublime Text 2已经慢慢的蚕食了很多TextMate的市场。
现在TextMate开源了,希望有高手可以赶快移植到Linux,Windows上,我们选择编辑器的时候就又多了一个选择。

Wednesday, August 8, 2012

putty + tmux 结合实现命令行多窗口

最近要远程登录Linux系统做一些东西,用putty一次 只能够执行一个程序,要在不同的目录运行不同的东西,要打开几个putty,很是麻烦。Google了一下,找到tmux这个小程序,参考了别人的配置,自己稍加改动,现在使用起来真的很爽。

我的配置文件:

##########################################################
# STATUS BAR
set -g status-utf8 on
set -g status-key vi
set -g status-interval 1
set -g status-attr bright
set -g status-fg white
set -g status-bg black
set -g status-left-length 20
set -g status-left '#[fg=green][#[fg=red]#S#[fg=green]]#[default]'
set -g status-justify centre
set -g status-right '#[fg=green][%m/%d %H:%M:%S]#[default]'
setw -g window-status-current-format '#[fg=yellow](#I.#P#F#W)#[default]'
setw -g window-status-format '#I#F#W'


##########################################
## TERMINAL EMULATOR TITLES
set -g set-titles on
set -g set-titles-string "#(tmux ls | awk -F: '{print $1}' | xargs | sed 's/\ / | /g')"


##########################################
## KEy BINDINGS
unbind C-b
set -g prefix C-s

# - = vertical split
unbind '"'
bind - split-window -v

# | = horizontal split
unbind %
bind \ split-window -h

# VIM Style movement
bind k selectp -U   # choose top panel
bind j selectp -D   # choose bottom panel
bind h selectp -L   # choose left panel
bind l selectp -R   # choose right panel

# bind ALT+Arrow to select panel
bind -n M-Up selectp -U   # choose top panel
bind -n M-Down selectp -D   # choose bottom panel
bind -n M-Left selectp -L   # choose left panel
bind -n M-Right selectp -R   # choose right panel


# Keys for resize panel
bind -n F9 resizep -U 1   # up
bind -n F10 resizep -D 1  # down
bind -n F11 resizep -L 1  # left
bind -n F12 resizep -R 1  # right

##########################################
## BASIC CONFIG
## utf8 ability
setw -g utf8 on
#
## vi Style Editing
setw -g mode-keys vi
#
## Make mouse useful in copy mode
#setw -g mode-mouse on

#
## Allow mouse to select which pane to use
#set -g mouse-select-pane on
#
## Allow xterm titles in terminal window, terminal scrolling with scrollbar, and setting overrides of C-Up, C-Down, C-Left, C-Right
set -g terminal-overrides "xterm*:XT:smcup@:rmcup@:kUP5=\eOA:kDN5=\eOB:kLFT5=\eOD:kRIT5=\eOC"
#
## Scroll History
set -g history-limit 30000
#
## Set ability to capture on start and restore on exit window data when running an application
setw -g alternate-screen on
#
## Lower escape timing from 500ms to 50ms for quicker response to scroll-buffer access.
set -s escape-time 50

Thursday, June 14, 2012

开始用 GitHub


现在免费的代码托管最出名的非Github莫属,但是我一直没有用Github,原因是因为Github没有免费的Private Repo。我之前一直是使用bitbucket的服务,可以有无限的私有Repo。最近因为学习目的,要fork一个Repo来看看,就开始使用Github。

Github有很详细的说明,我这里只是记录下来不让自己忘。
在做下面步骤之前,一定是要先安装git的。

$ git config --global user.name "myname"
$ git config --global user.email "myname@T420_Win"

make the git cache username and password for 1 hour (default is 15 mins), so you
don't need to type username and password everytime talk to remote server.

$ git config --global credential.helper 'cache --timeout=3600'

fork a repo

clone the forked repo
$ git clone git@github.com:username/Spoon-Knife.git

$ cd Spoon-Knife

Assigns the original repo to a remote called "upstream"
$ git remote add upstream git://github.com/octocat/Spoon-Knife.git

Pull the changes not present in your local repository, without modify your files
$ git fetch upstream

Pushes commits to your remote repo stored on GitHub
$ git push origin master

Fetches any new changes from the original repo and Merges any changes fetched into your working files
$ git fetch upstream

$ git merge upstream/master

Wednesday, June 13, 2012

在VirtualBox里面安装Plan 9

因为在学习Go,看到Go历史追溯到Plan9,就心血来潮要试着安装一个玩一玩。
下载plan9.iso。在VirtualBox里面创建一个新的VM,2G的IDE硬盘就够了,我给分配了512M的内存。把iso当中第二个IDE,然后从CD启动。

安装步骤蛮简单的,按照提示一步一步的安装,基本上就是一路点【Enter】键。在选择安装到哪个硬盘的时候,要手动输入。

安装完,把ISO从VM里面去掉,然后重启。

提示重那里启动 root is from ... : (按回车键)


提示用户名,输入glenda
user[none]: glenda
等待一阵子,就会看到rio图形界面了。

Plan9默认的图形分辨率太低,可以自己更改配置调高。


在图形界面上按住右键,选“new”
按住右键拉一个窗口
在窗口里面输入:

9fat:
sam /n/9fat/plan9.ini

在窗口里面按住右键,选“plan9.ini"
修改下面两行
monitor=xga
vgasize=640x480x8

替换内容
monitor=vesa
vgasize=1024x768x24

按住右键,选”write“
右键点击刚刚编辑的地方
按住右键,选”close“,再点右键
输入”q回车“退出

然后重启VM,就可以看到比较大的显示了。


下面的文档是plan9的一个入门文档,介绍了plan9下面一些常用软件和操作。
http://www.quanstro.net/newbie-guide.pdf

Tuesday, June 12, 2012

Golang conditional compilation

In C language, we use #if, #else, #endif for conditional compilation.

For Go, the conditional compilation can be achieved by include different files in certain build configuration.

At begin of source file, put // +build XXX then followed by a blank line.

main1.go
// +build main1

package main

import (
    "fmt"
)

func main() {
    fmt.Println("This is main 1")
}
main2.go
// +build main2

package main

import (
    "fmt"
)

func main() {
    fmt.Println("This is main 2")
}
when running "go build", I still got compile error
$ go build -tags 'main1'

Saturday, June 2, 2012

Setup emacs + gocode for golang editing with auto completion


from Go Source repository http://code.google.com/p/go/source/browse/misc/emacs/
download go-mode-load.el and go-mode.el, put both file into ~/.emacs.d

edit ~/.emacs to add
(add-to-list 'load-path "~/.emacs.d" t)
(require 'go-mode-load)

Go to ~/.emacs.d to compile go-mode.el
$emacs -batch -f batch-byte-compile go-mode.el

Install Autocomplete for emacs from http://cx4a.org/software/auto-complete/
Follow the user manual for instllation.

Copy emacs/go-autocomplete.el file from the gocode source distribution to ~/.emacs.d

edit ~/.emacs to add
(require 'go-autocomplete)
(require 'auto-complete-config)

Install gocode
$go get github.com/nsf/gocode
$go install github.com/nsf/gocode

All instllation is done. To test of gocode auto completion
$gocode -s 

then run emacs with a go file, test and enjoy it.

Using Juniper Network Connect on Lubuntu 12.04 64bit

All ideas are from http://mad-scientist.us/juniper.html.

Below is my preparation on my Lubuntu 12.04 64bit. Rest just follow the origin website.

Install ia32-libs

$sudo apt-get install ia32-libs

Download 64bit and 32bit Java installation files
jre-6u32-linux-i586.bin  for 32bit linux
jre-6u32-linux-x64.bin for 64bit linux

ia32-libs and jre 32bit is only needed if you want to run gui version of juniper vpn.

I will install both JAVA in /opt/java/
$sudo mkdir -p /opt/java/x86 /opt/java/x64
$cd /opt/java/x86
$sudo sh ~/Download/jre-6u32-linux-i586.bin

$cd /opt/java/x64
$sudo sh ~/Download/jre-6u32-linux-x64.bin

Create JAVA plugin for firefox.
$cd /usr/lib/firefox/plugins
$sudo ln -s /opt/java/x64/jre1.6.0_32/lib/amd64/libnpjp2.so .

Start Firefox, use "about:plugins" to check Java installed.

Install xterm by
$sudo apt-get install xterm