Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

2020-08-10

Intermediate Languages to Executable Binary

There's already bunch of alternative of programming languages implementation that compiles to intermediate language/bytecode, such as Java (using javac) and C# (using csc or old mcs) which can be run with interpreter or virtual machine (eg. JVM, CLR, Ruby, Python, PHP, DartVM, Julia, etc). Unlike other compiled language (Go, C++, Crystal, Rust, Haskell, V, Zig, D, Swift, etc) which only need to sync single binary on deployment (unless you're using docker or packager like jar, but at least you'll also need to install the VM on the deployment machine). There's some alternative that could compile those programming language implementation into single binary that match targeted machine architecture (either for ease of deployment, or closed source/copyright issue that probably you'll need also an obfuscator):

  • il2cpp, developed by Unity, could compile any CLR-based language (especially C#) into C++ then compile it into static binary makes it harder decompile
  • Nuitka, compile Python into executable binary
  • GraalVM Native Image, any JVM-based language (Java, Kotlin, Scala, Clojure, Groovy, Jython, JRuby, Javascript, etc) into native image executable
  • ORCA, compile Ruby to windows executable
  • Haxe, any language that targets to haxe (Javascript, Flash Actionscript, Neko, PHP, C++, Java, C#, Python, Lua)
  • NectarJS, compiles NodeJS into executable binary
  • KotlinNative, compiles Kotlin to executable binary 
  • wasm2c, convert wasm to C
  • Julia PackageCompiler, compiles Julia script into system image

See also list of languages that transpiles/targetting javascript also all languages LLVM supported, also list of new programming languages.


2015-02-14

How to Learn Programming and Train your Logic

So today one of my student ask me, how to train your logic in programming? There are two steps that you must do, here's my tips in English, the Indonesian slang version below. For those who doesn't understand English, it's greatly recommended to learn about it (at least you must able to read and understand English) before studying programming, since most all programming language tools, errors, and documentation written in English.

Tips on learning programming and train your logic

Actually, learning programming language is quite similar to learning ordinary language (Indonesian or English).

1. memorize the syntax

  • first thing you must do is.. memorize the syntax, yes, because it would took a long time to describe logic with shapes and pictures ^^ (especially when the logic is too long and complex), so learn how to describe a logic, and the most concrete way to do it is using a programming language!
    • understand and memorize how to create a variable, data types (character, integer, real numbers, boolean, string), how program works (from beginning to end, or line by line), how to create a main function and how to compile
    • this is analogous to understand a alphabet and how words are made, kind of words (nouns, adjective, verbs, adverb, etc)
    • we could not make a correct word without understanding alphabet
    • we could not make a correct statement without understanding kinds of words (is this word a subject/name? is this word a predicate/verb? is this an object/complement? is this word a modifier?)
    • people (or the compiler) would complain if we write many statements without punctuations (dot or question mark or exclamation sign, etc)
    • by doing a compilation process, it's like to tell the word processor to do a spell-check on our script, is there any miss-spelling on my script?
  • understand and memorize how to use ask for input and give an output, using built-in functions and math operators (addition, subtraction, division, multiplication and modulo), grammar, and also feedback (error and how to run a program)
    • this step analogous to how to create a statement, how to ask a question and how to give a correct answer
    • after we know how to ask and answer, we now could interact with computer, we also required to store their answer for later decision (just like approaching someone you like, if we remember that she like noodle (stored on a variable), maybe sometime we could ask her out on some noodle restaurant)
    • understand that there would be an input (how we tell something to the computer), process (how computer transform data into information), and output (how computer tell us something)
    • including a customer feedback, in this case, we are the store manager (or producer), and compiler is our prospective buyer/customer, when we knew that customer want, we already reduce 1/3rd of the problem (compile error - correct purchase request), 2 other problem would be runtime error (correct purchase order but our staff execute it poorly or give wrong item), and logic error (understand what customer need, but give a bad service)
    • running a program is just like accepting reader's feedback, is what we write could be understood well by computer (give an expected result)
  • learn and understand how boolean algebra works (and, or), branch or decision (if-then), looping or iteration (while, until) 
    • this is analogous to understand how to make correct life decision (if I need money, I should work; if I want to be an expert in certain field, I must practice and use it in my life, I must keep trying until I succeed or until I gave up; etc)
  • just doing first three steps is enough to write a program, but if you want your life to be easier, learn how to make a phrase/synonym/acronym (function/procedure + array/list/associative array/map + struct/record)
    • this is analogous to understanding certain word or phrase to shorten our statements (rather than say "4 legged animal that say meow", it would be easier to call it a "cat")
  • these first steps can be done by reading a good programming books
  • the criteria of success for step #1 is when you could read many program's source code and understand it's meaning, line by line

2. try to write, practice, practice and practice..

  • read a question, understand what's the input, what's the output, and what how to process those input into a correct output, for example, if you're given a raw ingredients, how to process it into a well prepared hot soup that ready to be eaten?
    • if you could not found the answer by yourself, you must read other people's source code (for example in codeforces), try to read and understand, imitate (try to cook it yourself), don't ask for other people to cook it for you (directly copying and pasting) then you claim it as your own soup
  • try to solve questions on the online judge (for example in URI, SPOJ, UVA, etc)
    • more you practice cooking, or workout/exercise, or anything, we would become more experienced in that field.. (practice doesn't lie - the practice result/planting/investing time/money correctly will produce a result)
    • start from easiest problem (start crawling, walking before you learn to run)
  • and lastly, don't start step 2 before you do step 1 (start by writing an alphabet before you write a poem)

Tips sukses belajar bahasa pemrograman dan mengasah logika

Benernya belajar bahasa pemrograman itu sama saja seperti mempelajari bahasa biasa (Indonesia or Inggris).

1. hafalkan syntax-nya.

  • pertama kali yang harus dilakukan adalah, hafalkan syntax, yup, karena mendeskripsikan suatu logika dengan gambar itu merepotkan ^^ (apalagi kalo logika-nya panjang dan kompleks); jadi dipelajari dahulu cara mendeskripsikan suatu logika, dan cara yang paling kokrit adalah dengan bahasa pemrograman!
    • pahami dan hafalkan cara membuat variabel, jenis2 tipe data (karakter, bilangan bulat, bilangan riil, boolean, string), cara program berjalan (dari atas ke bawah atau baris demi baris), cara membuat fungsi main dan cara compile..
    • ini analoginya seperti memahami huruf dan bagaimana sebuah kata dibentuk, jenis-jenis kata (kata benda, kata sifat, kata kerja, kata keterangan, dst)
    • kita tidak bisa membuat kata dengan benar kalau belum hafal semua huruf
    • kita tidak bisa membuat kalimat dengan benar, kalau tidak tahu kata ini jenisnya apa (subject/nama orang kah? predikat/kata kerja kah? obyek kah? kata keterangankah?)
    • orang (atau compiler) akan ngomel2 ketika kita menulis banyak kalimat tanpa diberi titik (atau titik koma atau pemisah lainnya)
    • dengan melakukan proses compile, itu seperti meminta program word processor untuk memeriksa spelling, ada kata/huruf yang salah atau tidak di naskah ku?
  • pahami dan hafalkan cara meminta input dan mencetak output, cara menggunakan fungsi2 bawaan dan operator2 matematika (penjumlahan, pengurangan, pembagian, perkalian, modulo, akar), tata bahasa, dan feedback (cara membaca error dan cara run program)
    • ini analoginya seperti memahami cara membuat kalimat (SPOK), cara membuat kalimat tanya, dan cara menjawab yang benar
    • setelah tahu cara bertanya dan cara menjawab, kita sudah bisa berinteraksi (PDKT dengan komputer), kita tinggal simpan jawaban si komputer untuk masa depan, misal dia suka makan ayam, ya suatu saat kita masak'kan soto ayam atau ayam goreng, dll
    • pahami bahwa minimal ada input (cara kita memberi tahu komputer), proses (cara data diubah menjadi informasi oleh komputer), dan output (cara komputer memberi tahu kita)
    • termasuk dengan customer feedback, dalam hal ini kita yang jadi toko/produser/distributor, compiler yang jadi customer; ketika tahu customer maunya apa, ya kita sudah mengurangi 1/3 masalah.. (compile error - pesanan benar), 2 masalah lagi adalah: runtime error (pesanan benar tapi staff kalian salah ngasih barang) dan logic error.. (paham kebutuhan customer tapi salah dalam memberikan pelayanan)
    • run program itu seperti menerima feedback dari pembaca, apakah yang ingin kumaksud sama dengan yang dipahami oleh komputer (hasilnya sesuai keinginan)
  • pahami dan hafalkan cara kerja aljabar boolean (dan, atau), percabangan (bila/jika, maka), perulangan (sampai, ketika masih)
    • ini analoginya seperti memahami cara membuat keputusan hidup yang benar, (jika butuh uang, maka saya harus bekerja; jika saya ingin mahir di suatu bidang, maka saya harus latihan dan sering menggunakannya dalam kehidupan; saya akan mencoba terus sampai saya berhasil atau saya putus asa; dst)
  • benernya dari 3 hal di atas sudah cukup untuk membuat program, tapi kalau mau hidup lebih mudah, pelajari cara membuat istilah/sinonim/frasa (fungsi/prosedur + array/list/associative array/map + struct/record)
    • ini analoginya seperti memahami suatu istilah, dengan menggunakan istilah, kita dapat mempersingkat kalimat (daripada menyebut "binatang berkaki empat yang mengeong", kan lebih muda menyebutnya "kucing")
  • step pertama ini bisa dilakukan dengan membaca buku programming yang tepat.
  • kesuksesan step pertama bisa diukur ketika sudah sanggup membaca banyak source code program dan memahami maksudnya baris demi baris.

2. coba menulis, latihan, latihan, dan latihan..

  • baca soal, dipahami apa inputnya, apa outputnya, dan kira2 prosesnya seperti apa (diapakan), misal dikasih 1 bungkus mie instan, maka harus diapakan supaya jadi mie goreng yang siap dimakan?
    • kalau belum bisa menemukan sendiri, ya terpaksa baca source code orang (misal di codeforces), pahami, tiru (dicoba masak sendiri), jangan minta orang lain yg membuatkan (copy paste langsung) lalu di claim sebagai mie goreng buatan sendiri..
  • coba soal2 di online judge (misal TOKI Learning Center, URI, SPOJ, dst)
    • makin sering kita latihan masak, atau olahraga, atau apapun, maka kita akan makin mahir.. (practice doesn't lie - hasil latihan/menanan/menginvestasikan materi/waktu dengan benar pasti berbuah)
    • mulailah dari problem/soal yang paling sederhana (belajarlah merangkak terlebih dahulu sebelum belajar berlari).
  • jangan lupa, jangan mulai step 2 sebelum menjalankan step 1 (belajarlah menulis huruf terlebih dahulu, sebelum belajar membuat puisi).







2014-12-18

Benchmark of Go's (Current) Best Router/Mux

Yesterday I stumbled upon a benchmark by euforic. So today I sort all the benchmark, remove all with high memory usages, and ones with worst performance and end up with this spreadsheet visualization (oh before I forgot, LibreOffice Calc conditional formatting is freakin' buggy).


And if you asked me, what's the best for all case? Just search for one that have the most green. Denco seems to have consistent performance, and FYI the older benchmark favors to HttpRouter.

2014-11-27

How to use Go-Couchbase

Today I will try to use Go-Couchbase, to insert, fetch, update and delete from database. To install go-couchbase, type this commands:

go get -u -v github.com/couchbaselabs/go-couchbase

Then just create an example source code and run it:

package main

import (
"fmt"

"github.com/couchbaselabs/go-couchbase"
//"github.com/davecgh/go-spew/spew"
"encoding/json"

"github.com/kr/pretty"
//"reflect"
"errors"
"runtime"
"strings"
)

var FILE_PATH string
var CB *couchbase.Bucket

// initialize file path
func init() {
_, file, _, _ := runtime.Caller(1)
FILE_PATH = file[:4+strings.Index(file, "/src/")]
err := errors.New("no error")
CB, err = couchbase.GetBucket("http://127.0.0.1:8091/", "default", "default")
Panic(err, "Error connection, getting pool or bucket:  %v")
}

// print warning message
func Check(err error, msg string, args ...interface{}) error {
if err != nil {
_, file, line, _ := runtime.Caller(1)
str := fmt.Sprintf("%s:%d: ", file[len(FILE_PATH):], line)
fmt.Errorf(str+msg, args...)
res := pretty.Formatter(err)
fmt.Errorf("%# v\n", res)
}
return err
}

// print error message and exit program
func Panic(err error, msg string, args ...interface{}) {
if Check(err, msg, args...) != nil {
panic(err)
}
}

// describe a variable
func Explain(args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
//res, _ := json.MarshalIndent(variable, "   ", "  ")
for _, arg := range args {
res := pretty.Formatter(arg)
fmt.Printf("%s:%d: %# v\n", file[len(FILE_PATH):], line, res)
}
//spew.Dump(variable)
}

func main() {

var err error

// save values (upsert)
err = CB.Set("someKey", 0, []string{"an", "example", "list"})
Check(err, "failed to set somekey")

err = CB.Set("primaryKey", 0, 1)
Check(err, "failed to set primaryKey")

// fetch one value
var rv interface{}
err = CB.Get("someKey", &rv)
Check(err, "failed to get someKey")
Explain(rv)

// fetch with CheckAndSet id
cas := uint64(0)
err = CB.Gets("primaryKey", &rv, &cas)
Check(err, "failed to get primaryKey")
Explain(cas, rv)

// fetch multivalue
rows, err := CB.GetBulk([]string{"someKey", "primaryKey", "nothingKey"})
Check(err, "failed to get someKey or primaryKey or nothingKey")
Explain(rows)

jsonStr := rows["someKey"].Body
Explain(string(jsonStr))

stringList := []string{}
err = json.Unmarshal(jsonStr, &stringList)
Check(err, "failed to convert back to json")
Explain(stringList)

// increment value, returns new value
nv, err := CB.Incr("primaryKey", 1, 1, 0)
Check(err, "failed to increment primaryKey")
Explain(nv)

// increment value, defaults to 1 if not exists
nv, err = CB.Incr("key3", 1, 1, 60)
Check(err, "failed to increment primaryKey")
Explain(nv)

}

This would give an output:

/test.go:92: []interface {}{
    "an",
    "example",
    "list",
}
/test.go:98: uint64(0x13aa8b32b9f7f091)
/test.go:98: float64(1)
/test.go:103: map[string]*gomemcached.MCResponse{
    "primaryKey": &gomemcached.MCResponse{
        Opcode: 0x0,
        Status: 0x0,
        Opaque: 0x0,
        Cas:    0x13aa8b32b9f7f091,
        Extras: {0x0, 0x0, 0x0, 0x0},
        Key:    {},
        Body:   {0x31},
        Fatal:  false,
    },
    "someKey": &gomemcached.MCResponse{
        Opcode: 0x0,
        Status: 0x0,
        Opaque: 0x0,
        Cas:    0x13aa8b32b9e4690f,
        Extras: {0x0, 0x0, 0x0, 0x0},
        Key:    {},
        Body:   {0x5b, 0x22, 0x61, 0x6e, 0x22, 0x2c, 0x22, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x22, 0x2c, 0x22, 0x6c, 0x69, 0x73, 0x74, 0x22, 0x5d},
        Fatal:  false,
    },
}
/test.go:106: "[\"an\",\"example\",\"list\"]"
/test.go:111: []string{"an", "example", "list"}
/test.go:116: uint64(0x2)
/test.go:121: uint64(0x4)

2014-11-26

How to start Martini Golang Project

Martini is another Golang web framework, that the design similar to Sinatra, to install it, just type this command:

go get -u -v github.com/go-martini/martini

Then, just create new source code, for example main.go:

package main
import "github.com/go-martini/martini"
func main() {
  m := martini.Classic()
  m.Get("/", func() string {
    return "Hello world!"
  })
  m.Run()
}

To run the website, just type:

go run main.go

Then visit http://localhost:3000/

We must recompile the source everytime the source code changed, that quite annoying and time consuming, to overcome that problem we could use a tool called gin, this program automatically run a program everytime there are code changed. To install this tool, type:

go get -u -v github.com/codegangsta/gin

Then run it using this command:

gin go run main.go

That command would create a proxy, if there are compilation errors, it would also show on the page.

How to install Goclipse and Golang IDEA plugin

Warning: current master version of these plugins (2014-11-25) are not good enough for daily coding, don't bother to try them for now.
Edit: latest alpha version of Golang IDEA plugin for IntelliJ are the best plugin for now.

Goclipse is another IDE for golang, that based on the infamous Eclipse platform. To install Eclipse, just type:

pacman -S eclipse

To install Goclipse, you must first clone the repository, for example using this command:

git clone --depth 1 https://github.com/GoClipse/goclipse.git

Then you must download all dependencies and start building:

cd goclipse
mvn clean integration-test
ant -f releng/ CreateProjectSite
ant -f releng/ PublishProjectSite

Last command would fail when not supplied with correct DprojectSiteGitURL parameter, but the required jars still resides in bin-maven/projectSite/, just use any webserver to serve the files as Eclipse update site, for example using php:

cd bin-maven/projectSite/
php -S localhost:9009

To install Goclipse, open Eclipse, Help > Install New Software..,  just add http://localhost:9009/releases

Then select Goclipse, next, accept the license, and finish.

Now the bad parts: bad coloring (for example, the operator color is not configurable), gocode doesn't work (even when GOPATH and GOROOT already configured on settings page and restarted), and autocomplete doesn't work at all.

Next we'll try IntelliJ with Golang IDEA plugin, first you must clone the repository:

git clone --depth 1 https://github.com/go-lang-plugin-org/go-lang-idea-plugin.git

Then place (or symlink) the IntelliJ program directory inside that folder that created by git, with name idea-IC, then just run:

ant -f build-package.xml

That command would produce a file named: google-go-language.jar, just install that plugin normally using on IntelliJ.

Now the bad parts: member autocomplete doesn't work at all (even when GOROOT and GOPATH configured on settings page and restarted).



2014-11-25

Wide: Web-based IDE for Go

Wide is one new web-based IDE, it has a lot of potential, for now, it has autocomplete and one that have working "go to definition".

To install Wide, type:

go get -u -v github.com/88250/ide_stub
go get -u -v github.com/nsf/gocode
go get -u -v github.com/b3log/wide

To start the program, type:

cd $GOPATH/src/github.com/b3log/wide/
wide

Then visit using your browser on http://your_ip_address:7070


There are some other web-based IDE such as GoDev (lags when showing godoc), LimeText, Carpo, Atom (aur/atom-editor-bin), Brackets.io, and Conception-go (this one not a web-based :3 it's OpenGL)
Btw, I make a list on GoogleDocs to list all Go IDEs, you can contribute/edit it if you want..

2014-11-04

How to start Revel, GORM with PostgreSQL project on Archlinux

Revel is one of many Go Web Application Framework that uses Go programming language. After installing Archlinux, first of all you'll need to install yaourt, the easiest way to install AUR packages. After that you'll need to run this command:

yaourt -Sy --noconfirm go postgresql postgresql-libs liteide chromium google-chrome-stable

Then setup your GOPATH and GOROOT environment variables on your .bashrc

export GOROOT=/usr/lib/go
export GOPATH=$HOME/Dropbox/go
export PATH="$PATH:$GOPATH/bin"


Change the permission of this folder:

sudo chmod -Rv a+rwx /usr/share/liteide/liteenv

Then open LiteIDE, select menu View > Edit Environment, then add this line and save:

GOROOT=/usr/lib/go

Add also a GOPATH directory on menu View > Manage GOPATH...
That is ~/Dropbox/go on my computer.

To test if your Go and LiteIDE working correctly, create a new .go file and press Build > FileRun to run, for example:

package main
import "fmt"
func main() {
  fmt.Println("Hello my PC <3")
}

The code above should give an output on Build output window.

To install revel, type this on shell:

go get -u -v github.com/revel/cmd/revel
go get -u -v github.com/revel/revel


To create a new project (for example, the name would be "puis"), type:

cd $GOPATH
revel new puis

Then you could start the app using this command:

revel run puis

And visit http://localhost:9000 to view your app.

Next, we should install PostgreSQL driver and GORM, type:

go get -u -v github.com/lib/pq
go get -u -v github.com/jinzhu/gorm

Then initialize and start your database server:

sudo su - postgres
initdb --locale en_US.UTF-8 -E UTF8 -D '/var/lib/postgres/data'
exit
sudo systemctl enable postgresql
sudo systemctl start postgresql
sudo su - postgres
createuser puis
createdb puis
psql 
GRANT ALL PRIVILEGES ON DATABASE puis TO puis;
\q
exit

Then create a model, for example in app/models/user.go

package models
import "time"
type User struct {
  Id                int64
  Name              string
  Gmail             string
  PuMail            string
  Password          string
  CreatedAt         time.Time
  UpdatedAt         time.Time
  DeletedAt         time.Time
  LastLoginAt       time.Time
  PasswordUpdatedAt time.Time
}

And create a controller for GORM in app/controllers/gorm.go

package controllers
import (
  "database/sql"
  "github.com/jinzhu/gorm"
  _ "github.com/lib/pq"
  "github.com/revel/revel"
  "puis/app/models"
)
type GormController struct {
  *revel.Controller
  Tx *gorm.DB
}
var Db gorm.DB
func InitDB() {
  var err error
  Db, err = gorm.Open("postgres", "user=puis sslmode=disable")
  if err != nil {
    revel.ERROR.Println("FATAL", err)
    panic(err)
  }
  tab := &models.User{}
  Db.AutoMigrate(tab)
  Db.Model(tab).AddUniqueIndex("idx_user__gmail", "gmail")
  Db.Model(tab).AddUniqueIndex("idx_user__pu_mail", "pu_mail")
}
func (c *GormController) Begin() revel.Result {
  txn := Db.Begin()
  if txn.Error != nil {
    panic(txn.Error)
  }
  c.Tx = txn
  revel.INFO.Println("c.Tx init", c.Tx)
  return nil
}
func (c *GormController) Commit() revel.Result {
  if c.Tx == nil {
    return nil
  }
  c.Tx.Commit()
  if err := c.Tx.Error; err != nil && err != sql.ErrTxDone {
    panic(err)
  }
  c.Tx = nil
  revel.INFO.Println("c.Tx commited (nil)")
  return nil
}

func (c *GormController) Rollback() revel.Result {
  if c.Tx == nil {
    return nil
  }
  c.Tx.Rollback()
  if err := c.Tx.Error; err != nil && err != sql.ErrTxDone {
    panic(err)
  }
  c.Tx = nil
  return nil
}

Also call those functions when application starts also before and after controller calling, add these lines in app/init.go on func init()

revel.OnAppStart(controllers.InitDB)
revel.InterceptMethod((*controllers.GormController).Begin, revel.BEFORE)
revel.InterceptMethod((*controllers.GormController).Commit, revel.AFTER)
revel.InterceptMethod((*controllers.GormController).Rollback, revel.FINALLY)

Two more things, add a testing code, for example in app/controllers/app.go on func Index()

user := &models.User{Name: "Kiswono Prayogo"}
c.Tx.NewRecord(user)
c.Tx.Create(user)
return c.Render(user) 

Last thing, just add one more line anywhere on Index.html

{{.user.Name}}

That's it, this is how to connect Revel to PostgreSQL using GORM. This tutorial adapted from Ivan Black's stackoverflow answer.

To solve slow Revel hot-reload or Go build/install, just use this command:

go get -u -v github.com/mattn/go-sqlite3

2014-08-23

Where to put fonts on Linux

To install fonts on Linux (especially Arch Linux), you must copy the fonts on the ~/.local/share/fonts folder (for old distribution, use ~/.fonts directory). To view fonts, install gnome-font-viewer, that program could also be used to install fonts locally. I have selected some fonts that good for programming imho. Contact me (if you can ^^ myahahah!) if the server is down or expired, or just google for these fonts:

BPmono.ttf BPmonoBold.ttf BPmonoItalics.ttf DejaVuSans-Bold.ttf DejaVuSans-BoldOblique.ttf
DejaVuSans-ExtraLight.ttf DejaVuSans-Oblique.ttf DejaVuSans.ttf DejaVuSansCondensed-Bold.ttf DejaVuSansCondensed-BoldOblique.ttf
DejaVuSansCondensed-Oblique.ttf DejaVuSansCondensed.ttf DejaVuSansMono-Bold.ttf DejaVuSansMono-BoldOblique.ttf DejaVuSansMono-Oblique.ttf
DejaVuSansMono.ttf DejaVuSerif-Bold.ttf DejaVuSerif-BoldItalic.ttf DejaVuSerif-Italic.ttf DejaVuSerif.ttf
DejaVuSerifCondensed-Bold.ttf DejaVuSerifCondensed-BoldItalic.ttf DejaVuSerifCondensed-Italic.ttf DejaVuSerifCondensed.ttf DroidSansMono.ttf
Envy Code B 10pt.ttf Envy Code R Bold.ttf Envy Code R Italic.ttf Envy Code R VS Italic-as-bold.ttf Envy Code R VS.ttf
Envy Code R.ttf FantasqueSansMono-Bold.ttf FantasqueSansMono-BoldItalic.ttf FantasqueSansMono-RegItalic.ttf FantasqueSansMono-Regular.ttf
FiraMono-Bold.ttf FiraMono-Medium.ttf FiraMono-Regular.ttf FiraSans-Bold.ttf FiraSans-BoldItalic.ttf
FiraSans-Book.ttf FiraSans-BookItalic.ttf FiraSans-Eight.ttf FiraSans-EightItalic.ttf FiraSans-ExtraBold.ttf
FiraSans-ExtraBoldItalic.ttf FiraSans-ExtraLight.ttf FiraSans-ExtraLightItalic.ttf FiraSans-Four.ttf FiraSans-FourItalic.ttf
FiraSans-Hair.ttf FiraSans-HairItalic.ttf FiraSans-Heavy.ttf FiraSans-HeavyItalic.ttf FiraSans-Italic.ttf
FiraSans-Light.ttf FiraSans-LightItalic.ttf FiraSans-Medium.ttf FiraSans-MediumItalic.ttf FiraSans-Regular.ttf
FiraSans-SemiBold.ttf FiraSans-SemiBoldItalic.ttf FiraSans-Thin.ttf FiraSans-ThinItalic.ttf FiraSans-Two.ttf
FiraSans-TwoItalic.ttf FiraSans-Ultra.ttf FiraSans-UltraItalic.ttf FiraSans-UltraLight.ttf FiraSans-UltraLightItalic.ttf
LiberationMono-Bold.ttf LiberationMono-BoldItalic.ttf LiberationMono-Italic.ttf LiberationMono-Regular.ttf LiberationSans-Bold.ttf
LiberationSans-BoldItalic.ttf LiberationSans-Italic.ttf LiberationSans-Regular.ttf LiberationSerif-Bold.ttf LiberationSerif-BoldItalic.ttf
LiberationSerif-Italic.ttf LiberationSerif-Regular.ttf MesloLGLDZ-Bold.ttf MesloLGLDZ-BoldItalic.ttf MesloLGLDZ-Italic.ttf
MesloLGLDZ-Regular.ttf MesloLGMDZ-Bold.ttf MesloLGMDZ-BoldItalic.ttf MesloLGMDZ-Italic.ttf MesloLGMDZ-Regular.ttf
MesloLGSDZ-Bold.ttf MesloLGSDZ-BoldItalic.ttf MesloLGSDZ-Italic.ttf MesloLGSDZ-Regular.ttf Monaco.ttf
PTM55F.ttf PTM75F.ttf VeraMono-Bold-Italic.ttf VeraMono-Bold.ttf VeraMono-Italic.ttf
VeraMono.ttf drucifer_0.ttf drucifer_i.ttf edlo.ttf mplus-1c-black.ttf
mplus-1c-bold.ttf mplus-1c-heavy.ttf mplus-1c-light.ttf mplus-1c-medium.ttf mplus-1c-regular.ttf
mplus-1c-thin.ttf mplus-1m-bold.ttf mplus-1m-light.ttf mplus-1m-medium.ttf mplus-1m-regular.ttf
mplus-1m-thin.ttf mplus-1mn-bold.ttf mplus-1mn-light.ttf mplus-1mn-medium.ttf mplus-1mn-regular.ttf
mplus-1mn-thin.ttf mplus-1p-black.ttf mplus-1p-bold.ttf mplus-1p-heavy.ttf mplus-1p-light.ttf
mplus-1p-medium.ttf mplus-1p-regular.ttf mplus-1p-thin.ttf mplus-2c-black.ttf mplus-2c-bold.ttf
mplus-2c-heavy.ttf mplus-2c-light.ttf mplus-2c-medium.ttf mplus-2c-regular.ttf mplus-2c-thin.ttf
mplus-2m-bold.ttf mplus-2m-light.ttf mplus-2m-medium.ttf mplus-2m-regular.ttf mplus-2m-thin.ttf
mplus-2p-black.ttf mplus-2p-bold.ttf mplus-2p-heavy.ttf mplus-2p-light.ttf mplus-2p-medium.ttf
mplus-2p-regular.ttf mplus-2p-thin.ttf

Installing Go 1.3.1 with LiteIDE x23.2 on Arch Linux

So I installing new computer on my company, using Arch Linux as usual.

How to install Go? it's really easy when using yaourt, just type:

yaourt --needed --noconfirm -S --force go mercurial git bzr subversion liteide gdb

Go took about 40.76 MB
Mercurial, Git, Bzr and Subversion requires about 13.12 MB
LiteIDE took about 13.14 MB
Gdb took about 3.06 MB

Set your working directory:

mkdir ~/go
export GOPATH=~/go
export PATH=$PATH:~/go/bin


I suggest that you should put those environment variables on .bashrc

Then you can test the installation, create a file named test1.go

package main
import "fmt"
func main() {
  fmt.Println("Hello my lovely PC :3")
}


Run it using:

go run test1.go 

or

go build test1.go && ./test1

or press Ctrl+R on LiteIDE.

2014-08-11

How to make git ignore changes on commited files?

Sometimes there are some file that we want to ignore some file on git, of course we could use .gitignore, but that only take effect on untracked files. When the files already tracked/commited, we could make that file changes ignored using git update-index command, for example:

git update-index --assume-unchanged file-to-be-ignored

From now on, that file would not appear on git status or git diff when changed. When you want to track back the changes, use --no-assume-unchanged flag.

What to do when git pull conflict before commit?

Sometimes we want to pull from git without committing current changes, and yes, the correct way is to commit our changes first before pulling, so we could merge the conflict. But if you doesn't want to do that, there are some trick that you could use, that is git stash, the usage example:

# to store all changes on the stash
git stash
# this should no longer conflict
git pull
# to overwrite from previous stash
git stash pop
# you could see the difference using
git diff

2014-08-04

Open Source Desktop Database GUI

When developing database apps sometimes we need easier user interface to query the database, instead of using command line (mysql for MySQL, psql for PostgreSQL), or using MySQL Workbench or the default pgAdmin. When you're using any of IDE from JetBrains you could use their Database Explorer.

DBeaver is one open source and cross platform database explorer, but it doesn't really work well with dark theme.
SQL Workbench also open source java-based database explorer, works fine with dark theme, but failed to display invalid Date.
Execute Query quite fine, I have no rants about this one.
Oh well I'll find and try another later on.

2014-07-31

How to set Komodo Edit as Go IDE with komodo-go

LiteIDE 23.1 is quite good enough IDE for Go in my opinion, the autocomplete and method hint works fine. All we need after installing is just configure the Environment file (View > Edit Environment) such as this:

GOROOT=/usr/lib/go
GOBIN=/home/kyz/Dropbox/go/bin

Don't forget to change the ownership or you won't able to save:

sudo chown `whoami` /usr/share/liteide/liteenv/*

Also don't forget to add custom GOPATH (View > Manage GOPATH..) if necessary


But sometimes the jump to declaration feature doesn't work at all.
There are another alternative that is komodo-edit, you can install it using:

pacman -Sy komodo-edit

Then you could clone the komodo-go repository:

cd /tmp
git clone https://github.com/Komodo/komodo-go
cd komodo-go

Make sure that you have installed Python 2.x, and then just built the extension

/opt/komodo-edit/lib/sdk/bin/koext build

Then drag the .xpi file into Komodo Extension Manager.
Now, install godef to make it support jump to declaration command:

go get -u -v code.google.com/p/rog-go/exp/cmd/godef

Now your komodo-edit with Go integration will work as expected.



2014-07-28

Xfce4 CPU, RAM, Network and Disk Monitoring Applet

When using Gnome or Xfce4, I always have the urge to monitor CPU, RAM, network and disk usage/throughput. This is the screenshot of my xfce4 panel:


To make it happened, I modified Ciriaco's source code to suit my need:

curl -L http://goo.gl/MO3lx5 > netmon.cpp
g++ -O3 -lrt netmon.cpp -o netmon
sudo mv netmon /usr/bin/

So when netmon program executed, it would give an XML ouput (note that enp1s0 is my network interface name):

netmon enp1s0 
<txt>D:   312 KB/s  | U:    15 KB/s  | CPU:  12% | RAM:  7008 MB | sdc:   .   . | sda:   .   . | sdb:   .   1 | sdf:   .   . | sde:   .   . | sdd:   .   . | sdg:   .   .</txt><tool> enp1s0:
    3102.07 MB received 
    261.08 MB sent 
 CPU usage:
     15.6% since boot 
 RAM usage:
     45.4% of 15436 MB</tool>

The next step is installing Generic Monitor Applet:

yaourt -Sy xfce4-genmon-plugin

Add it to your panel (right click on panel > Panel > Add New Item..), and configure it:

And your CPU, RAM, network and disk is now appeared on the panel ^_^)b

Disk monitoring notes:

  • dot means idle
  • zero means <1MB/s read/write
  • others in MB/s

Installing HHVM on Ubuntu or ArchLinux

As we already know, HHVM is the fastest PHP interpreter/JIT-compiler for 64-bit systems. To install HHVM on Ubuntu, the easiest way is use the PPA using these commands:

# install HHVM repos' public key
wget -O - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-key add -

# add HHVM repos
echo deb http://dl.hhvm.com/ubuntu trusty main | sudo tee /etc/apt/sources.list.d/hhvm.list

# update list of available software
sudo apt-get update

# install hhvm
sudo apt-get install hhvm

Or when using archlinux, use yaourt command (warning: this would compile the hhvm package, that requires about ~1 hour and more than 2GB of RAM, so add a virtual memory if your RAM not big enough)

sudo yaourt --needed --noconfirm -S --force hhvm

As we already know, since PHP 5.4, PHP can be used without installing any webserver (Apache, Nginx, IIS), use this command to run built-in web server on localhost:8083:

hhvm -m server -p 8083
mapping self...
mapping self took 0'00" (18015 us) wall time
loading static content...
loading static content took 0'00" (0 us) wall time
page server started
all servers started

or when using standard PHP:

php -S localhost:8083
PHP 5.5.15 Development Server started at Mon Jul 28 20:48:06 2014
Listening on http://localhost:8083
Document root is /tmp
Press Ctrl-C to quit.

Installing Ruby 2.1+ on Ubuntu (via RVM)

On some distro, Ruby interpreter was out of date

apt-cache show ruby2.0 | grep Version
Version: 2.0.0.484-1ubuntu2

And we want the latest version, we could use Brightbox's PPA:

# install add-apt-repository command
sudo apt-get install software-properties-common python-software-properties

# add brightbox's repository
sudo apt-add-repository ppa:brightbox/ruby-ng

# update list of available software
sudo apt-get update

# install ruby
sudo apt-get install ruby2.1

Or use RVM, the Ruby Version Manager, that could be installed using these commands:

# install rvm
curl -sSL https://get.rvm.io | bash

# use rvm (or relogin/restart bash, since it's inserted into .bashrc)
source /etc/profile.d/rvm.sh

to see the list of available version, we could use:

rvm list known

to install the latest version, run this command:

rvm install ruby-2.1.2
ruby-2.1.2 - #removing src/ruby-2.1.2..
ruby-2.1.2 - #removing rubies/ruby-2.1.2..
Searching for binary rubies, this might take some time.
Found remote file https://rvm.io/binaries/ubuntu/14.04/x86_64/ruby-2.1.2.tar.bz2
Checking requirements for ubuntu.
Requirements installation successful.
ruby-2.1.2 - #configure
ruby-2.1.2 - #download
######################################################################## 100.0%
ruby-2.1.2 - #validate archive
ruby-2.1.2 - #extract
ruby-2.1.2 - #validate binary
ruby-2.1.2 - #setup
ruby-2.1.2 - #gemset created /usr/local/rvm/gems/ruby-2.1.2@global
ruby-2.1.2 - #importing gemset /usr/local/rvm/gemsets/global.gems....................................
ruby-2.1.2 - #generating global wrappers........
ruby-2.1.2 - #gemset created /usr/local/rvm/gems/ruby-2.1.2
ruby-2.1.2 - #importing gemsetfile /usr/local/rvm/gemsets/default.gems evaluated to empty gem list
ruby-2.1.2 - #generating default wrappers........
Making gemset ruby-2.1.2 pristine.............................................................
Making gemset ruby-2.1.2@global pristine..............................................................


Voila, done! now we could use it using this command:

rvm use ruby-2.1.2 

ruby --version
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]

gem install pry
Fetching: coderay-1.1.0.gem ( 52%)
Fetching: coderay-1.1.0.gem (100%)
Successfully installed coderay-1.1.0
Fetching: slop-3.6.0.gem (100%)
Successfully installed slop-3.6.0
Fetching: method_source-0.8.2.gem (100%)
Successfully installed method_source-0.8.2
Fetching: pry-0.10.0.gem (100%)
Successfully installed pry-0.10.0
invalid options: -SNw2
(invalid options are ignored)
Parsing documentation for coderay-1.1.0
Installing ri documentation for coderay-1.1.0
Parsing documentation for method_source-0.8.2
Installing ri documentation for method_source-0.8.2
Parsing documentation for pry-0.10.0
Installing ri documentation for pry-0.10.0
Parsing documentation for slop-3.6.0
Installing ri documentation for slop-3.6.0
Done installing documentation for coderay, method_source, pry, slop after 4 seconds
4 gems installed




Installing Go 1.3+ on Ubuntu via GVM (Go Version Manager)

Sometimes on some Linux distribution, the Go package are out of date, for example:

apt-cache show golang | grep Version
Version: 2:1.2.1-2ubuntu1

and we look for the PPA (user repository) but failed to see the latest version!
One solution that we could use is using GVM that could be installed using this command:

# install dependencies
sudo apt-get install curl git mercurial make binutils bison gcc

# install gvm
bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

# use gvm (or relogin/restart bash, since it's inserted into .bashrc)
source ~/.gvm/scripts/gvm

to see the list of available version, we could use:

gvm listall

to install Go 1.3, we could use this command:

gvm install go1.3
Installing go1.3...
 * Compiling...

Voila, done! now we could use it using this command:

gvm use go1.3
Now using version go1.3
go version
go version go1.3 linux/amd64


Better Grep, Grep files with line numbers (ag)

Sometimes when programming on my old Netbook (that not powerful enough top open any IDE, so I must use just a standard text editor such as Vim or GEdit), I need to quickly search some string (function, symbol or signature) on all source code in my project, that I will use:

grep -n Symbol *.rb */*.rb */*/*.rb

(-n is line number, Symbol is the search string) that will show something like this:


Now I found a better way, The Silver Searcher! Ag (argentum, latin name for Silver), when using Ubuntu, you could install it using this command:

sudo apt-get install silversearcher-ag

or when using ArchLinux:

sudo pacman -Sy the_silver_searcher

and use it just like grep ^_^)b for example:

ag --ruby Symbol .

(--ruby means all ruby source code, dot means only on current directory, recursively) that will show something like this: