Skip to content

Instantly share code, notes, and snippets.

@jn0
jn0 / int2str.py
Last active September 15, 2020 07:35
integer to string at arbitrary (2..36) base
import string
def signum(n):
return int(n / abs(n)) if n else 0
def i2s(n, b=10, d=string.digits+string.ascii_lowercase):
assert 2 <= b <= len(d)
return d[0] if n == 0 else ('-' + i2s(abs(n), b, d)) if n < 0 else (i2s(n//b, b, d) + d[n % b]).lstrip(d[0])
@jn0
jn0 / git-cat.sh
Created June 18, 2020 08:22
extract a file (with repo relative path) from a git repo to stdout
#!/bin/bash
[ -n "$2" ] || { echo "$0 <repo-url> <repo-path-file>">&2; exit 1; }
repo="$1"
dirn=$(dirname "$2")
[ "$dirn" = . ] && dirn=''
fnam=$(basename "$2")
exec git archive --remote="${repo}" HEAD:"${dirn}" -- "${fnam}" | tar xO
@jn0
jn0 / sdsocket.go
Created December 17, 2019 15:13
Draft for handling socket-activated systemd's units
package main
import (
"fmt"
"os"
"strconv"
"strings"
"syscall"
)
@jn0
jn0 / go-spaces.go
Created December 17, 2019 12:06
Handling spaces in strings
package spaces
import "regexp"
import "strings"
var spaces_re = regexp.MustCompile(`\s+`) // *any* space
const sp = " " // *the* space
// Replace *any* sequence of white-space chars with single vanilla space ('\x20')
func Strip(s string) string { return strings.TrimSpace(spaces_re.ReplaceAllString(s, sp)) }
@jn0
jn0 / netrc.go
Created December 10, 2019 13:49
sorta replacement for cmd/go/internal/auth
package main
import (
"os"
"path"
"io/ioutil"
"strings"
)
import "net/http"
@jn0
jn0 / Makefile
Created December 9, 2019 12:29
How to serialize a Go project
# Idea from https://stackoverflow.com/questions/11354518/
COMMIT := $(shell git log | grep -wm1 commit | cut -d' ' -f2)
GITTAG := $(shell git tag -n | tail -n1 | cut -d ' ' -f1)
BDATE := $(shell date -u '+%FT%T%z')
GOFILES := $(wildcard *.go)
GO_LD_FLAGS := -ldflags "-X main.commit=$(COMMIT) -X main.version=$(GITTAG) -X main.built=$(BDATE)"
@jn0
jn0 / file_http_upload.go
Last active December 3, 2019 07:55
Using HTTP POST form to upload files
package main
import (
"fmt"
"time"
"bytes"
"net/http"
"mime/multipart"
"io"
"os"
@jn0
jn0 / utils.go
Created December 3, 2019 07:52
Assorted functions (FS object existense, error assertion)
package main
import (
"os"
)
func assert(e error, message string, args ...interface{}) {
if e != nil {
args = append(args, e)
log.Fatal(message + ": %v", args...)
@jn0
jn0 / log.go
Created December 3, 2019 07:49
Mimic python's logging in go
package main
import logging "log"
import "fmt"
import "strings"
type LogLevel int
const (
FATAL = LogLevel(0) + iota
@jn0
jn0 / sdnotify.go
Created December 3, 2019 07:46
Implement the sd_notify protocol to talk to systemd (Type=notify)
package main
// https://github.com/coreos/go-systemd/blob/master/daemon/sdnotify.go
import (
"net"
"os"
"fmt"
)
const (