Showing posts with label Go. Show all posts
Showing posts with label Go. Show all posts

Friday, January 25, 2013

Go wrapper for Lauterbach Trace32 Remote API

公司里面用Lauterbach Trace32的simulation来解决一些问题,其过程比较繁琐,要运行很多次不同的cmm文件,还要好几种文件。于是就想把这些过程自动化,写一个小工具根据指定的参数自动生成cmm文件,然后用Remote API控制Trace32来运行这些生成的cmm。这个小工具已经做好,用Go写的,本来决定要用QT写一个GUI版本,因为那些API是C的。最后因为发现那些API比较容易封装,而且自己也正在学习Go,就多做了一些工,把API用Go封装一下,然后用Go来写这个小工具。

本着共享的精神,封装好的API放在github上,不是每一个function我都测试过,我自己需要用的那几个API是没有问题的。 :)

代码地址: https://github.com/yongzhy/t32

Tuesday, January 8, 2013

简单的 p4wrapper 实现 perforce p4的edit和revert命令

公司用Perforce管理代码,因为有很多产品,每个产品在自己的branch里面,电脑上自己参与的产品都有一个独立的workspace。自己用SourceInsight和SublimeText2来编辑代码,每次都在不同的workspace间换来换去,所以如果用p4命令来check out代码,P4_CLIENT每次都在变。为了省事,自己用Go写了一个简单的p4的wrapper,只做两件事情,check out和revert。其余的perforce的工作就用GUI的客户端。

自己写的这个wrapper有考虑到本人自己的情况,所以这个wrapper不需要用户去定义现在的workspace,wrapper会通过比较现在的工作文件的绝对路径和用户在当前开发主机上的所有workspace的路径mapping比较找出working workspace。这样就省去了每次要定义P4_CLIENT的苦恼。

代码放在github上, 点这里

我也把自己用的SublimeText 2的plugin放上去了。希望对那些工作环境跟我差不多的人有所帮助。

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. )

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

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.

Setup Sublime Text 2 + gocode for GoLang coding on Ubuntu 12.04


Step to setup on Ubuntu 12.04


Install Golang
$sudo apt-get install golang


Install gocode and dependency packages
$ sudo go get github.com/nsf/gocode
$ sudo go install github.com/nsf/gocode
$ sudo go get github.com/DisposaBoy/MarGo
$ sudo go install github.com/DisposaBoy/MarGo

add /usr/lib/go/bin to your $PATH by edit ~/.bashrc
export PATH=$PATH:/usr/lib/go/bin

Install Sublime Text 2 from http://http://www.sublimetext.com/2
$ tar vxjf Sublime Text 2 Build 2181 x64.tar.bz2
$ sudo mv Sublime\ Text\ 2 /opt/sublime2
$ sudo sudo ln -s /opt/sublime2/sublime_text /usr/bin/subl

Installation for Sublime Text 2 OK. Can run using symbol link "subl"
$ subl  &

Install Package Control for Sublime Text 2.
press Ctrl + ` to view the python consol, paste following line

import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())); open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read()); print 'Please restart Sublime Text to finish installation'

Reset Sublime Text 2

Ctrl + Shift + P, then select "Package Control: Install Package", type "gosublime" and install

Reset Sublime Text 2, now you have a very nice go editor. Enjoy it.

Friday, June 1, 2012

读书 Learning Go

Learning Go - a free E-Book for learning the Go language, 这个是一本不错的Go语言入门的书,免费的,书本身是用Latex写的,放在github上( https://github.com/miekg/gobook ), 也可以直接下载PDF版本(http://miek.nl/files/go/),中文翻译版本(http://www.mikespook.com/learning-go/

昨晚10点多开始读,刚刚读完,没有做里面的练习题,算是对Go有了一个初步也比较全面的了解,感觉Go设计的的确很不错,毕竟是大牛们经过了好多年思考的结果。语法简介,清晰,功能强大。以后工作中如果要写一些小工具,可以考虑用Go来代替Python。

Thursday, May 31, 2012

Lubuntu 12.04 安装 Go

在网上看到一篇介绍Go的文章,颇为心动,对于我这种现在主要用C和Python的人好像蛮值得一学。于是开始着手在我新安装的Lubuntu 12.04里面安装Go。

$ apt-cache search go | grep ^go
发现源里面竟然已经有了golang,于是直接apt-get install golang来安装, 这个命令会安装go的源代码和程序。

安装完,按照网上的文档,在.bashrc里面设置环境变量, 然后用8g,8l测试了一个hello world。不过后来发现根本不用设置这些变量,因为新版的go在/usr/bin/里面有一个go的命令,这个命令本身就可以做各种各样的事情。

要运行程序 go run test.go
要编译程序 go build test.go

Go现在终于到了1.0版,以后应该慢慢变流行吧,毕竟是Google请的几个超级大牛写的。以后有空就学习Go吧!!!