go: base64 decoding

Here is an example how to decode base64 encoded strings https://play.golang.org/p/iojjUKwvZvn
It uses encoding packages encoding/base64 and encoding/hex .

package main

import (
	"fmt"
	"encoding/base64"
	"encoding/hex"
)

func isAscii7printable(bytes []byte)(bool){
   for _, b := range bytes {
   	if b < 32 || b > 127 {
		return false
	}
   }
   return true
}

func main() {
	b64 := "QUJD"  //ABC
	b64  = "QUJD-" //illegal base64 data at input byte 4
	b64  = "QUIK"  //AB\n
	
	bytes, err := base64.StdEncoding.DecodeString(b64)
	if err != nil {
	   fmt.Println("Input string `", b64, "`has an error: ", err.Error())
	   return
	}
        hexBytes := make([]byte, hex.EncodedLen(len(bytes)))
	hex.Encode(hexBytes, bytes)
	
	fmt.Println("Decoding base64 encoded strings")
	fmt.Println("===============================")
	fmt.Printf("Base64: %s\n", b64)
	fmt.Printf("Length: %d bytes; %d bits\n", len(bytes), 8*len(bytes))
	fmt.Printf("Hex   : %s \n", hexBytes)	

	if isAscii7printable(bytes) {
		fmt.Println("String: "+string(bytes))
	} else {
		fmt.Println("There are non ASCII7 characters.")
	}
}

Output could be:
Decoding base64 encoded strings
===============================
Base64: QUIK
Length: 3 bytes; 24 bits
Hex : 41420a
There are non ASCII7 characters.

Or after commenting two b64 lines:
Decoding base64 encoded strings
===============================
Base64: QUJD
Length: 3 bytes; 24 bits
Hex : 414243
String: ABC

For decoding non printable characters is good to use hex.Dump, see https://play.golang.org/p/f6fQpbqeHo8

package main

import (
	"fmt"
	"encoding/base64"
	"encoding/hex"
)

func b64print(b64 string) {
	bytes, err := base64.StdEncoding.DecodeString(b64)
	fmt.Printf("Base64 : %s\n", b64)
	if err != nil {
	   fmt.Printf("Input string '%s' has an error: %s\n\n", b64, err.Error())
	   return
	}
	fmt.Printf("Decoded: length: %d bytes ~ %d bits, `hexdump -C` format:\n", len(bytes), 8*len(bytes))
	fmt.Printf("%s\n", hex.Dump(bytes))	
}

func main() {
	fmt.Println("Decoding base64 encoded strings")
	fmt.Printf("===============================\n\n")

        b64print("wrong")
	b64print("SGVsbG8gV29ybGQh")
	b64print("VGFsbCByZWQgdHJlZSBvbiB0aGUgcml2ZXIgYmFuay4=")
	b64print("QSBsYXp5IGZveCBqdW1wcyBvdmVyIHF1aWNrIGJyb3duIGRvZyEgRW1haWw6dTEwQG15LmV4YW1wbGUub3JnIA==")
}

Here is an output:
Decoding base64 encoded strings
===============================

Base64 : wrong
Input string 'wrong' has an error: illegal base64 data at input byte 4

Base64 : SGVsbG8gV29ybGQh
Decoded: length: 12 bytes ~ 96 bits, `hexdump -C` format:
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 |Hello World!|

Base64 : VGFsbCByZWQgdHJlZSBvbiB0aGUgcml2ZXIgYmFuay4=
Decoded: length: 32 bytes ~ 256 bits, `hexdump -C` format:
00000000 54 61 6c 6c 20 72 65 64 20 74 72 65 65 20 6f 6e |Tall red tree on|
00000010 20 74 68 65 20 72 69 76 65 72 20 62 61 6e 6b 2e | the river bank.|

Base64 : QSBsYXp5IGZveCBqdW1wcyBvdmVyIHF1aWNrIGJyb3duIGRvZyEgRW1haWw6dTEwQG15LmV4YW1wbGUub3JnIA==
Decoded: length: 64 bytes ~ 512 bits, `hexdump -C` format:
00000000 41 20 6c 61 7a 79 20 66 6f 78 20 6a 75 6d 70 73 |A lazy fox jumps|
00000010 20 6f 76 65 72 20 71 75 69 63 6b 20 62 72 6f 77 | over quick brow|
00000020 6e 20 64 6f 67 21 20 45 6d 61 69 6c 3a 75 31 30 |n dog! Email:u10|
00000030 40 6d 79 2e 65 78 61 6d 70 6c 65 2e 6f 72 67 20 |@my.example.org |

Posted in golang, workday | Leave a comment

go: characters frequency

Let’s explore characters frequency in the go string. Characters in go are in the format int32 – rune, and they can have any unicode value. Here is a simple go program https://play.golang.org/p/fbg7VXetxCg .

package main

import (
	"fmt"
	"sort"
)
func runeCharsFrequency(inpStr string) string {
	m := make(map[rune]int)
	for _, runeChar := range inpStr {
		m[runeChar]++
	}
	var keys []rune
	for kRune, _ := range m {
		keys = append(keys, kRune)
	}
	sort.Slice(keys, func(i, j int) bool {
		return keys[i] < keys[j]
	})

	outStr := ""
	comma := ""
	for _, k := range keys {
		outStr += fmt.Sprint(comma, k, ":", m[k])
		comma = ", "
	}
	return outStr
}
func main() {
        s := "Hello World!!!!!"
	fmt.Println("Characters frequency in string: "+s)
	fmt.Println(runeCharsFrequency(s))
}

Characters in the output have ordinal value and count:
32:1, 33:5, 72:1, 87:1, 100:1, 101:1, 108:3, 111:2, 114:1

Posted in golang, workday | Leave a comment

go: duration loop

Here is a simple duration loop go program https://play.golang.org/p/ly9U9EUr2of

package main

import (
	"fmt"
	"time"
)

func main() {
	duration := time.Second *10
	fmt.Println("Hello, duration loop "+duration.String()+" long")
	
	t1 := time.Now()
	
	for t2:= time.Now(); t2.Sub(t1) < duration; t2 = time.Now(){
	   	fmt.Println(t2.String())
		time.Sleep(time.Second)
	
	}
}

Posted in golang, workday | Leave a comment

go: proverbs

Rob Pike at Gopherfest on November 18, 2015 mentioned several thoughtful go proverbs, as you may see on this video. Here they are:

  1. Don’t communicate by sharing memory, share memory by communicating.
  2. Concurrency is not parallelism.
  3. Channels orchestrate; mutexes serialize.
  4. The bigger the interface, the weaker the abstraction.
  5. Smaller the interface, more useful.
  6. Make the zero value useful.
  7. interface{} says nothing.
  8. Gofmt’s style is no one’s favorite, yet gofmt is everyone favorite.
  9. A little copying is better than a little dependency.
  10. Syscall must always be guarded with build tags.
  11. Cgo must always be guarded with build tags.
  12. Cgo is not Go.
  13. With the unsafe package there are no guarantees.
  14. Clear is better then clever.
  15. Reflection is never clear.
  16. Errors are values.
  17. Don’t just check errors, handle them gracefully.
  18. Design the architecture, name the components, document the details.
  19. Documentation is for users.

Many more proverbs possible, but they must be short, poetic, general, about Go more than about programming. Contradictory is OK. Life and programming are full of contradictions.

Greg Osuri made Go proverbs illustrated.

Posted in golang, workday | Leave a comment

go: printing struct & array

Printing struct https://play.golang.org/p/BvMIqF3Pmc9

package main

import "fmt"

type point struct {
    x, y int
}

func main() {
    p := point{1, 2}
    fmt.Println("Printing struct point:")
    fmt.Printf(" type          %%T: %T\n", p)
    fmt.Printf(" just values   %%v: %v\n", p)
    fmt.Printf(" +field names %%+v: %+v\n", p)
    fmt.Printf(" go syntax    %%#v: %#v\n", p)
    fmt.Println()

    ptr := &p
    fmt.Println("Printing pointer to struct point:")
    fmt.Printf(" type          %%T: %T\n", ptr)
    fmt.Printf(" just values   %%v: %v\n", ptr)
    fmt.Printf(" +field names %%+v: %+v\n", ptr)
    fmt.Printf(" go syntax    %%#v: %#v\n", ptr)
    fmt.Println()

    arrP := []point{point{1, 2},point{3, 4}}
    fmt.Println("Printing array of struct points:")
    fmt.Printf(" type          %%T: %T\n", arrP)
    fmt.Printf(" just values   %%v: %v\n", arrP)
    fmt.Printf(" +field names %%+v: %+v\n", arrP)
    fmt.Printf(" go syntax    %%#v: %#v\n", arrP)
}

Output:

Printing struct point:
 type          %T: main.point
 just values   %v: {1 2}
 +field names %+v: {x:1 y:2}
 go syntax    %#v: main.point{x:1, y:2}

Printing pointer to struct point:
 type          %T: *main.point
 just values   %v: &{1 2}
 +field names %+v: &{x:1 y:2}
 go syntax    %#v: &main.point{x:1, y:2}

Printing array of struct points:
 type          %T: []main.point
 just values   %v: [{1 2} {3 4}]
 +field names %+v: [{x:1 y:2} {x:3 y:4}]
 go syntax    %#v: []main.point{main.point{x:1, y:2}, main.point{x:3, y:4}}
Posted in golang, workday | Leave a comment

go: add elements to array

Here is one way, how to add elements to array in go language, see https://play.golang.org/p/nCLX23ymRUM

package main

import (
	"fmt"
)

type MyRecord struct {
	Name  string
	Phone string
}

var recA = MyRecord{Name: "Anna", Phone: "123"}
var recB = MyRecord{Name: "Bob", Phone: "456"}

type Records []MyRecord

func buildAppendedArrayPtr() {
	arr := make(Records, 0)
	arrPtr := &arr
	arrPtr = appendToArrayPtr(arrPtr, recA)
	arrPtr = appendToArrayPtr(arrPtr, recB)

	fmt.Printf("%v %T %d \n", arrPtr, arrPtr, len(*arrPtr))

	for i, rec := range *arrPtr {
		fmt.Printf("%d. %v\n", i, rec)
	}
}

func appendToArrayPtr(recordsPtr *Records, myRecord MyRecord) *Records {
	arr := append(*recordsPtr, myRecord)
	return &arr
}

func main() {
	buildAppendedArrayPtr()
}

Posted in golang, workday | Leave a comment

GIMP: first script-fu

GIMP is great tool for images manipulation. Even better is to automate as much as possible through scripts.
Lets say we would create file named my-first.scm and this file will be placed into sub-directory scripts. Location would depend on the operation system.
Here is example from Windows 10:
C:\Users\JoeDoe\AppData\Roaming\GIMP\2.10\scripts\my-first.scm

File could have content:

(define (ten) (+ 5 5))
(define (square x) (* x x))

In GIMP, scripts have to be refreshed: Filters/Scripts-Fu/Refresh scripts
Then we can open console Filters/Script-Fu/Console and in command line write command:
(ten)
We should see output 10.
(square 5)
We should see output 25.

At https://stackoverflow.com/questions/5811378/how-do-i-write-a-custom-auto-crop-script-using-the-gimp has been published very useful Edger Script. If you would copy and paste it into file, let’s say C:\Users\JoeDoe\AppData\Roaming\GIMP\2.10\scripts\my-edger.scm and then refresh scripts. Script takes arguments input-file, output file, top, right, bottom, left. Example executing it from the console is below:

(script-fu-wirebear-edger "I:\\Pictures\\IMG-000.png" "I:\\Pictures\\Edged-IMG-000.png" 10 20 30 40)
Posted in workday | Leave a comment

base64

Base64 encoding is widely used and there are nice online tools, for example https://www.base64decode.org/.

On command line could be convenient choice to use openssl with argument base64 to encode or two arguments base64 -d to decode. Tool reads from stdin, or from file with argument -in and writes to stdout or to the file with arguments -out .

echo Blog | openssl base64
QmxvZwo=
echo AB | openssl base64
QUIK
echo QUIK | openssl base64 -d
AB
Posted in workday | Leave a comment

go: interface example

Go is fresh fast relatively new language. One of the key to utilize it’s power are interfaces. Here is example of the geometry interfaces. See https://play.golang.org/p/nQ_ylb2jXKS

package main

import (
	"fmt"
	"math"
)

//https://www.mathsisfun.com/area.html

type geometry interface {
	area() float64
	perimeter() float64
}

type square struct {
	side float64
}
type rectangle struct {
	width, height float64
}
type triangle struct {
	a, b, c float64
}
type circle struct {
	radius float64
}

func (s square) area() float64 {
	return s.side * s.side
}
func (s square) perimeter() float64 {
	return 4 * s.side
}
func (r rectangle) area() float64 {
	return r.width * r.height
}
func (r rectangle) perimeter() float64 {
	return 2*r.width + 2*r.height
}
func (t triangle) area() float64 {
	cosGama := (t.c*t.c - t.a*t.a - t.b*t.b) / (2 * t.a * t.b)
	if math.Abs(cosGama) > 1.0 {
		fmt.Println("Input values are not for triangle")
		return -1
	}
	sinGama := math.Sqrt(1.0 - cosGama*cosGama)
	heightA := t.b * sinGama
	// fmt.Printf("triangle:  cos=%f, sin=%f,hA=%f\n",cosGama,sinGama,heightA)
	return t.a * heightA
}
func (t triangle) perimeter() float64 {
	return t.a + t.b + t.c
}
func (c circle) area() float64 {
	return math.Pi * c.radius * c.radius
}
func (c circle) perimeter() float64 {
	return 2 * math.Pi * c.radius
}
func measure(g geometry) {
	fmt.Println(g)
	fmt.Printf("area     : %f \n", g.area())
	fmt.Printf("perimeter: %f \n", g.perimeter())
}
func main() {
	s := square{side: 2}
	r := rectangle{width: 3, height: 4}
	t1 := triangle{a: 3, b: 4, c: 5}
	t2 := triangle{a: 1, b: 1, c: 1}
	t3 := triangle{a: 1, b: 1, c: 30}
	c := circle{radius: 5}
	
	measure(s)
	measure(r)
	measure(t1)
	measure(t2)
	measure(t3)
	measure(c)
}

Posted in golang, workday | Leave a comment

HTTPS Tomcat

Here are some notes from install and run HTTPS Tomcat on digitalocean inpired by Mavi’s blog.

on digitalocean:
Ubuntu 18.04 x64
Memory:1GB, vCPU:1, SSD_Disk:25GB, Transfer:1TB, price:$5/mo
Hostname:ubuntu18
IP:1.2.3.4

on my DNS provider web:
Edit DNS A records for example.com and www.example.com

ssh session to example.com, user root

# snap install docker
2018-08-29T15:33:20Z INFO Waiting for restart...
docker 17.06.2-ce from 'docker-inc' installed

#snap info certbot
#snap install --edge certbot

#apt-get update
#apt-get install software-properties-common
#add-apt-repository ppa:certbot/certbot
#apt-get update
#apt-get install certbot 
.
.
.Setting up certbot (0.26.1-1+ubuntu18.04.1+certbot+2) ...
Created symlink /etc/systemd/system/timers.target.wants/certbot.timer → /lib/systemd/system/certbot.timer.
certbot.service is a disabled or a static unit, not starting it.

#certbot certonly
...I choosed 1. spin up a temporary webserver (standalone)


#apt install docker-compose


#cd /root/app
#docker-compose up

and, yes, I see Tomcat at https://example.com

Posted in workday | Leave a comment