package backoff

import (
	"math"
	"time"
)

type ExponentialBackoff struct {
	RandomizationFactor float64
	Retries             int
	MaxRetries          int
	Delay               time.Duration
	Interval            time.Duration
}

func Exponential() *ExponentialBackoff {
	return &ExponentialBackoff{
		RandomizationFactor: 0.5,
		Retries:             0,
		MaxRetries:          5,
		Delay:               time.Duration(0),
		Interval:            time.Duration(1 * time.Second),
	}
}

func (self *ExponentialBackoff) Next() bool {
	self.Retries++

	if self.Retries >= self.MaxRetries {
		return false
	}

	self.Delay = time.Duration(math.Pow(2, float64(self.Retries))-1) * self.Interval

	return true
}

func (self *ExponentialBackoff) Retry(f func() error) error {
	err := f()

	if err == nil {
		return nil
	}

	for self.Next() {
		if err = f(); err == nil {
			return nil
		}

		time.Sleep(self.Delay)
	}

	return err
}

func (self *ExponentialBackoff) Reset() {
	self.Retries = 0
	self.Delay = time.Duration(0 * time.Second)
}

package backoff

import (
	"math"
	"time"
)

type ExponentialBackoff struct {
	Retries             int
	MaxRetries          int
	Delay               time.Duration
	Interval            time.Duration
}

func Exponential() *ExponentialBackoff {
	return &ExponentialBackoff{
		Retries:             0,
		MaxRetries:          5,
		Delay:               time.Duration(0),
		Interval:            time.Duration(1 * time.Second),
	}
}

func (self *ExponentialBackoff) Next() bool {
	self.Retries++

	if self.Retries >= self.MaxRetries {
		return false
	}

	self.Delay = time.Duration(math.Pow(2, float64(self.Retries))-1) * self.Interval

	return true
}

func (self *ExponentialBackoff) Retry(f func() error) error {
	err := f()

	if err == nil {
		return nil
	}

	for self.Next() {
		if err = f(); err == nil {
			return nil
		}

		time.Sleep(self.Delay)
	}

	return err
}

func (self *ExponentialBackoff) Reset() {
	self.Retries = 0
	self.Delay = time.Duration(0 * time.Second)
}

Make algorithms use uniform distribution of backoff times.


package main

import (
	"flag"
	"image"
	"log"
	"os"

	"github.com/pixiv/go-libjpeg/jpeg"
)

func main() {
	flag.Parse()
	file := flag.Arg(0)

	io, err := os.Open(file)
	if err != nil {
		log.Fatalln("Can't open file: ", file)
	}

	img, err := jpeg.Decode(io, &jpeg.DecoderOptions{})
	if img == nil {
		log.Fatalln("Got nil")
	}
	if err != nil {
		log.Fatalln("Got Error: %v", err)
	}

	//
	// write your code here ...
	//

	switch img.(type) {
	case *image.YCbCr:
		log.Println("decoded YCbCr")
	case *image.Gray:
		log.Println("decoded Gray")
	default:
		log.Println("unknown format")
	}
}

package main

import (
	"flag"
	"image"
	"log"
	"os"

	"github.com/pixiv/go-libjpeg/jpeg"
)

func main() {
	flag.Parse()
	file := flag.Arg(0)

	io, err := os.Open(file)
	if err != nil {
		log.Fatalln("Can't open file: ", file)
	}

	img, err := jpeg.Decode(io, &jpeg.DecoderOptions{})
	if img == nil {
		log.Fatalln("Got nil")
	}
	if err != nil {
		log.Fatalf("Got Error: %v", err)
	}

	//
	// write your code here ...
	//

	switch img.(type) {
	case *image.YCbCr:
		log.Println("decoded YCbCr")
	case *image.Gray:
		log.Println("decoded Gray")
	default:
		log.Println("unknown format")
	}
}

Fix Travis errors on recent Go


package main

import (
  "os"
  "io/ioutil"
  "github.com/hashicorp/hcl/json/parser"
  "github.com/hashicorp/hcl/hcl/printer"
)

func main() {
  input, _ := ioutil.ReadAll(os.Stdin)

  ast, err := parser.Parse([]byte(input))
  if err != nil {
    panic(err)
  }

  err = printer.Fprint(os.Stdout, ast)
  if err != nil {
    panic(err)
  }
}

package main

import (
  "os"
  "io/ioutil"
  "github.com/Acconut/hcl/json/parser"
  "github.com/Acconut/hcl/hcl/printer"
)

func main() {
  input, _ := ioutil.ReadAll(os.Stdin)

  ast, err := parser.Parse([]byte(input))
  if err != nil {
    panic(err)
  }

  err = printer.Fprint(os.Stdout, ast)
  if err != nil {
    panic(err)
  }
}

Switch to @Acconut's HCL fork


package main

import (
	"fmt"
	"github.com/Financial-Times/service-status-go/buildinfo"
)

func main() {
	fmt.Printf("Build info is %+v", buildinfo.GetBuildInfo)
}

package main

import (
	"fmt"
	"github.com/Financial-Times/service-status-go/buildinfo"
)

func main() {
	info := buildinfo.GetBuildInfo()
	fmt.Printf("Build info is %v+", info)
}

Print info as an example


package main

import (
	"fmt"
	"os"
	"os/user"
	"path"
	"strconv"
	"strings"
	"syscall"
)

func checkError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(111)
	}
}

func main() {

	username := os.Args[1]
	program := os.Args[2]
	pargv := os.Args[2:]

	user, err := user.Lookup(username)
	checkError(err)

	uid, err := strconv.Atoi(user.Uid)
	checkError(err)
	gid, err := strconv.Atoi(user.Gid)
	checkError(err)

	err = syscall.Setgid(gid)
	checkError(err)
	err = syscall.Setuid(uid)
	checkError(err)

	if path.IsAbs(program) {
		err := syscall.Exec(program, pargv, os.Environ())
		checkError(err)
	}

	for _, p := range strings.Split(os.Getenv("PATH"), ":") {
		absPath := path.Join(p, program)
		err = syscall.Exec(absPath, pargv, os.Environ())
	}

	checkError(err)
}

package main

import (
	"fmt"
	"os"
	"os/user"
	"path"
	"strconv"
	"strings"
	"syscall"
)

var usage string = "setuidgid: usage: setuidgid username program [arg...]"

func checkError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(111)
	}
}

func main() {

	if len(os.Args) <= 2 {
		fmt.Print(usage)
		os.Exit(100)
	}

	username := os.Args[1]
	program := os.Args[2]
	pargv := os.Args[2:]

	user, err := user.Lookup(username)
	checkError(err)

	uid, err := strconv.Atoi(user.Uid)
	checkError(err)
	gid, err := strconv.Atoi(user.Gid)
	checkError(err)

	err = syscall.Setgid(gid)
	checkError(err)
	err = syscall.Setuid(uid)
	checkError(err)

	if path.IsAbs(program) {
		err := syscall.Exec(program, pargv, os.Environ())
		checkError(err)
	}

	for _, p := range strings.Split(os.Getenv("PATH"), ":") {
		absPath := path.Join(p, program)
		err = syscall.Exec(absPath, pargv, os.Environ())
	}

	checkError(err)
}

Print usage when incorrect parameters passed


/*
http://www.apache.org/licenses/LICENSE-2.0.txt

Copyright 2015 Intel Coporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"os"

	// Import the pulse plugin library
	"github.com/intelsdi-x/pulse/control/plugin"
	"github.com/intelsdi-x/pulse/plugin/publisher/pulse-publisher-rabbitmq/rmq"
)

func main() {
	// Three things provided:
	//   the definition of the plugin metadata
	//   the implementation satfiying plugin.CollectorPlugin
	//   the collector configuration policy satifying plugin.ConfigRules

	// Define metadata about Plugin
	meta := rmq.Meta()

	// Start a collector
	plugin.Start(meta, rmq.NewRmqPublisher(), os.Args[1])
}

/*
http://www.apache.org/licenses/LICENSE-2.0.txt

Copyright 2015 Intel Coporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"os"

	// Import the pulse plugin library
	"github.com/intelsdi-x/pulse-plugin-publisher-rabbitmq/rmq"
	"github.com/intelsdi-x/pulse/control/plugin"
)

func main() {
	// Three things provided:
	//   the definition of the plugin metadata
	//   the implementation satfiying plugin.CollectorPlugin
	//   the collector configuration policy satifying plugin.ConfigRules

	// Define metadata about Plugin
	meta := rmq.Meta()

	// Start a collector
	plugin.Start(meta, rmq.NewRmqPublisher(), os.Args[1])
}

Update import for rmq package


package threedo

import (
	"github.com/codegangsta/negroni"
	"log"
	"os"
)

func NewLogger() *negroni.Logger {
	return &negroni.Logger{
		log.New(os.Stdout, "[http] ", log.LstdFlags),
	}
}

package threedo

import (
	"github.com/codegangsta/negroni"
	"github.com/go-kit/kit/log"
	"net/http"
	"os"
	"time"
)

type Logger struct {
	log.Logger
}

func NewLogger() *Logger {
	return &Logger{log.NewLogfmtLogger(os.Stderr)}
}

func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	start := time.Now()

	next(rw, r)

	res := rw.(negroni.ResponseWriter)
	l.Log(
		"action", "request",
		"method", r.Method,
		"path", r.URL.Path,
		"status", res.Status(),
		"time", time.Since(start),
	)
}

Use go-kit/log instead of the std log package


package imgbase64

import (
	"testing"
)

func TestEncode(t *testing.T) {
	const in, out = "Hello, World!", "SGVsbG8sIFdvcmxkIQ=="
	if x := encode([]byte(in)); string(x) != out {
		t.Errorf("Encode(%v) = %s, want %v", in, x, out)
	}
}

func TestDefaultImage(t *testing.T) {
	const expected = "https://www.github.com/"

	SetDefaultImage(expected)
	if actual := DefaultImage(); actual != expected {
		t.Errorf("SetDefaultImage(%v) = %v, want %v", expected, actual, expected)
	}
}

func TestCleanUrl(t *testing.T) {
	const in, out = "Hello, World!", "Hello,%20World!"

	if x := cleanUrl(in); x != out {
		t.Errorf("CleanUrl(%v) = %v, want %v", in, x, out)
	}
}

/**
 * Check if the failover succeeds
 */
func TestDefaultFailOver(t *testing.T) {
	const in, out = "https://github.com/polds/imgbase64.png", ""
	if x := NewImage(in); x != out {
		t.Errorf("NewImage(%v) = %v, want %v", in, x, out)
	}
}

package imgbase64

import (
	"testing"
)

func TestEncode(t *testing.T) {
	const in, out = "Hello, World!", "SGVsbG8sIFdvcmxkIQ=="
	if x := encode([]byte(in)); string(x) != out {
		t.Errorf("Encode(%v) = %s, want %v", in, x, out)
	}
}

func TestDefaultImage(t *testing.T) {
	const expected = "https://www.github.com/"

	SetDefaultImage(expected)
	if actual := DefaultImage(); actual != expected {
		t.Errorf("SetDefaultImage(%v) = %v, want %v", expected, actual, expected)
	}
}

func TestCleanUrl(t *testing.T) {
	const in, out = "Hello, World!", "Hello,%20World!"

	if x := cleanUrl(in); x != out {
		t.Errorf("CleanUrl(%v) = %v, want %v", in, x, out)
	}
}

// Check if the failover succeeds
/*func TestDefaultFailOver(t *testing.T) {
	const in, out = "https://github.com/polds/imgbase64.png", ""
	if x := NewImage(in); x != out {
		t.Errorf("NewImage(%v) = %v, want %v", in, x, out)
	}
}*/

Disable DefaultFailOver Test for the moment till todo 1 is complete


package batchgcd

import (
	"fmt"
	"github.com/ncw/gmp"
)

type Collision struct {
	Modulus *gmp.Int
	P       *gmp.Int
	Q       *gmp.Int
}

func (x Collision) HavePrivate() bool {
	return x.P != nil || x.Q != nil
}

func (x Collision) String() string {
	if x.HavePrivate() {
		if x.P.Cmp(x.Q) < 0 {
			return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.P, x.Q)
		} else {
			return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.Q, x.P)
		}
	} else {
		return fmt.Sprintf("DUPLICATE: %x", x.Modulus)
	}
}

func (x Collision) Test() bool {
	if !x.HavePrivate() {
		return true
	}
	n := gmp.NewInt(0)
	n.Mul(x.P, x.Q)
	return n.Cmp(x.Modulus) == 0
}

func (x Collision) Csv() string {
	if x.P.Cmp(x.Q) < 0 {
		return fmt.Sprintf("%x,%x,%x", x.Modulus, x.P, x.Q)
	} else {
		return fmt.Sprintf("%x,%x,%x", x.Modulus, x.Q, x.P)
	}
}

Add support for CSV output


package main

import (
	"fmt"
)

const (
	MaxRedirects = 10
)

func main() {
	redirects := ReadCsv("301s.csv")

	log := make([]redirectResult, 0)

	for _, info := range redirects {
		result := CheckUrl(info)
		log = append(log, result)
	}

	for _, logItem := range log {

		if logItem.FinalUrl == logItem.ExpectedUrl {
			fmt.Printf("OK: %v Matched\n", logItem.Url)
			continue
		}

		if logItem.LooksLikeRedirectLoop() {
			fmt.Printf("LOOP: %v Redirect Loop? Stopped after %v redirects\n", logItem.Url, logItem.Redirects)
			continue
		}

		fmt.Printf("ERR: %v Unexpected destination: %v\n", logItem.Url, logItem.FinalUrl)
	}
}

package main

import (
	"fmt"
	"flag"
)

const (
	MaxRedirects = 10
)

func main() {
	flag.Parse()

	filename := flag.Arg(0)

	if filename == "" {
		filename = "301s.csv"
	}

	redirects := ReadCsv(filename)

	log := make([]redirectResult, 0)

	for _, info := range redirects {
		result := CheckUrl(info)
		log = append(log, result)
	}

	for _, logItem := range log {

		if logItem.FinalUrl == logItem.ExpectedUrl {
			fmt.Printf("OK: %v Matched\n", logItem.Url)
			continue
		}

		if logItem.LooksLikeRedirectLoop() {
			fmt.Printf("LOOP: %v Redirect Loop? Stopped after %v redirects\n", logItem.Url, logItem.Redirects)
			continue
		}

		fmt.Printf("ERR: %v Unexpected destination: %v\n", logItem.Url, logItem.FinalUrl)
	}
}

Add argument parsing to customize input file


package main

import (
	"flag"
	"fmt"
	"log"
	"os/exec"
)

func init() {
	flag.Parse()
}

func main() {
	command := flag.Args()
	bin, args := command[0], command[1:]

	cmd := exec.Command(bin, args...)

	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Print(string(output))
}

package main

import (
	"crypto/md5"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"time"

	"github.com/justincampbell/cacheout/cache"
)

func init() {
	flag.Parse()
}

func main() {
	command := flag.Args()
	key := hashCommand(command)
	ttlArg, bin, args := command[0], command[1], command[2:]

	ttl, err := time.ParseDuration(ttlArg)
	if err != nil {
		log.Fatal(err)
	}

	fc := cache.NewFileCache(key, &ttl)

	if fc.Stale() {
		cmd := exec.Command(bin, args...)

		output, err := cmd.CombinedOutput()
		if err != nil {
			log.Fatal(err)
		}

		_, err = os.Stdout.Write(output)
		if err != nil {
			log.Fatal(err)
		}

		fc.Write(output)
		fc.Persist()
	} else {
		_, err = os.Stdout.Write(fc.Bytes())
		if err != nil {
			log.Fatal(err)
		}
	}
}

func hashCommand(command []string) string {
	h := md5.New()

	for _, part := range command {
		io.WriteString(h, part)
	}

	return fmt.Sprintf("%x", h.Sum(nil))
}

Use cache/file in proof of concept


package g

import (
	"time"
)

// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口；收集udp流量数据；du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugin mechanism
// 5.1.6: Update cfg.json in release package. Program file is same as 5.1.5.
const (
	VERSION          = "5.1.6"
	COLLECT_INTERVAL = time.Second
	URL_CHECK_HEALTH = "url.check.health"
	NET_PORT_LISTEN  = "net.port.listen"
	DU_BS            = "du.bs"
	PROC_NUM         = "proc.num"
)

package g

import (
	"time"
)

// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口；收集udp流量数据；du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugin mechanism
// 5.1.6: Update cfg.json in release package. Program file is same as 5.1.5.
// 5.1.7: Fix failure of plugin updating.
const (
	VERSION          = "5.1.7"
	COLLECT_INTERVAL = time.Second
	URL_CHECK_HEALTH = "url.check.health"
	NET_PORT_LISTEN  = "net.port.listen"
	DU_BS            = "du.bs"
	PROC_NUM         = "proc.num"
)

Update agent version to 5.1.7


package builder

import (
	"fmt"
	"strings"

	"github.com/openshift/origin/pkg/build/api"
)

type Builder interface {
	Build() error
}

// imageTag returns the tag to be used for the build. If a registry has been
// specified, it will prepend the registry to the name
func imageTag(build *api.Build) string {
	tag := build.Parameters.Output.ImageTag
	if !strings.HasPrefix(tag, build.Parameters.Output.Registry) {
		tag = fmt.Sprintf("%s/%s", build.Parameters.Output.Registry, tag)
	}
	return tag
}

// getBuildEnvVars returns a map with the environment variables that should be added
// to the built image
func getBuildEnvVars(build *api.Build) map[string]string {
	envVars := map[string]string{
		"OPENSHIFT_BUILD_NAME":   build.Name,
		"OPENSHIFT_BUILD_SOURCE": build.Parameters.Source.Git.URI,
	}
	if build.Parameters.Source.Git.Ref != "" {
		envVars["OPENSHIFT_BUILD_REFERENCE"] = build.Parameters.Source.Git.Ref
	}
	if build.Parameters.Revision != nil &&
		build.Parameters.Revision.Git != nil &&
		build.Parameters.Revision.Git.Commit != "" {
		envVars["OPENSHIFT_BUILD_COMMIT"] = build.Parameters.Revision.Git.Commit
	}
	return envVars
}

package builder

import (
	"fmt"
	"strings"

	"github.com/openshift/origin/pkg/build/api"
)

type Builder interface {
	Build() error
}

// imageTag returns the tag to be used for the build. If a registry has been
// specified, it will prepend the registry to the name
func imageTag(build *api.Build) string {
	tag := build.Parameters.Output.ImageTag
	if !strings.HasPrefix(tag, build.Parameters.Output.Registry) {
		tag = fmt.Sprintf("%s/%s", build.Parameters.Output.Registry, tag)
	}
	return tag
}

// getBuildEnvVars returns a map with the environment variables that should be added
// to the built image
func getBuildEnvVars(build *api.Build) map[string]string {
	envVars := map[string]string{
		"OPENSHIFT_BUILD_NAME":      build.Name,
		"OPENSHIFT_BUILD_NAMESPACE": build.Namespace,
		"OPENSHIFT_BUILD_SOURCE":    build.Parameters.Source.Git.URI,
	}
	if build.Parameters.Source.Git.Ref != "" {
		envVars["OPENSHIFT_BUILD_REFERENCE"] = build.Parameters.Source.Git.Ref
	}
	if build.Parameters.Revision != nil &&
		build.Parameters.Revision.Git != nil &&
		build.Parameters.Revision.Git.Commit != "" {
		envVars["OPENSHIFT_BUILD_COMMIT"] = build.Parameters.Revision.Git.Commit
	}
	return envVars
}

Add build namespace to built image environment


package certmon

const (
	CertTypeSSH  = 0
	CertTypeX509 = 1
)

// Format of certificate notifications (server -> client):
// certType:   32 bit uint (big-endian)
// certLength: 64 bit uint (big-endian)
// certData:   sequence of bytes

// Client sends no data.

package certmon

const (
	ConnectString = "200 Connected to keymaster certmon service"
	HttpPath      = "/certmon"

	CertTypeSSH  = 0
	CertTypeX509 = 1
)

// Format of certificate notifications (server -> client):
// certType:   32 bit uint (big-endian)
// certLength: 64 bit uint (big-endian)
// certData:   sequence of bytes

// Client sends no data.

Add ConnectString and HttpPath constants to proto/certmon package.


package main

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/guregu/kami"
	"golang.org/x/net/context"
)

func main() {
	kami.Get("/contacts/", getContacts)
	kami.Serve()
}

func getContacts(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	page, err := strconv.Atoi(r.FormValue("page"))
	if err != nil {
		page = 1
	}

	perPage, err := strconv.Atoi(r.FormValue("perPage"))
	if err != nil {
		perPage = 100
	}

	json.NewEncoder(w).Encode(
		NewContactQuery(page, perPage).All())
}

package main

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/guregu/kami"
	"golang.org/x/net/context"
)

func main() {
	kami.Get("/contacts/", getContacts)
	kami.Serve()
}

func getContacts(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	page, err := strconv.Atoi(r.FormValue("page"))
	if err != nil {
		page = 1
	}

	perPage, err := strconv.Atoi(r.FormValue("per_page"))
	if err != nil {
		perPage = 100
	}

	json.NewEncoder(w).Encode(
		NewContactQuery(page, perPage).All())
}

Change perPage to per_page for /contacts query params


package main

import sp "github.com/scipipe/scipipe"

const (
	workDir = "/scipipe-data/"
)

func main() {
	prun := sp.NewPipelineRunner()

	peakPicker := sp.NewFromShell("PeakPicker", "PeakPickerHiRes -in {i:sample} -out {o:out} -ini {p:ini}")
	peakPicker.PathFormatters["out"] = func(t *sp.SciTask) string {
		//         filename = basename("{0}_{2}.{1}".format(*self.sampleFile.rsplit('.', 1) + ["peaks"]))
		//         return luigi.LocalTarget("results/"+filename)
		return "todo_implement_path_formatting.txt"
	}

	prun.AddProcess(peakPicker)

	prun.Run()
}

package main

import (
	str "strings"

	sp "github.com/scipipe/scipipe"
)

const (
	workDir = "/scipipe-data/"
)

func main() {
	prun := sp.NewPipelineRunner()

	peakPicker := sp.NewFromShell("PeakPicker", "PeakPickerHiRes -in {i:sample} -out {o:out} -ini {p:ini}")
	peakPicker.PathFormatters["out"] = func(t *sp.SciTask) string {
		parts := str.Split(t.GetInPath("sample"), ".")
		outPath := "results/" + str.Join(parts[:len(parts)-1], "_") + ".peaks"
		return outPath
	}

	prun.AddProcess(peakPicker)

	prun.Run()
}

Improve path formatting in k8s openms example


// $G $D/$F.go && $L $F.$A && (! ./$A.out || echo BUG: should not succeed)

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
type I interface { };
func foo1(i int) int { return i }
func foo2(i int32) int32 { return i }
func main() {
  var i I;
  i = 1;
  var v1 int = i;
  if foo1(v1) != 1 { panicln(1) }
  var v2 int32 = i.(int).(int32);
  if foo1(v2) != 1 { panicln(2) }
  var v3 int32 = i; // This implicit type conversion should fail at runtime.
  if foo1(v3) != 1 { panicln(3) }
}

// $G $D/$F.go && $L $F.$A && (! ./$A.out || echo BUG: should not succeed)

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main
type I interface { };
func foo1(i int) int { return i }
func foo2(i int32) int32 { return i }
func main() {
  var i I;
  i = 1;
  var v1 int = i;
  if foo1(v1) != 1 { panicln(1) }
  var v2 int32 = i.(int).(int32);
  if foo2(v2) != 1 { panicln(2) }
  var v3 int32 = i; // This implicit type conversion should fail at runtime.
  if foo2(v3) != 1 { panicln(3) }
}

Call the right function for int32 values.


package channels

// BlackHole implements the InChannel interface and provides an analogue for the "Discard" variable in
// the ioutil package - it never blocks, and simply discards every value it reads. The number of items
// discarded in this way is counted and returned from Len.
type BlackHole struct {
	input   chan interface{}
	stopper chan struct{}
	count   int
}

func NewBlackHole() *BlackHole {
	ch := &BlackHole{make(chan interface{}), make(chan struct{}), 0}
	go ch.discard()
	return ch
}

func (ch *BlackHole) In() chan<- interface{} {
	return ch.input
}

func (ch *BlackHole) Len() int {
	return ch.count
}

func (ch *BlackHole) Cap() BufferCap {
	return Infinity
}

func (ch *BlackHole) Close() {
	close(ch.input)
	<-ch.stopper
}

func (ch *BlackHole) discard() {
	for _ = range ch.input {
		ch.count++
	}
	close(ch.stopper)
}

package channels

// BlackHole implements the InChannel interface and provides an analogue for the "Discard" variable in
// the ioutil package - it never blocks, and simply discards every value it reads. The number of items
// discarded in this way is counted and returned from Len.
type BlackHole struct {
	input  chan interface{}
	length chan int
	count  int
}

func NewBlackHole() *BlackHole {
	ch := &BlackHole{
		input:  make(chan interface{}),
		length: make(chan int),
	}
	go ch.discard()
	return ch
}

func (ch *BlackHole) In() chan<- interface{} {
	return ch.input
}

func (ch *BlackHole) Len() int {
	val, open := <-ch.length
	if open {
		return val
	} else {
		return ch.count
	}
}

func (ch *BlackHole) Cap() BufferCap {
	return Infinity
}

func (ch *BlackHole) Close() {
	close(ch.input)
}

func (ch *BlackHole) discard() {
	for {
		select {
		case _, open := <-ch.input:
			if !open {
				close(ch.length)
				return
			}
			ch.count++
		case ch.length <- ch.count:
		}
	}
}

Fix data race in BlackHole


package gondom

import (
	"math/rand"
)

const (
	_rawURLLetters = "abcdefghijklmnopqrstuvwxyz0123456789"
	_rawLetters    = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)

func Make(n int, seed int64) string {
	b := make([]byte, n)
	rand.Seed(seed)
	for i := range b {
		b[i] = _rawLetters[rand.Intn(62)]
	}
	return string(b)
}

func MakeURL(n int, seed int64) string {
	b := make([]byte, n)
	rand.Seed(seed)
	for i := range b {
		b[i] = _rawURLLetters[rand.Intn(36)]
	}
	return string(b)
}

package gondom

import (
	"math/rand"
)

const (
	_rawURLLetters = "abcdefghijklmnopqrstuvwxyz0123456789"
	_rawLetters    = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)

func Make(n int, seed int64) string {
	if n < 0 {
		n = n * -1
	}
	b := make([]byte, n)
	rand.Seed(seed)
	for i := range b {
		b[i] = _rawLetters[rand.Intn(62)]
	}
	return string(b)
}

func MakeURL(n int, seed int64) string {
	if n < 0 {
		n = n * -1
	}
	b := make([]byte, n)
	rand.Seed(seed)
	for i := range b {
		b[i] = _rawURLLetters[rand.Intn(36)]
	}
	return string(b)
}

Fix support for minus value


// doc-gen generates gke-deploy's help docs.
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/GoogleCloudPlatform/cloud-builders/gke-deploy/cmd"
	"github.com/spf13/cobra"
	"github.com/spf13/cobra/doc"
)

var dir string
var root = &cobra.Command{
	Use:   "gendoc",
	Short: "Generate gke-deploy's help docs",
	Args:  cobra.NoArgs,
	Run: func(*cobra.Command, []string) {
		if err := doc.GenMarkdownTree(cmd.NewCommand(), dir); err != nil {
			log.Fatalln(err)
		}
	},
}

func init() {
	root.Flags().StringVarP(&dir, "dir", "d", ".", "Path to directory in which to generate docs")
}

func main() {
	if err := root.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

Fix package comment in doc-gen.


package main

import (
	"fmt"
	"github.com/kidoman/embd"
	"bufio"
	"os"
	"strconv"
	"strings"
)

var blinker Blinker

func main() {
	var blinker Blinker
	err := embd.InitGPIO()
	if err != nil {
		blinker = new (MockBlinker)
	} else {
		blinker = new (GPIOBlinker)
	}
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter number: ")
	text, _ := reader.ReadString('\n')

	intValue, err := strconv.Atoi(strings.TrimRight(text, "\n"))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(intValue)
	fmt.Println(blinker.Blink(intValue))
}

type Blinker interface {
	Blink(number int) string
}

type MockBlinker struct {

}

type GPIOBlinker struct {

}

func(mb MockBlinker) Blink(number int) string {
	return fmt.Sprintf("Mock Blink (%v)", number)
}

func(b GPIOBlinker) Blink(number int) string {
	return fmt.Sprintf("Sending signal to GPIO pin %d", number);
}

package main

import (
	"fmt"
	"github.com/kidoman/embd"
	"bufio"
	"os"
	"strconv"
	"strings"
	"time"
)

var blinker Blinker

func output(c chan int) {
	seconds := <-c
	fmt.Printf("Outputting Hi for %d s\n", seconds)
	time.Sleep(time.Duration(seconds) * time.Second)
	fmt.Println("Finished outputting Hi")
}

func main() {
	var blinker Blinker
	c := make(chan int)
	go output(c)
	err := embd.InitGPIO()
	if err != nil {
		blinker = new (MockBlinker)
	} else {
		blinker = new (GPIOBlinker)
	}
	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Enter number: ")
		text, _ := reader.ReadString('\n')

		intValue, err := strconv.Atoi(strings.TrimRight(text, "\n"))
		if err != nil {
			fmt.Println(err)
		}
		//fmt.Println(intValue)
		c <- intValue
		fmt.Println(blinker.Blink(intValue))
	}
}

type Blinker interface {
	Blink(number int) string
}

type MockBlinker struct {

}

type GPIOBlinker struct {

}

func(mb MockBlinker) Blink(number int) string {
	return fmt.Sprintf("Mock Blink (%v)", number)
}

func(b GPIOBlinker) Blink(number int) string {
	return fmt.Sprintf("Sending signal to GPIO pin %d", number);
}

Send & read off a channel


package mail

import (
	"github.com/go-gomail/gomail"
	"github.com/skygeario/skygear-server/pkg/core/config"
)

func NewDialer(c config.SMTPConfiguration) *gomail.Dialer {
	if c.Host == "" {
		panic("mail server is not configured")
	}

	return gomail.NewPlainDialer(c.Host, c.Port, c.Login, c.Password)
}

package mail

import (
	"errors"

	"github.com/go-gomail/gomail"
	"github.com/skygeario/skygear-server/pkg/core/config"
)

func NewDialer(c config.SMTPConfiguration) *gomail.Dialer {
	if c.Host == "" {
		panic(errors.New("mail server is not configured"))
	}

	return gomail.NewPlainDialer(c.Host, c.Port, c.Login, c.Password)
}

Fix wrong error thrown for new smtp dailer


// Package profile is for specific profiles
package profile

// Local is a profile for local environments
func Local() []string {
	return []string{}
}

// Kubernetes is a profile for kubernetes
func Kubernetes() []string {
	return []string{}
}

// Platform is a platform profile
func Platform() []string {
	return []string{
		"MICRO_BROKER=service",
		"MICRO_REGISTRY=service",
		"MICRO_PROXY=go.micro.proxy",
		// expects k8s service name
		"MICRO_PROXY_ADDRESS=micro-proxy:8081",
	}
}

// Package profile is for specific profiles
package profile

// Local is a profile for local environments
func Local() []string {
	return []string{}
}

// Kubernetes is a profile for kubernetes
func Kubernetes() []string {
	return []string{}
}

// Platform is a platform profile
func Platform() []string {
	return []string{
		"MICRO_BROKER=service",
		"MICRO_REGISTRY=service",
		"MICRO_STORE=service",
		"MICRO_PROXY=go.micro.proxy",
		// expects k8s service name
		"MICRO_PROXY_ADDRESS=micro-proxy:8081",
	}
}

Add runtime service env var


// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package testing

import (
	"testing"

	gitjujutesting "github.com/juju/testing"
	jc "github.com/juju/testing/checkers"
	gc "gopkg.in/check.v1"
	"gopkg.in/mgo.v2"

	"github.com/juju/juju/mongo"
)

// MgoTestPackage should be called to register the tests for any package
// that requires a secure connection to a MongoDB server.
func MgoTestPackage(t *testing.T) {
	gitjujutesting.MgoTestPackage(t, Certs)
}

// NewServerReplSet returns a new mongo server instance to use in
// testing with replicaset. The caller is responsible for calling
// inst.Destroy() when done.
func NewServerReplSet(c *gc.C) *gitjujutesting.MgoInstance {
	inst := &gitjujutesting.MgoInstance{Params: []string{"--replSet", mongo.ReplicaSetName}}
	err := inst.Start(Certs)
	c.Assert(err, jc.ErrorIsNil)

	// Verify the server is up before returning.

	session, err := inst.DialDirect()
	if err != nil {
		inst.Destroy()
		c.Fatalf("error dialing mongo server: %v", err.Error())
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)
	if err = session.Ping(); err != nil {
		inst.Destroy()
		c.Fatalf("error pinging mongo server: %v", err.Error())
	}
	return inst
}

// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package testing

import (
	"testing"

	gitjujutesting "github.com/juju/testing"
)

// MgoTestPackage should be called to register the tests for any package
// that requires a secure connection to a MongoDB server.
func MgoTestPackage(t *testing.T) {
	gitjujutesting.MgoTestPackage(t, Certs)
}

Drop the NewServerReplSet testing helper.


// Copyright 2011 Julian Phillips.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package py

// #include "utils.h"
// static inline int stringCheck(PyObject *o) { return PyString_Check(o); }
import "C"

import (
	"os"
	"unsafe"
)

type String struct {
	BaseObject
}

func stringCheck(obj Object) bool {
	return C.stringCheck(c(obj)) != 0
}

func newString(obj *C.PyObject) *String {
	return (*String)(unsafe.Pointer(obj))
}

func String_FromString(s string) (*String, os.Error) {
	cs := C.CString(s)
	defer C.free(unsafe.Pointer(cs))
	ret := C.PyString_FromString(cs)
	if ret == nil {
		return nil, exception()
	}
	return newString(ret), nil
}

func (s *String) String() string {
	ret := C.PyString_AsString(c(s))
	if ret == nil {
		panic(exception())
	}
	return C.GoString(ret)
}

func (s *String) Format(args *Tuple) (*String, os.Error) {
	ret := C.PyString_Format(c(s), c(args))
	if ret == nil {
		return nil, exception()
	}
	return newString(ret), nil
}

Add Format method to String


package twofactor

import "github.com/volatiletech/authboss"

// Page constants
const (
	PageRecovery2FA  = "recovery2fa"
	PageVerify2FA    = "twofactor_verify"
	PageVerifyEnd2FA = "twofactor_verify_end"
)

// Email constants
const (
	EmailVerifyHTML = "twofactor_verify_email_html"
	EmailVerifyTxt  = "twofactor_verify_email_txt"
)

// Form value constants
const (
	FormValueToken = "token"
)

// Data constants
const (
	DataRecoveryCode     = "recovery_code"
	DataRecoveryCodes    = "recovery_codes"
	DataNumRecoveryCodes = "n_recovery_codes"
	DataVerifyEmail      = "email"
	DataVerifyURL        = "url"
)

const (
	alphabet             = "abcdefghijklmnopqrstuvwxyz0123456789"
	recoveryCodeLength   = 10
	verifyEmailTokenSize = 16
)

// User interface
type User interface {
	authboss.User

	GetEmail() string
	PutEmail(string)

	// GetRecoveryCodes retrieves a CSV string of bcrypt'd recovery codes
	GetRecoveryCodes() string
	// PutRecoveryCodes uses a single string to store many
	// bcrypt'd recovery codes
	PutRecoveryCodes(codes string)
}

package twofactor

import "github.com/volatiletech/authboss"

// Page constants
const (
	PageRecovery2FA  = "recovery2fa"
	PageVerify2FA    = "twofactor_verify"
	PageVerifyEnd2FA = "twofactor_verify_end"
)

// Email constants
const (
	EmailVerifyHTML = "twofactor_verify_email_html"
	EmailVerifyTxt  = "twofactor_verify_email_txt"
)

// Form value constants
const (
	FormValueToken = "token"
)

// Data constants
const (
	DataRecoveryCode     = "recovery_code"
	DataRecoveryCodes    = "recovery_codes"
	DataNumRecoveryCodes = "n_recovery_codes"
	DataVerifyEmail      = "email"
	DataVerifyURL        = "url"
)

const (
	alphabet             = "abcdefghijkmnopqrstuvwxyz0123456789"
	recoveryCodeLength   = 10
	verifyEmailTokenSize = 16
)

// User interface
type User interface {
	authboss.User

	GetEmail() string
	PutEmail(string)

	// GetRecoveryCodes retrieves a CSV string of bcrypt'd recovery codes
	GetRecoveryCodes() string
	// PutRecoveryCodes uses a single string to store many
	// bcrypt'd recovery codes
	PutRecoveryCodes(codes string)
}

Remove L from two factor recovery codes


package forgotpwdemail

import (
	"crypto/sha1"
	"fmt"
	"io"
	"time"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"

	"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)

type CodeGenerator struct {
	MasterKey string
}

func (c *CodeGenerator) Generate(
	authInfo authinfo.AuthInfo,
	userProfile userprofile.UserProfile,
	hashedPassword []byte,
	expireAt time.Time,
) string {
	h := sha1.New()
	io.WriteString(h, c.MasterKey)
	io.WriteString(h, authInfo.ID)
	if email, ok := userProfile.Data["email"].(string); ok {
		io.WriteString(h, email)
	}
	io.WriteString(h, expireAt.Format(time.RFC3339))
	if len(hashedPassword) > 0 {
		h.Write(hashedPassword)
	}
	if authInfo.LastLoginAt != nil && !authInfo.LastLoginAt.IsZero() {
		io.WriteString(h, authInfo.LastLoginAt.Format(time.RFC3339))
	}

	bs := h.Sum(nil)
	return fmt.Sprintf("%x", bs)[0:8]
}

package forgotpwdemail

import (
	"crypto/sha256"
	"fmt"
	"io"
	"time"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"

	"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)

type CodeGenerator struct {
	MasterKey string
}

func (c *CodeGenerator) Generate(
	authInfo authinfo.AuthInfo,
	userProfile userprofile.UserProfile,
	hashedPassword []byte,
	expireAt time.Time,
) string {
	h := sha256.New()
	io.WriteString(h, c.MasterKey)
	io.WriteString(h, authInfo.ID)
	if email, ok := userProfile.Data["email"].(string); ok {
		io.WriteString(h, email)
	}
	io.WriteString(h, expireAt.Format(time.RFC3339))
	if len(hashedPassword) > 0 {
		h.Write(hashedPassword)
	}
	if authInfo.LastLoginAt != nil && !authInfo.LastLoginAt.IsZero() {
		io.WriteString(h, authInfo.LastLoginAt.Format(time.RFC3339))
	}

	bs := h.Sum(nil)
	return fmt.Sprintf("%x", bs)[0:8]
}

Use sha256 instead of sha1 to fix lint


// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package auth

import (
	"go.chromium.org/luci/server/router"
)

// Authenticate returns a middleware that performs authentication.
//
// This is simplest form of this middleware that uses only one authentication
// method. It is sufficient in most cases.
//
// This middleware either updates the context by injecting the authentication
// state into it (enabling functions like CurrentIdentity and IsMember), or
// aborts the request with an HTTP 401 or HTTP 500 error.
//
// Note that it passes through anonymous requests. CurrentIdentity returns
// identity.AnonymousIdentity in this case. Use separate authorization layer to
// further restrict the access, if necessary.
func Authenticate(m Method) router.Middleware {
	a := &Authenticator{Methods: []Method{m}}
	return a.GetMiddleware()
}

// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package auth

import (
	"go.chromium.org/luci/server/router"
)

// Authenticate returns a middleware that performs authentication.
//
// Typically you only one one Method, but you may specify multiple Methods to be
// tried in order (see Authenticator).
//
// This middleware either updates the context by injecting the authentication
// state into it (enabling functions like CurrentIdentity and IsMember), or
// aborts the request with an HTTP 401 or HTTP 500 error.
//
// Note that it passes through anonymous requests. CurrentIdentity returns
// identity.AnonymousIdentity in this case. Use separate authorization layer to
// further restrict the access, if necessary.
func Authenticate(m ...Method) router.Middleware {
	a := &Authenticator{Methods: m}
	return a.GetMiddleware()
}

Allow Authenticate package function to take multiple Methods.


package observers

import (
	"github.com/sirupsen/logrus"

	"github.com/ivan1993spb/snake-server/objects/wall"
	"github.com/ivan1993spb/snake-server/world"
)

const wallPerNDots = 100

type WallObserver struct{}

func (WallObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) {
	go func() {
		for i := uint16(0); i < w.Size()/wallPerNDots; i++ {
			if _, err := wall.NewRandWall(w); err != nil {
				logger.WithError(err).Error("cannot create rand wall")
			}
		}
	}()
}

package observers

import (
	"github.com/sirupsen/logrus"

	"github.com/ivan1993spb/snake-server/objects/wall"
	"github.com/ivan1993spb/snake-server/world"
)

type WallObserver struct{}

func (WallObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) {
	go func() {
		if _, err := wall.NewWallRuins(w); err != nil {
			logger.WithError(err).Error("cannot create wall ruins")
		}
	}()
}

Fix WallObserver to use wall.NewWallRuins wall generator


// +build acceptance

package app_test

import (
	"net"

	"github.com/DATA-DOG/godog"
	"github.com/deshboard/boilerplate-grpc-service/test"
	"google.golang.org/grpc"
)

func init() {
	test.RegisterFeaturePath("../features")
	test.RegisterFeatureContext(FeatureContext)
}

func FeatureContext(s *godog.Suite) {
	lis, err := net.Listen("tcp", ":0")
	if err != nil {
		panic(err)
	}

	client, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		panic(err)
	}

	server := grpc.NewServer()

	// Add steps here
	func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client)

	go server.Serve(lis)
}

// +build acceptance

package app_test

import (
	"net"

	"github.com/DATA-DOG/godog"
	"github.com/deshboard/boilerplate-grpc-service/test"
	"google.golang.org/grpc"
)

func init() {
	test.RegisterFeaturePath("../features")
	test.RegisterFeatureContext(FeatureContext)
}

func FeatureContext(s *godog.Suite) {
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}

	client, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
	if err != nil {
		panic(err)
	}

	server := grpc.NewServer()

	// Add steps here
	func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client)

	go server.Serve(lis)
}

Use the loopback interface for acceptance tests


package config

// Default Configurator constants that are describe a specific configuration option
const (
	Locale    = "Locale"
	Keymap    = "Keymap"
	Wifi      = "Wifi"
	Interface = "Interface"
	DNS       = "DNS"
	SSH       = "SSH"
	Camera    = "Camera"

	MountDir = "/tmp/isaax-sd/"

	Language   = "LANGUAGE=%s\n"
	LocaleAll  = "LC_ALL=%s\n"
	LocaleLang = "LANG=%s\n"

	DefaultLocale = "en_US.UTF-8"

	IsaaxConfDir = "/etc/"
	TmpDir       = "/tmp/"

	InterfaceWLAN string = "auto wlan0\n" +
		"iface wlan0 inet static\n" +
		"address %s\n" +
		"netmask %s\n" +
		"gateway %s\n" +
		"dns-nameservers %s\n"

	InterfaceETH string = "auto eth0\n" +
		"iface eth0 inet static\n" +
		"address %s\n" +
		"netmask %s\n" +
		"gateway %s\n" +
		"dns-nameservers %s\n" +
		"\n" +
		"iface default inet dhcp\n"

	WPAconf = `ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev

	update_config=1

	network={
		ssid=\"%s\"
		psk=\"%s\"
	}
	`
)

package config

// Default Configurator constants that are describe a specific configuration option
const (
	Locale    = "Locale"
	Keymap    = "Keymap"
	Wifi      = "Wifi"
	Interface = "Interface"
	DNS       = "DNS"
	SSH       = "SSH"
	Camera    = "Camera"

	MountDir = "/tmp/isaax-sd/"

	Language   = "LANGUAGE=%s\n"
	LocaleAll  = "LC_ALL=%s\n"
	LocaleLang = "LANG=%s\n"

	DefaultLocale = "en_US.UTF-8"

	IsaaxConfDir = "/etc/"
	TmpDir       = "/tmp/"

	InterfaceWLAN string = "auto wlan0\n" +
		"iface wlan0 inet static\n" +
		"address %s\n" +
		"netmask %s\n" +
		"gateway %s\n" +
		"dns-nameservers %s\n"

	InterfaceETH string = "auto eth0\n" +
		"iface eth0 inet static\n" +
		"address %s\n" +
		"netmask %s\n" +
		"gateway %s\n" +
		"dns-nameservers %s\n" +
		"\n" +
		"iface default inet dhcp\n"

	WPAconf = `ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    country=us
	update_config=1

	network={
		ssid=\"%s\"
		psk=\"%s\"

	}
	`
)

Add default country to wpa supplicant


package s3

// Options defines options for S3-based storage.
type Options struct {
	// BucketName is the name of the bucket where data is stored.
	BucketName string `json:"bucket"`

	// Prefix specifies additional string to prepend to all objects.
	Prefix string `json:"prefix,omitempty"`

	Endpoint    string `json:"endpoint"`
	DoNotUseTLS bool   `json:"doNotUseTLS,omitempyy"`

	AccessKeyID     string `json:"accessKeyID"`
	SecretAccessKey string `json:"secretAccessKey" kopia:"sensitive"`

	MaxUploadSpeedBytesPerSecond int `json:"maxUploadSpeedBytesPerSecond,omitempty"`

	MaxDownloadSpeedBytesPerSecond int `json:"maxDownloadSpeedBytesPerSecond,omitempty"`
}

package s3

// Options defines options for S3-based storage.
type Options struct {
	// BucketName is the name of the bucket where data is stored.
	BucketName string `json:"bucket"`

	// Prefix specifies additional string to prepend to all objects.
	Prefix string `json:"prefix,omitempty"`

	Endpoint    string `json:"endpoint"`
	DoNotUseTLS bool   `json:"doNotUseTLS,omitempty"`

	AccessKeyID     string `json:"accessKeyID"`
	SecretAccessKey string `json:"secretAccessKey" kopia:"sensitive"`

	MaxUploadSpeedBytesPerSecond int `json:"maxUploadSpeedBytesPerSecond,omitempty"`

	MaxDownloadSpeedBytesPerSecond int `json:"maxDownloadSpeedBytesPerSecond,omitempty"`
}

Fix mispelled tag, caught by staticheck linter


// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"
)

func main() {
}

// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"  // ERROR "missing"
)

func main() {
}

Add ERROR comment for errmsg to look for.


package utils

import (
	"bytes"
	"os/exec"
)

func ExecCmd(name string, args ...string) (string, error) {
	cmd := exec.Command(name, args...)
	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		return "", err
	}

	return out.String(), nil
}

package utils

import (
	"bytes"
	"os/exec"
	"syscall"
)

const PR_SET_CHILD_SUBREAPER = 36

func ExecCmd(name string, args ...string) (string, error) {
	cmd := exec.Command(name, args...)
	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		return "", err
	}

	return out.String(), nil
}

// SetSubreaper sets the value i as the subreaper setting for the calling process
func SetSubreaper(i int) error {
	return Prctl(PR_SET_CHILD_SUBREAPER, uintptr(i), 0, 0, 0)
}

// Prctl is a way to make the prctl linux syscall
func Prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {
	_, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)
	if e1 != 0 {
		err = e1
	}
	return
}

Add utility functions to set process as subreaper.


// staticcheck statically checks arguments to certain functions
package main // import "honnef.co/go/staticcheck/cmd/staticcheck"

import (
	"os"

	"honnef.co/go/lint/lintutil"
	"honnef.co/go/staticcheck"
)

func main() {
	var args []string
	for _, arg := range os.Args[1:] {
		if arg == "-dubious" {
			continue
		}
		args = append(args, arg)
	}
	c := staticcheck.NewChecker()
	lintutil.ProcessArgs("staticcheck", c, args)
}

// staticcheck statically checks your code for bugs.
package main // import "honnef.co/go/staticcheck/cmd/staticcheck"

import (
	"os"

	"honnef.co/go/lint/lintutil"
	"honnef.co/go/staticcheck"
)

func main() {
	var args []string
	for _, arg := range os.Args[1:] {
		if arg == "-dubious" {
			continue
		}
		args = append(args, arg)
	}
	c := staticcheck.NewChecker()
	lintutil.ProcessArgs("staticcheck", c, args)
}

Update package docs of the command


package horizon

import (
	"github.com/stellar/horizon/db"
	"github.com/stellar/horizon/txsub"
	"net/http"
)

func initSubmissionSystem(app *App) {
	app.submitter = &txsub.System{
		Pending:   txsub.NewDefaultSubmissionList(),
		Submitter: txsub.NewDefaultSubmitter(http.DefaultClient, app.config.StellarCoreUrl),
		Results: &db.ResultProvider{
			Ctx:     app.ctx,
			Core:    app.coreDb,
			History: app.historyDb,
		},
		NetworkPassphrase: app.networkPassphrase,
	}
}

func init() {
	appInit.Add("txsub", initSubmissionSystem, "app-context", "log", "history-db", "core-db")
}

package horizon

import (
	"github.com/stellar/horizon/db"
	"github.com/stellar/horizon/txsub"
	"net/http"
	"time"
)

func initSubmissionSystem(app *App) {
	app.submitter = &txsub.System{
		Pending:   txsub.NewDefaultSubmissionList(),
		Submitter: txsub.NewDefaultSubmitter(http.DefaultClient, app.config.StellarCoreUrl),
		Results: &db.ResultProvider{
			Ctx:     app.ctx,
			Core:    app.coreDb,
			History: app.historyDb,
		},
		NetworkPassphrase: app.networkPassphrase,
	}

	//TODO: bundle this with the ledger close pump system
	go func() {
		for {
			<-time.After(1 * time.Second)
			app.submitter.Tick(app.ctx)
		}
	}()
}

func init() {
	appInit.Add("txsub", initSubmissionSystem, "app-context", "log", "history-db", "core-db")
}

Add janky Ticker for txsub system


package cmd

import (
	"github.com/gsamokovarov/jump/cli"
)

func Example_helpCmd() {
	_ = helpCmd(cli.Args{}, nil)

	// Output:
	// Usage: jump [COMMAND ...]
	//
	// Jump to a fuzzy-matched directory passed as an argument.
	//
	// Commands:
	//   cd           Fuzzy match a directory to jump to.
	//   chdir        Update the score of directory during chdir.
	//   clean        Cleans the database of inexisting entries.
	//   forget       Removes the current directory from the database.
	//   hint         Hints relevant paths for jumping.
	//   import       Import autojump or z scores.
	//   pin          Pin a directory to a search term.
	//   pins         Lists all the pinned search terms.
	//   settings     Configure jump settings
	//   shell        Display a shell integration script.
	//   top          Lists the directories as they are scored.
	//   unpin        Unpin a search term.
	//
	// Options:
	//   --help       Show this screen.
	//   --version    Show version.
}

package cmd

import (
	"github.com/gsamokovarov/jump/cli"
)

func Example_helpCmd() {
	_ = helpCmd(cli.Args{}, nil)

	// Output:
	// Usage: jump [COMMAND ...]
	//
	// Jump to a fuzzy-matched directory passed as an argument.
	//
	// Commands:
	//   cd           Fuzzy match a directory to jump to.
	//   chdir        Update the score of directory during chdir.
	//   clean        Cleans the database of inexisting entries.
	//   forget       Removes the current directory from the database.
	//   hint         Hints relevant paths for jumping.
	//   import       Import autojump or z scores.
	//   pin          Pin a directory to a search term.
	//   pins         Lists all the pinned search terms.
	//   settings     Configure jump settings.
	//   shell        Display a shell integration script.
	//   top          Lists the directories as they are scored.
	//   unpin        Unpin a search term.
	//
	// Options:
	//   --help       Show this screen.
	//   --version    Show version.
}

Fix the settings dot tests


package github

import (
	"fmt"
	"strings"

	"github.com/hashicorp/vault/api"
)

type CLIHandler struct{}

func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	mount, ok := m["mount"]
	if !ok {
		mount = "github"
	}

	token, ok := m["token"]
	if !ok {
		return "", fmt.Errorf("'token' var must be set")
	}

	path := fmt.Sprintf("auth/%s/login", mount)
	secret, err := c.Logical().Write(path, map[string]interface{}{
		"token": token,
	})
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}

func (h *CLIHandler) Help() string {
	help := `
The GitHub credential provider allows you to authenticate with GitHub.
To use it, specify the "token" var with the "-var" flag. The value should
be a personal access token for your GitHub account. You can generate a personal
access token on your account settings page on GitHub.

    Example: vault auth -method=github -var="token=<token>"

	`

	return strings.TrimSpace(help)
}

package github

import (
	"fmt"
	"strings"

	"github.com/hashicorp/vault/api"
)

type CLIHandler struct{}

func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	mount, ok := m["mount"]
	if !ok {
		mount = "github"
	}

	token, ok := m["token"]
	if !ok {
		return "", fmt.Errorf("'token' var must be set")
	}

	path := fmt.Sprintf("auth/%s/login", mount)
	secret, err := c.Logical().Write(path, map[string]interface{}{
		"token": token,
	})
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}

func (h *CLIHandler) Help() string {
	help := `
The GitHub credential provider allows you to authenticate with GitHub.
To use it, specify the "token" var with the "-var" flag. The value should
be a personal access token for your GitHub account. You can generate a personal
access token on your account settings page on GitHub.

    Example: vault auth -method=github token=<token>

	`

	return strings.TrimSpace(help)
}

Fix output from GitHub help


package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{"abc", regexp.MustCompile(`(abc)`)},

	{"a,b", regexp.MustCompile(`(a|b)`)},

	{"a\\,b", regexp.MustCompile(`(a,b)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{"abc", regexp.MustCompile(`(abc)`)},
	{"abcdef", regexp.MustCompile(`(abcdef)`)},

	{"a,b", regexp.MustCompile(`(a|b)`)},
	{"a,bc,def", regexp.MustCompile(`(a|bc|def)`)},

	{"a\\,b", regexp.MustCompile(`(a,b)`)},
	{"a\\,bc\\,def", regexp.MustCompile(`(a,bc,def)`)},

	{"a\\,b,c", regexp.MustCompile(`(a,b|c)`)},
	{"a,bc\\,def", regexp.MustCompile(`(a|bc,def)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

Add valid cases for later


// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

func out_escapes() (x int, p *int) {
	p = &x;	// ERROR "address.*out parameter"
	return;
}

func out_escapes() (x int, p *int) {
	return 2, &x;	// ERROR "address.*out parameter"
}

// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

func out_escapes() (x int, p *int) {
	p = &x;	// ERROR "address of out parameter"
	return;
}

func out_escapes_2() (x int, p *int) {
	return 2, &x;	// ERROR "address of out parameter"
}

Rename function to avoid function redefinition error. Remove .* from regexp since it confuses DejaGNU which runs gcc's testsuite.


package validations

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

var settingKey = "validations:errors"

func AddError(db *gorm.DB, resource interface{}, err string) {
	var errors = GetErrors(db)
	var scope = db.NewScope(resource)

	key := fmt.Sprintf("%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue())
	errors[key] = append(errors[key], err)

	db.InstantSet(settingKey, errors)
}

func AddErrorForColumn(db *gorm.DB, resource interface{}, column, err string) {
	var errors = GetErrors(db)
	var scope = db.NewScope(resource)

	key := fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), column)
	errors[key] = append(errors[key], err)

	db.InstantSet(settingKey, errors)
}

func GetErrors(db *gorm.DB) map[string][]string {
	var errors = map[string][]string{}
	if e, ok := db.Get(settingKey); ok {
		errors = e.(map[string][]string)
	}
	return errors
}

package validations

import (
	"errors"
	"fmt"

	"github.com/jinzhu/gorm"
)

var settingKey = "validations:errors"

func AddError(db *gorm.DB, resource interface{}, err string) {
	var validationErrors = GetErrors(db)
	var scope = db.NewScope(resource)

	key := fmt.Sprintf("%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue())
	validationErrors[key] = append(validationErrors[key], err)

	db.InstantSet(settingKey, validationErrors).Error = errors.New(err)
}

func AddErrorForColumn(db *gorm.DB, resource interface{}, column, err string) {
	var validationErrors = GetErrors(db)
	var scope = db.NewScope(resource)

	key := fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), column)
	validationErrors[key] = append(validationErrors[key], err)

	db.InstantSet(settingKey, validationErrors).Error = errors.New(err)
}

func GetErrors(db *gorm.DB) map[string][]string {
	var validationErrors = map[string][]string{}
	if errors, ok := db.Get(settingKey); ok {
		validationErrors = errors.(map[string][]string)
	}
	return validationErrors
}

Set DB's Error if get any validation error


package ast_test

import (
	"strings"
	"testing"

	"github.com/DeedleFake/wdte/ast"
)

func printTree(t *testing.T, cur ast.Node, depth int) {
	indent := strings.Repeat("  ", depth)
	switch cur := cur.(type) {
	case *ast.Term:
		t.Logf("%v%v", indent, cur)

	case *ast.NTerm:
		t.Logf("%v(%v", indent, cur)
		for _, c := range cur.Children() {
			printTree(t, c, depth+1)
		}
		t.Logf("%v)", indent)

	case *ast.Epsilon:
		t.Logf("%vε", indent)

	default:
		t.Fatalf("Unexpected node: %#v", cur)
	}
}

func TestParse(t *testing.T) {
	//const test = `"test" => t; + x y => nil;`

	const test = `
'test' => test;

fib n => switch n {
	0 => 0;
	default => + (fib (- n 1)) (fib (- n 2));
};

main => print (fib 5);
`

	root, err := ast.Parse(strings.NewReader(test))
	if err != nil {
		t.Fatal(err)
	}
	printTree(t, root, 0)
}

package ast_test

import (
	"strings"
	"testing"

	"github.com/DeedleFake/wdte/ast"
)

func printTree(t *testing.T, cur ast.Node, depth int) {
	indent := strings.Repeat("  ", depth)
	switch cur := cur.(type) {
	case *ast.Term:
		t.Logf("%v%v", indent, cur)

	case *ast.NTerm:
		t.Logf("%v(%v", indent, cur)
		for _, c := range cur.Children() {
			printTree(t, c, depth+1)
		}
		t.Logf("%v)", indent)

	case *ast.Epsilon:
		t.Logf("%vε", indent)

	default:
		t.Fatalf("Unexpected node: %#v", cur)
	}
}

func TestParse(t *testing.T) {
	//const test = `"test" => t; + x y => nil;`

	const test = `
'test' => test;

fib n => switch n {
	0 => 0;
	default => + (fib (- n 1;);) (fib (- n 2;););
};

main => print (fib 5;);
`

	root, err := ast.Parse(strings.NewReader(test))
	if err != nil {
		t.Fatal(err)
	}
	printTree(t, root, 0)
}

Fix syntax error in test.


// Enumerates USB devices, finds and identifies CrazyRadio USB dongle.
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/krasin/crazyradio"
	"github.com/krasin/crazyradio/usb"
)

func fail(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
	os.Exit(1)
}

func main() {
	st, err := crazyradio.Start(usb.Hub)
	if err != nil {
		fail("Unable to start station: %v\n", err)
	}

	addr, err := st.Scan()
	if err != nil {
		fail("Scan: %v\n", err)
	}

	if len(addr) == 0 {
		fail("No Crazyflies found\n")
	}

	flie, err := st.Open(addr[0])
	if err != nil {
		fail("Unable to connect to [%s]: %v\n", addr, err)
	}

	flie.Write([]byte{60, 0, 0, 0, 0, 0, 0, 0, 128, 250, 117, 61, 64, 48, 117})

	fmt.Printf("Press Ctrl+C to exit\n")
	for {
		time.Sleep(time.Second)
	}
}

// Enumerates USB devices, finds and identifies CrazyRadio USB dongle.
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/krasin/crazyradio"
	"github.com/krasin/crazyradio/usb"
)

func fail(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
	os.Exit(1)
}

func main() {
	st, err := crazyradio.Start(usb.Hub)
	if err != nil {
		fail("Unable to start station: %v\n", err)
	}

	addr, err := st.Scan()
	if err != nil {
		fail("Scan: %v\n", err)
	}

	if len(addr) == 0 {
		fail("No Crazyflies found\n")
	}

	flieAddr := addr[0]
	flie, err := st.Open(flieAddr)
	if err != nil {
		fail("Unable to connect to [%s]: %v\n", flieAddr, err)
	}

	flie.Write([]byte{60, 0, 0, 0, 0, 0, 0, 0, 128, 250, 117, 61, 64, 48, 117})

	fmt.Printf("Press Ctrl+C to exit\n")
	for {
		time.Sleep(time.Second)
	}
}

Fix a typo: error message showed the whole list of flies, instead of the one to which we tried to connect


package util

import (
	"testing"
)

func TestNormalizeName(t *testing.T) {
	packages := map[string]string{
		"github.com/Masterminds/cookoo/web/io/foo": "github.com/Masterminds/cookoo",
		"golang.org/x/crypto/ssh":                  "golang.org/x/crypto",
		"incomplete/example":                       "incomplete/example",
		"net":                                      "net",
	}
	for start, expected := range packages {
		if finish, extra := NormalizeName(start); expected != finish {
			t.Errorf("Expected '%s', got '%s'", expected, finish)
		} else if start != finish && start != finish+"/"+extra {
			t.Errorf("Expected %s to end with %s", finish, extra)
		}
	}
}

package util

import (
	"testing"
)

func TestNormalizeName(t *testing.T) {
	packages := map[string]string{
		"github.com/Masterminds/cookoo/web/io/foo": "github.com/Masterminds/cookoo",
		`github.com\Masterminds\cookoo\web\io\foo`: "github.com/Masterminds/cookoo",
		"golang.org/x/crypto/ssh":                  "golang.org/x/crypto",
		"incomplete/example":                       "incomplete/example",
		"net":                                      "net",
	}
	for start, expected := range packages {
		if finish, extra := NormalizeName(start); expected != finish {
			t.Errorf("Expected '%s', got '%s'", expected, finish)
		} else if start != finish && start != finish+"/"+extra {
			t.Errorf("Expected %s to end with %s", finish, extra)
		}
	}
}

Add testcase that fails old code.


package randstring

import (
	"crypto/rand"
	"encoding/hex"
	"io"
	"math/big"
)

/*
   Use mixed-case alphanumeric characters, minus vowels so we don't
   get naughty words. This leaves us with 10+21+21=52 possibilities
   per character, or 5.7 bits (-log(1/52, 2)) of information.

   Thus a random string of length 15 gives us 85 bits of information
*/
const chars = "0123456789bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

func AlphaNum(n int) (string, error) {
	max := big.NewInt(int64(len(chars)))

	bytes := make([]byte, n)
	for i := range bytes {
		j, err := rand.Int(rand.Reader, max)
		if err != nil {
			return "", err
		}

		bytes[i] = chars[int(j.Int64())]
	}
	return string(bytes), nil
}

func Hex(n int) (string, error) {
	bytes := make([]byte, n)
	_, err := io.ReadFull(rand.Reader, bytes)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

package randstring

import (
	"crypto/rand"
	"encoding/hex"
	"io"
	"math/big"
)

/*
   Use mixed-case alphanumeric characters, minus vowels so we don't
   get naughty words. This leaves us with 10+21+21=52 possibilities
   per character, or 5.7 bits (-log(1/52, 2)) of information.

   Thus a random string of length 15 gives us 85 bits of information
*/
const chars = "0123456789bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

func randFromString(n int, charSet string) (string, error) {
	max := big.NewInt(int64(len(charSet)))

	bytes := make([]byte, n)
	for i := range bytes {
		j, err := rand.Int(rand.Reader, max)
		if err != nil {
			return "", err
		}

		bytes[i] = charSet[int(j.Int64())]
	}

	return string(bytes), nil
}

func AlphaNum(n int) (string, error) {
	return randFromString(n, chars)
}

func Numeric(n int) (string, error) {
	return randFromString(n, chars[0:10])
}

func Hex(n int) (string, error) {
	bytes := make([]byte, n)
	_, err := io.ReadFull(rand.Reader, bytes)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

Add a function for generating random numeric strings


package piglatin

import "strings"

func Sentence(sentence string) string {
	if startsWithVowel(sentence) ||
		strings.HasPrefix(sentence, "xr") ||
		strings.HasPrefix(sentence, "yt") {
		return sentence + "ay"
	}
	if strings.HasPrefix(sentence, "p") {
		return strings.TrimPrefix(sentence, "p") + "p" + "ay"
	}

	return sentence
}

func startsWithVowel(sentence string) bool {
	return strings.HasPrefix(sentence, "a") ||
		strings.HasPrefix(sentence, "e") ||
		strings.HasPrefix(sentence, "i") ||
		strings.HasPrefix(sentence, "o") ||
		strings.HasPrefix(sentence, "u")
}

package piglatin

import (
	"fmt"
	"strings"
)

var consonants = []string{"p", "k"}

func Sentence(sentence string) string {
	if startsWithVowel(sentence) ||
		strings.HasPrefix(sentence, "xr") ||
		strings.HasPrefix(sentence, "yt") {
		return sentence + "ay"
	}
	if startsWithConsonant(sentence) {
		return handleConsonant(sentence)
	}

	return sentence
}

func startsWithVowel(sentence string) bool {
	return strings.HasPrefix(sentence, "a") ||
		strings.HasPrefix(sentence, "e") ||
		strings.HasPrefix(sentence, "i") ||
		strings.HasPrefix(sentence, "o") ||
		strings.HasPrefix(sentence, "u")
}

func startsWithConsonant(sentence string) bool {
	for _, consonant := range consonants {
		if strings.HasPrefix(sentence, consonant) {
			return true
		}
	}
	return false
}

func handleConsonant(sentence string) string {
	for _, consonant := range consonants {
		if strings.HasPrefix(sentence, consonant) {
			return strings.TrimPrefix(sentence, consonant) + consonant + "ay"
		}
	}
	panic(fmt.Sprintf("could not find consonant prefix for sentence %v", sentence))
}

Implement rule 2 for multiple consonants


package certstream

import (
	"time"
	"github.com/gorilla/websocket"
	"github.com/jmoiron/jsonq"
	"github.com/pkg/errors"
)

func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
	outputStream := make(chan jsonq.JsonQuery)
	errStream := make(chan error)

	go func() {
		for {
			c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)

			if err != nil {
				errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
				time.Sleep(5 * time.Second)
				continue
			}

			defer c.Close()
			defer close(outputStream)

			for {
				var v interface{}
				err = c.ReadJSON(&v)
				if err != nil {
					errStream <- errors.Wrap(err, "Error decoding json frame!")
				}

				jq := jsonq.NewQuery(v)

				res, err := jq.String("message_type")
				if err != nil {
					errStream <- errors.Wrap(err, "Error creating jq object!")
				}

				if skipHeartbeats && res == "heartbeat" {
					continue
				}

				outputStream <- *jq
			}
		}
	}()

	return outputStream, errStream
}

package certstream

import (
	"time"

	"github.com/gorilla/websocket"
	"github.com/jmoiron/jsonq"
	"github.com/pkg/errors"
)

func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
	outputStream := make(chan jsonq.JsonQuery)
	errStream := make(chan error)

	go func() {
		for {
			c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)

			if err != nil {
				errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
				time.Sleep(5 * time.Second)
				continue
			}

			defer c.Close()
			defer close(outputStream)

			for {
				var v interface{}
				err = c.ReadJSON(&v)
				if err != nil {
					errStream <- errors.Wrap(err, "Error decoding json frame!")
					break
				}

				jq := jsonq.NewQuery(v)

				res, err := jq.String("message_type")
				if err != nil {
					errStream <- errors.Wrap(err, "Error creating jq object!")
				}

				if skipHeartbeats && res == "heartbeat" {
					continue
				}

				outputStream <- *jq
			}
		}
	}()

	return outputStream, errStream
}

Break on error in ReadJSON instead of continuing and panicing on NewQuery later on. Fixes panic on connection loss.


package bitbucket

import (
	"code.cloudfoundry.org/lager"
	api "github.com/SHyx0rmZ/go-bitbucket/bitbucket"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type UserVerifier struct {
	users  []string
	client api.Client
}

func NewUserVerifier(client api.Client, users []string) verifier.Verifier {
	return UserVerifier{
		users: users,
	}
}

func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) {
	currentUser, err := verifier.client.CurrentUser()
	if err != nil {
		logger.Error("failed-to-get-current-user", err)
		return false, err
	}

	for _, user := range verifier.users {
		if user == currentUser {
			return true, nil
		}
	}

	logger.Info("not-validated-user", lager.Data{
		"have": currentUser,
		"want": verifier.users,
	})

	return false, nil
}

package bitbucket

import (
	"code.cloudfoundry.org/lager"
	api "github.com/SHyx0rmZ/go-bitbucket/bitbucket"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type UserVerifier struct {
	users  []string
	client api.Client
}

func NewUserVerifier(client api.Client, users []string) verifier.Verifier {
	return UserVerifier{
		users:  users,
		client: client,
	}
}

func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) {
	verifier.client.SetHTTPClient(c)

	currentUser, err := verifier.client.CurrentUser()
	if err != nil {
		logger.Error("failed-to-get-current-user", err)
		return false, err
	}

	for _, user := range verifier.users {
		if user == currentUser {
			return true, nil
		}
	}

	logger.Info("not-validated-user", lager.Data{
		"have": currentUser,
		"want": verifier.users,
	})

	return false, nil
}

Set HTTP client in UserVerifier


package cruncher

import (
	"github.com/davecgh/go-spew/spew"
	"pilosa/core"
	"pilosa/dispatch"
	"pilosa/index"
	"pilosa/transport"
)

type Cruncher struct {
	core.Service
	close_chan chan bool
	api        *index.FragmentContainer
}

func (cruncher *Cruncher) Run(port int) {
	spew.Dump("Cruncher.Run")
	spew.Dump(port)

	cruncher.api = index.NewFragmentContainer()
	/*
	   bh = api.Get(frag,tileid)
	   api.SetBit(frag,bh,1)
	   api.Count(frag,bh)
	   api.Union(frag,[bh1,bh2])
	   api.Intersect(frag,[bh1,bh2])
	*/

	cruncher.Service.Run()
}

func NewCruncher() *Cruncher {
	service := core.NewService()
	fragment_container := index.NewFragmentContainer()
	cruncher := Cruncher{*service, make(chan bool), fragment_container}
	cruncher.Transport = transport.NewTcpTransport(service)
	cruncher.Dispatch = dispatch.NewCruncherDispatch(service)
	return &cruncher
}

package cruncher

import (
	"github.com/davecgh/go-spew/spew"
	"pilosa/core"
	"pilosa/dispatch"
	"pilosa/index"
	"pilosa/transport"
)

type Cruncher struct {
	*core.Service
	close_chan chan bool
	api        *index.FragmentContainer
}

func (cruncher *Cruncher) Run(port int) {
	spew.Dump("Cruncher.Run")
	spew.Dump(port)

	cruncher.api = index.NewFragmentContainer()
	/*
	   bh = api.Get(frag,tileid)
	   api.SetBit(frag,bh,1)
	   api.Count(frag,bh)
	   api.Union(frag,[bh1,bh2])
	   api.Intersect(frag,[bh1,bh2])
	*/

	cruncher.Service.Run()
}

func NewCruncher() *Cruncher {
	service := core.NewService()
	fragment_container := index.NewFragmentContainer()
	cruncher := Cruncher{service, make(chan bool), fragment_container}
	cruncher.Transport = transport.NewTcpTransport(service)
	cruncher.Dispatch = dispatch.NewCruncherDispatch(service)
	return &cruncher
}

Use pointer to not copy service.


package test

import (
	"github.com/davecgh/go-spew/spew"
	"github.com/pmezard/go-difflib/difflib"
)

func init() {
	spew.Config.SortKeys = true // :\
}

// Diff diffs two arbitrary data structures, giving human-readable output.
func Diff(want, have interface{}) string {
	text, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
		A:        difflib.SplitLines(spew.Sdump(want)),
		B:        difflib.SplitLines(spew.Sdump(have)),
		FromFile: "want",
		ToFile:   "have",
		Context:  3,
	})
	return "\n" + text
}

package test

import (
	"github.com/davecgh/go-spew/spew"
	"github.com/pmezard/go-difflib/difflib"
)

// Diff diffs two arbitrary data structures, giving human-readable output.
func Diff(want, have interface{}) string {
	config := spew.NewDefaultConfig()
	config.ContinueOnMethod = true
	config.SortKeys = true
	config.SpewKeys = true
	text, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
		A:        difflib.SplitLines(config.Sdump(want)),
		B:        difflib.SplitLines(config.Sdump(have)),
		FromFile: "want",
		ToFile:   "have",
		Context:  3,
	})
	return "\n" + text
}

Make dumper a bit more verbose


package util

import (
	"errors"
	"fmt"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/engine-api/types"
)

const labelPrefix string = "io.conplicity"

// CheckErr checks for error, logs and optionally exits the program
func CheckErr(err error, msg string, exit int) {
	if err != nil {
		log.Errorf(msg, err)

		if exit != -1 {
			os.Exit(exit)
		}
	}
}

// GetVolumeLabel retrieves the value of given key in the io.conplicity
// namespace of the volume labels
func GetVolumeLabel(vol *types.Volume, key string) (value string, err error) {
	value, ok := vol.Labels[labelPrefix+key]
	if !ok {
		errMsg := fmt.Sprintf("Key %v not found in labels for volume %v", key, vol.Name)
		err = errors.New(errMsg)
	}
	return
}

package util

import (
	"errors"
	"fmt"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/engine-api/types"
)

const labelPrefix string = "io.conplicity"

// CheckErr checks for error, logs and optionally exits the program
func CheckErr(err error, msg string, exit int) {
	if err != nil {
		if exit != -1 {
			log.Fatalf(msg, err)
			os.Exit(exit)
		} else {
			log.Errorf(msg, err)
		}
	}
}

// GetVolumeLabel retrieves the value of given key in the io.conplicity
// namespace of the volume labels
func GetVolumeLabel(vol *types.Volume, key string) (value string, err error) {
	value, ok := vol.Labels[labelPrefix+key]
	if !ok {
		errMsg := fmt.Sprintf("Key %v not found in labels for volume %v", key, vol.Name)
		err = errors.New(errMsg)
	}
	return
}

Use log.Fatal for fatal errors


package main

import (
	"testing"
)

func TestNewCmd(t *testing.T) {
	initLogsTest()

	args := []string{"new", "/tmp/testwf.go"}
	err := parseFlags(args)
	if err != nil {
		t.Error("Could not parse flags:", err.Error())
	}
}

package main

import (
	"os"
	"testing"
)

func TestNewCmd(t *testing.T) {
	initLogsTest()

	testWfPath := "/tmp/testwf.go"

	args := []string{"new", testWfPath}
	err := parseFlags(args)
	if err != nil {
		t.Error("Could not parse flags:", err.Error())
	}

	if _, err := os.Stat(testWfPath); os.IsNotExist(err) {
		t.Error(t, "`scipipe new` command failed to create new workflow file: "+testWfPath)
	}

	cleanFiles(t, testWfPath)
}

func cleanFiles(t *testing.T, files ...string) {
	for _, f := range files {
		err := os.Remove(f)
		if err != nil {
			t.Error(err.Error())
		}
	}
}

Extend test of scipipe command


package main

import (
	"fmt"
)

func inspectJob(id uint64) (err error) {
	body, err := conn.Peek(id)
	stats, _ := conn.StatsJob(id)

	if err != nil {
		return fmt.Errorf("Unknown job %v", id)
	}
	printJob(id, body, stats)

	return
}

func nextJobs(state string) {
	for _, t := range ctubes {
		fmt.Printf("Next %s job in %s:\n", state, t.Name)

		if id, body, err := peekState(t, state); err == nil {
			stats, _ := conn.StatsJob(id)
			printJob(id, body, stats)
			fmt.Println()
		}
	}
}

func printJob(id uint64, body []byte, stats map[string]string) {
	fmt.Printf("%25s: %v\n", "id", id)
	fmt.Printf("%25s:\n---------------------\n%s\n---------------------\n", "body", body)

	var include = []string{
		"tube",
		"age",
		"reserves",
		"kicks",
		"delay",
		"releases",
		"pri",
		"ttr",
		"time-left",
		"timeouts",
		"buries",
	}
	printStats(stats, include)
}

package main

import (
	"fmt"
)

func inspectJob(id uint64) (err error) {
	body, err := conn.Peek(id)
	stats, _ := conn.StatsJob(id)

	if err != nil {
		return fmt.Errorf("Unknown job %v", id)
	}
	printJob(id, body, stats)

	return
}

func nextJobs(state string) {
	for _, t := range ctubes {
		fmt.Printf("Next %s job in %s:\n", state, t.Name)

		if id, body, err := peekState(t, state); err == nil {
			stats, _ := conn.StatsJob(id)
			printJob(id, body, stats)
			fmt.Println()
		}
	}
}

func printJob(id uint64, body []byte, stats map[string]string) {
	fmt.Printf("%25s: %v\n", "id", id)
	fmt.Printf("%25s:\n---------------------\n%s\n---------------------\n", "body", body)

	var include = []string{
		"tube",
		"age",
		"reserves",
		"kicks",
		"delay",
		"releases",
		"pri",
		"ttr",
		"timeouts",
		"buries",
	}
	printStats(stats, include)
}

Drop time-left from job stats.


// +build !linux

/*
Copyright 2016 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cm

import "fmt"

type unsupportedCgroupManager struct{}

// Make sure that unsupportedCgroupManager implements the CgroupManager interface
var _ CgroupManager = &unsupportedCgroupManager{}

func NewCgroupManager(_ *cgroupSubsystems) CgroupManager {
	return &unsupportedCgroupManager{}
}

func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error {
	return nil
}

func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error {
	return nil
}

func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error {
	return fmt.Errorf("Cgroup Manager is not supported in this build")
}

// +build !linux

/*
Copyright 2016 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cm

import "fmt"

type unsupportedCgroupManager struct{}

// Make sure that unsupportedCgroupManager implements the CgroupManager interface
var _ CgroupManager = &unsupportedCgroupManager{}

func NewCgroupManager(_ interface{}) CgroupManager {
	return &unsupportedCgroupManager{}
}

func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error {
	return nil
}

func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error {
	return nil
}

func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error {
	return fmt.Errorf("Cgroup Manager is not supported in this build")
}

Fix reference to linux-only struct


package download

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/srt32/hkpg/heroku"
)

// DownloadUrl takes a url string, downloads it, and copies it to a local file
// on disk.
func DownloadUrl(url string, transfer *heroku.Transfer) (*os.File, error) {
	out, err := os.Create(fmt.Sprintf("backup-%d", transfer.Num))
	if err != nil {
		return nil, err
	}

	resp, err := http.Get(url)
	defer resp.Body.Close()
	if err != nil {
		return nil, err
	}

	n, err := io.Copy(out, resp.Body)
	if err != nil {
		return nil, err
	}
	log.Printf("Copied %d bytes", n)

	return out, nil
}

package download

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/srt32/hkpg/heroku"
)

// DownloadUrl takes a url string, downloads it, and copies it to a local file
// on disk.
func DownloadUrl(url string, transfer *heroku.Transfer) (*os.File, error) {
	out, err := os.Create(fmt.Sprintf("backup-%d", transfer.Num))
	if err != nil {
		return nil, err
	}

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	n, err := io.Copy(out, resp.Body)
	if err != nil {
		return nil, err
	}
	log.Printf("Copied %d bytes", n)

	return out, nil
}

Fix go vet error on resp usage


// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build !nouname,linux,386 !nouname,linux,amd64 !nouname,linux,arm64 !nouname,linux,mips64 !nouname,linux,mips64le

package collector

func unameToString(input [65]int8) string {
	var str string
	for _, a := range input {
		if a == 0 {
			break
		}
		str += string(a)
	}
	return str
}

// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build 386 amd64 arm64 mips64 mips64le mips mipsle
// +build linux
// +build !nouname

package collector

func unameToString(input [65]int8) string {
	var str string
	for _, a := range input {
		if a == 0 {
			break
		}
		str += string(a)
	}
	return str
}

Build for 32bit MIPS too


package main

import (
  "fmt"

  "github.com/jasonpuglisi/ircutil"
)

// main requests a server and user which it uses establish a connection. It
// runs a loop to keep the client alive until it is no longer active.
func main() {
  // Request a server with the specified details.
  server, err := ircutil.CreateServer("irc.rizon.net", 6667, true, "");
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Request a user with the specified details.
  user, err := ircutil.CreateUser("Inami", "inami", "Mahiru Inami", 8)
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Establish a connection and get a client using user and server details.
  client, err := ircutil.EstablishConnection(server, user);
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Loop until client is no longer active.
  for client.Active {}
}

package main

import (
  "fmt"

  "github.com/jasonpuglisi/ircutil"
)

// main requests a server and user which it uses establish a connection. It
// runs a loop to keep the client alive until it is no longer active.
func main() {
  // Request a server with the specified details.
  server, err := ircutil.CreateServer("irc.rizon.net", 6697, true, "");
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Request a user with the specified details.
  user, err := ircutil.CreateUser("Inami", "inami", "Mahiru Inami", 8)
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Establish a connection and get a client using user and server details.
  client, err := ircutil.EstablishConnection(server, user);
  if err != nil {
    fmt.Println(err.Error())
    return
  }

  // Loop until client is no longer active.
  for client.Active {}
}

Change connection port to a secure one


package sensu

import "fmt"

// GetEvents Return all the current events
func (s *Sensu) GetEvents() ([]interface{}, error) {
	return s.GetList("events", 0, 0)
}

// GetEventsForClient Returns the current events for given client
func (s *Sensu) GetEventsForClient(client string) ([]interface{}, error) {
	//return s.Get("events", client)
	// TODO  is this the correct way? need validation??
	return s.GetList(fmt.Sprintf("events/%s", client), 0, 0)
}

// GetEventsCheckForClient Returns the event for a check for a client
func (s *Sensu) GetEventsCheckForClient(client string, check string) ([]interface{}, error) {
	//return s.Get("events", client)
	// TODO  is this the correct way? need validation??
	return s.GetList(fmt.Sprintf("events/%s/%s", client, check), 0, 0)
}

// ResolveEvent Resolves an event (delayed action)
func (s *Sensu) ResolveEvent(client string, check string) (map[string]interface{}, error) {
	return s.Delete(fmt.Sprintf("events/%s/%s", client, check))
}

package sensu

import (
	"encoding/json"
	"fmt"
)

// GetEvents Return all the current events
func (s *Sensu) GetEvents() ([]interface{}, error) {
	return s.GetList("events", 0, 0)
}

// GetEventsForClient Returns the current events for given client
func (s *Sensu) GetEventsForClient(client string) ([]interface{}, error) {
	//return s.Get("events", client)
	// TODO  is this the correct way? need validation??
	return s.GetList(fmt.Sprintf("events/%s", client), 0, 0)
}

// GetEventsCheckForClient Returns the event for a check for a client
func (s *Sensu) GetEventsCheckForClient(client string, check string) ([]interface{}, error) {
	//return s.Get("events", client)
	// TODO  is this the correct way? need validation??
	return s.GetList(fmt.Sprintf("events/%s/%s", client, check), 0, 0)
}

// ResolveEvent delete an event
func (s *Sensu) ResolveEvent(payload interface{}) (map[string]interface{}, error) {
	//	return s.Post(fmt.Sprintf("stashes/create"), payload)
	payloadstr, err := json.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("Stash parsing error: %q returned: %v", err, err)
	}
	return s.PostPayload("resolve", string(payloadstr[:]))
}

Add ResolveEvent function that use POST instead of DELETE


package cc1100

import (
	"github.com/ecc1/gpio"
	"github.com/ecc1/spi"
)

const (
	spiSpeed = 1000000 // Hz
	gpioPin  = 14      // Intel Edison GPIO connected to GDO0
)

type Device struct {
	spiDev *spi.Device
	rxGPIO gpio.InputPin
}

func Open() (*Device, error) {
	spiDev, err := spi.Open(spiSpeed)
	if err != nil {
		return nil, err
	}
	err = spiDev.SetMaxSpeed(spiSpeed)
	if err != nil {
		return nil, err
	}
	g, err := gpio.Input(gpioPin, "rising", false)
	if err != nil {
		return nil, err
	}
	return &Device{spiDev: spiDev, rxGPIO: g}, nil
}

package cc1100

import (
	"github.com/ecc1/gpio"
	"github.com/ecc1/spi"
)

const (
	spiSpeed = 6000000 // Hz
	gpioPin  = 14      // Intel Edison GPIO connected to GDO0
)

type Device struct {
	spiDev *spi.Device
	rxGPIO gpio.InputPin
}

func Open() (*Device, error) {
	spiDev, err := spi.Open(spiSpeed)
	if err != nil {
		return nil, err
	}
	err = spiDev.SetMaxSpeed(spiSpeed)
	if err != nil {
		return nil, err
	}
	g, err := gpio.Input(gpioPin, "both", false)
	if err != nil {
		return nil, err
	}
	return &Device{spiDev: spiDev, rxGPIO: g}, nil
}

Increase SPI clock speed and trigger receive interrupt on both rise and fall


package models

type Direction byte

const (
	North Direction = 1 << iota
	South
	East
	West
)

type Coordinate struct {
	X, Y int
}

type Gopher struct {
	// Current direction
	Direction Direction
	X, Y      int
	Path      []Coordinate
}

func (g *Gopher) Increment() {

}

package models

type Direction byte

const (
	North Direction = 1 << iota
	South
	East
	West
)

type Coordinate struct {
	X, Y int
}

type Gopher struct {
	// Current direction
	Direction Direction
	X, Y      int
	Path      []Coordinate
	Score     int
}

Remove (*Gopher).Increment, add Score field to struct Gopher


// +build !windows

package osfs

import (
	"syscall"
)

func (f *file) Lock() error {
	f.m.Lock()
	defer f.m.Unlock()

	return syscall.Flock(int(f.File.Fd()), syscall.LOCK_EX)
}

func (f *file) Unlock() error {
	f.m.Lock()
	defer f.m.Unlock()

	return syscall.Flock(int(f.File.Fd()), syscall.LOCK_UN)
}

// +build !windows

package osfs

import (
	"golang.org/x/sys/unix"
)

func (f *file) Lock() error {
	f.m.Lock()
	defer f.m.Unlock()

	return unix.Flock(int(f.File.Fd()), unix.LOCK_EX)
}

func (f *file) Unlock() error {
	f.m.Lock()
	defer f.m.Unlock()

	return unix.Flock(int(f.File.Fd()), unix.LOCK_UN)
}

Change Posix File Locking to x/unix


package enaml

type JobManifest struct {
	Properties map[string]JobManifestProperty `yaml:"properties"`
}

type JobManifestProperty struct {
	Description string      `yaml:"description"`
	Default     interface{} `yaml:"default"`
}

package enaml

type JobManifest struct {
	Name       string                         `yaml:"name"`
	Properties map[string]JobManifestProperty `yaml:"properties"`
}

type JobManifestProperty struct {
	Description string      `yaml:"description"`
	Default     interface{} `yaml:"default"`
}

Add Name to job manifest yaml struct


package utils

import (
	"github.com/paulbellamy/ratecounter"
	"github.com/c2h5oh/datasize"
	"time"
)

type DataRateCounter interface {
	GetDataRate() datasize.ByteSize
	CaptureEvent(rate int)
}

func NewRateCounter() DataRateCounter {
	return dataRateCounter{
		rateCounter: ratecounter.NewRateCounter(10 * time.Second),
	}
}

type dataRateCounter struct {
	rateCounter *ratecounter.RateCounter
	//rateUpdater chan uint
}

func (c dataRateCounter) GetDataRate() datasize.ByteSize {
	return (datasize.ByteSize)(c.rateCounter.Rate()/10) * datasize.B
}

func (c dataRateCounter) CaptureEvent(rate int) {
	c.rateCounter.Incr(int64(rate))
	//return (datasize.ByteSize)(c.rateCounter.Rate()/10) * datasize.B
}

package utils

import (
	"github.com/paulbellamy/ratecounter"
	"github.com/c2h5oh/datasize"
	"time"
)

type DataRateCounter interface {
	GetDataRate() datasize.ByteSize
	CaptureEvent(rate int)
}

func NewRateCounter() DataRateCounter {
	counter := dataRateCounter{
		rateCounter:     ratecounter.NewRateCounter(10 * time.Second),
		noActivityTimer: time.NewTimer(time.Second),
	}
	go counter.updateOnNoActivity()

	return counter
}

type dataRateCounter struct {
	rateCounter *ratecounter.RateCounter
	noActivityTimer *time.Timer
}

func (c dataRateCounter) GetDataRate() datasize.ByteSize {
	return (datasize.ByteSize)(c.rateCounter.Rate()/10) * datasize.B
}

func (c dataRateCounter) CaptureEvent(rate int) {
	c.rateCounter.Incr(int64(rate))
	c.noActivityTimer.Reset(time.Second)
}

func (c dataRateCounter) updateOnNoActivity() {
	for {
		<-c.noActivityTimer.C
		c.rateCounter.Incr(0)
	}
}

Update data rate counter on no activity


// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package merkle

// LogHasher provides the hash functions needed to compute dense merkle trees.
type LogHasher interface {
	// EmptyRoot supports returning a special case for the root of an empty tree.
	EmptyRoot() []byte
	// HashLeaf computes the hash of a leaf that exists.
	HashLeaf(leaf []byte) []byte
	// HashChildren computes interior nodes.
	HashChildren(l, r []byte) []byte
	// Size returns the number of bytes the Hash* functions will return.
	Size() int
}

// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package merkle provides Merkle tree interfaces and implementation.
package merkle

// TODO(pavelkalinnikov): Remove this root package. The only interface provided
// here does not have to exist, and can be [re-]defined on the user side, such
// as in compact or proof package.

// LogHasher provides the hash functions needed to compute dense merkle trees.
type LogHasher interface {
	// EmptyRoot supports returning a special case for the root of an empty tree.
	EmptyRoot() []byte
	// HashLeaf computes the hash of a leaf that exists.
	HashLeaf(leaf []byte) []byte
	// HashChildren computes interior nodes.
	HashChildren(l, r []byte) []byte
	// Size returns the number of bytes the Hash* functions will return.
	Size() int
}

Add package comment and TODO


package api

const (
	// Version of Rikka
	Version = "0.2.0"
)

package api

const (
	// Version of Rikka
	Version = "0.1.9"
)

Revert "update version to 0.2.0"


// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

func out_escapes() (x int, p *int) {
	p = &x;	// ERROR "address.*out parameter"
	return;
}

func out_escapes() (x int, p *int) {
	return 2, &x;	// ERROR "address.*out parameter"
}

// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

func out_escapes() (x int, p *int) {
	p = &x;	// ERROR "address of out parameter"
	return;
}

func out_escapes_2() (x int, p *int) {
	return 2, &x;	// ERROR "address of out parameter"
}


package netlink

/*
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>

#define IFREQ_SIZE sizeof(struct ifreq)
*/
import "C"

type ifReq struct {
	Name  [C.IFNAMSIZ]byte
	Flags uint16
	pad   [C.IFREQ_SIZE - C.IFNAMSIZ - 2]byte
}

package netlink

// ideally golang.org/x/sys/unix would define IfReq but it only has
// IFNAMSIZ, hence this minimalistic implementation
const (
	SizeOfIfReq = 40
	IFNAMSIZ    = 16
)

type ifReq struct {
	Name  [IFNAMSIZ]byte
	Flags uint16
	pad   [SizeOfIfReq - IFNAMSIZ - 2]byte
}

Drop cgo usage for ifReq structure.


package mpb

import (
	"io/ioutil"
	"testing"
)

func BenchmarkIncrSingleBar(b *testing.B) {
	p := New(WithOutput(ioutil.Discard))
	bar := p.AddBar(int64(b.N))
	for i := 0; i < b.N; i++ {
		bar.Increment()
	}
}

func BenchmarkIncrSingleBarWhileIsNotCompleted(b *testing.B) {
	p := New(WithOutput(ioutil.Discard))
	bar := p.AddBar(int64(b.N))
	for !bar.Completed() {
		bar.Increment()
	}
}

package mpb

import (
	"io/ioutil"
	"testing"

	"github.com/vbauerster/mpb/decor"
)

func BenchmarkIncrSingleBar(b *testing.B) {
	p := New(WithOutput(ioutil.Discard))
	bar := p.AddBar(int64(b.N))
	for i := 0; i < b.N; i++ {
		bar.Increment()
	}
}

func BenchmarkIncrSingleBarWhileIsNotCompleted(b *testing.B) {
	p := New(WithOutput(ioutil.Discard))
	bar := p.AddBar(int64(b.N))
	for !bar.Completed() {
		bar.Increment()
	}
}

func BenchmarkIncrSingleBarWithNameDecorator(b *testing.B) {
	p := New(WithOutput(ioutil.Discard))
	bar := p.AddBar(int64(b.N), PrependDecorators(decor.Name("test")))
	for i := 0; i < b.N; i++ {
		bar.Increment()
	}
}

Add bench with name decorator


package userverify

import (
	"github.com/sirupsen/logrus"
	"github.com/skygeario/skygear-server/pkg/core/db"
)

type safeStoreImpl struct {
	impl      *storeImpl
	txContext db.SafeTxContext
}

func NewSafeStore(
	builder db.SQLBuilder,
	executor db.SQLExecutor,
	logger *logrus.Entry,
	txContext db.SafeTxContext,
) Store {
	return &safeStoreImpl{
		impl: newStore(builder, executor, logger),
	}
}

func (s *safeStoreImpl) CreateVerifyCode(code *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.CreateVerifyCode(code)
}

func (s *safeStoreImpl) UpdateVerifyCode(code *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.UpdateVerifyCode(code)
}

func (s *safeStoreImpl) GetVerifyCodeByCode(code string, vCode *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.GetVerifyCodeByCode(code, vCode)
}

package userverify

import (
	"github.com/sirupsen/logrus"
	"github.com/skygeario/skygear-server/pkg/core/db"
)

type safeStoreImpl struct {
	impl      *storeImpl
	txContext db.SafeTxContext
}

func NewSafeStore(
	builder db.SQLBuilder,
	executor db.SQLExecutor,
	logger *logrus.Entry,
	txContext db.SafeTxContext,
) Store {
	return &safeStoreImpl{
		impl:      newStore(builder, executor, logger),
		txContext: txContext,
	}
}

func (s *safeStoreImpl) CreateVerifyCode(code *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.CreateVerifyCode(code)
}

func (s *safeStoreImpl) UpdateVerifyCode(code *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.UpdateVerifyCode(code)
}

func (s *safeStoreImpl) GetVerifyCodeByCode(code string, vCode *VerifyCode) error {
	s.txContext.EnsureTx()
	return s.impl.GetVerifyCodeByCode(code, vCode)
}

Add missing tx context for user verify tx store.


// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package ptypes

import "math"

// ReverseInt returns reversed x digits.
// 0, false is returned if x cannot be reversed because of int64 overflow.
// The time complexity is O(n), where n is the number of digits in x.
// The space complexity is O(1).
func ReverseInt(x int64) (r int64, ok bool) {
	var n uint64

	neg := x < 0
	u := uint64(x)
	if neg {
		u = -u
	}

	for u > 0 {
		n = n*10 + u%10
		if neg && n > -math.MinInt64 || !neg && n > math.MaxInt64 { // -n < math.MinInt64 || n > math.MaxInt64
			return 0, false
		}
		u /= 10
	}

	r = int64(n)
	if neg {
		r = -r
	}
	return r, true
}

// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package ptypes

import "math"

// ReverseInt returns reversed x digits.
// 0, false is returned if x cannot be reversed because of int64 overflow.
// The time complexity is O(n), where n is the number of digits in x.
// The space complexity is O(1).
func ReverseInt(x int64) (r int64, ok bool) {
	const cutoff = math.MaxInt64/10 + 1 // The first smallest number such that cutoff*10 > MaxInt64.
	var n uint64

	neg := x < 0
	u := uint64(x)
	if neg {
		u = -u
	}

	for u > 0 {
		if n >= cutoff { // Check if n*10 overflows.
			return 0, false // TODO: cover this in tests!
		}
		n = n*10 + u%10
		if neg && n > -math.MinInt64 || !neg && n > math.MaxInt64 { // -n < math.MinInt64 || n > math.MaxInt64
			return 0, false
		}
		u /= 10
	}

	r = int64(n)
	if neg {
		r = -r
	}
	return r, true
}

Add check for multiplication overflow in ptypes.ReverseInt function