// 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 main

import (
	"log"
	"net"
)

func StartServer() {
	listener, err := net.Listen("tcp", Config.String("listen"))
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go communicate(conn)
	}
}

func communicate(conn net.Conn) {
	log.Printf("%v connected", conn.RemoteAddr())

	buf := make([]byte, TotalVoxels * 3)
	for {
		_, err := conn.Read(buf[:3])
		if err != nil {
			log.Printf("%v disconnected", conn.RemoteAddr())
			break
		}
		switch string(buf[:3]) {
		case "inf":
			conn.Write([]byte(INFO))
		case "frm":
			for completed := 0; completed < TotalVoxels * 3; {
				read, err := conn.Read(buf[:TotalVoxels*3 - completed])
				if err != nil {
					log.Printf("%v disconnected", conn.RemoteAddr())
					break
				}
				for i, b := range buf[:read] {
					DisplayBackBuffer[completed+i] = float32(b) / 256
				}
				completed += read
			}
		case "swp":
			SwapDisplayBuffer()
		default:
			conn.Write([]byte("err\n"))
		}
	}
}

package main

import (
	"log"
	"net"
)

func StartServer() {
	listener, err := net.Listen("tcp", Config.String("listen"))
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go communicate(conn)
	}
}

func communicate(conn net.Conn) {
	log.Printf("%v connected", conn.RemoteAddr())

	buf := make([]byte, TotalVoxels * 3)
	for {
		_, err := conn.Read(buf[:3])
		if err != nil {
			log.Printf("%v disconnected", conn.RemoteAddr())
			break
		}
		switch string(buf[:3]) {
		case "nfo":
			conn.Write([]byte(INFO))
		case "frm":
			for completed := 0; completed < TotalVoxels * 3; {
				read, err := conn.Read(buf[:TotalVoxels*3 - completed])
				if err != nil {
					log.Printf("%v disconnected", conn.RemoteAddr())
					break
				}
				for i, b := range buf[:read] {
					DisplayBackBuffer[completed+i] = float32(b) / 256
				}
				completed += read
			}
		case "swp":
			SwapDisplayBuffer()
		}
	}
}

Change inf command to nfo and remove err messages


package main

import "html/template"
import "log"
import "net/http"
import "time"

import "github.com/stianeikeland/go-rpio"

const GPIOPin = 18
const DelaySeconds = 5

type gpioHandler struct {
  pin rpio.Pin
}

func GpioHandler(pin rpio.Pin) http.Handler {
  return &gpioHandler{pin}
}

func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  t, err := template.ParseFiles("templates/hodoor.html")
  if err != nil {
    log.Fatal(err)
  }

  type TemplateOutput struct {
    Pin int
    Delay int
  }
  output := &TemplateOutput{GPIOPin, DelaySeconds}

  t.Execute(w, output)

  timer := time.NewTimer(time.Second * DelaySeconds)
  go func() {
    f.pin.Output()
    f.pin.High()
    <-timer.C
    f.pin.Low()
  }()

}

func main() {
  err := rpio.Open()
  defer rpio.Close()

  if err != nil {
    log.Fatal(err)
  }

  http.Handle("/hodoor", GpioHandler(rpio.Pin(18)))
  http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
  log.Fatal(http.ListenAndServe(":8080", nil))
}

package main

import "html/template"
import "log"
import "net/http"
import "time"

import "github.com/stianeikeland/go-rpio"

const GPIOPin = 18
const DelaySeconds = 5

type gpioHandler struct {
  pin rpio.Pin
}

func GpioHandler(pin rpio.Pin) http.Handler {
  return &gpioHandler{pin}
}

func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  t, err := template.ParseFiles("templates/hodoor.html")
  if err != nil {
    log.Fatal(err)
  }

  type TemplateOutput struct {
    Pin rpio.Pin
    Delay int
  }
  output := &TemplateOutput{f.pin, DelaySeconds}

  t.Execute(w, output)

  timer := time.NewTimer(time.Second * DelaySeconds)
  go func() {
    f.pin.Output()
    f.pin.High()
    <-timer.C
    f.pin.Low()
  }()

}

func main() {
  err := rpio.Open()
  defer rpio.Close()

  if err != nil {
    log.Fatal(err)
  }

  http.Handle("/hodoor", GpioHandler(rpio.Pin(18)))
  http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
  log.Fatal(http.ListenAndServe(":8080", nil))
}

Use member instead of constant.


package main

import (
	"bufio"
	"flag"
	"log"
	"os"

	"github.com/bfontaine/edn"
)

func main() {
	flag.Parse()

	// buffered I/O makes my 55M-file benchmark go 3x times faster
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriter(os.Stdout)

	// This takes ~5.8s on my 55M benchmark file
	err := edn.PPrintStream(output, input, &edn.PPrintOpts{})

	if err != nil {
		log.Fatal(err)
	}
}

package main

import (
	"bufio"
	"flag"
	"log"
	"os"

	"gopkg.in/bfontaine/edn.v1"
)

func main() {
	flag.Parse()

	// buffered I/O makes my 55M-file benchmark go 3x times faster
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriter(os.Stdout)

	// This takes ~5.8s on my 55M benchmark file
	err := edn.PPrintStream(output, input, &edn.PPrintOpts{})

	if err != nil {
		log.Fatal(err)
	}
}

Use a released version of the edn fork


package main

import (
    "github.com/hashicorp/terraform/plugin"
	"github.com/finn-no/terraform-provider-softlayer/softlayer"
)

func main() {
    plugin.Serve(&plugin.ServeOpts{
        ProviderFunc: softlayer.Provider,
    })
}

package main

import (
	"github.com/finn-no/terraform-provider-softlayer/softlayer"
	"github.com/hashicorp/terraform/plugin"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: softlayer.Provider,
	})
}

Fix formatting to comply with go fmt


// +build windows linux
package clw11

/*
#cgo LDFLAGS: -lOpenCL

#include "CL/opencl.h"
*/
import "C"
import (
	"errors"
)

const (
	GLContext     ContextProperties = C.CL_GL_CONTEXT_KHR
	EGLDisplay    ContextProperties = C.CL_EGL_DISPLAY_KHR
	GLXDisplay    ContextProperties = C.CL_GLX_DISPLAY_KHR
	WGLHDC        ContextProperties = C.CL_WGL_HDC_KHR
	CGLSharegroup ContextProperties = C.CL_CGL_SHAREGROUP_KHR
)

var InvalidGLSharegroupReference = errors.New("invalid GL sharegroup reference")

func init() {
	errorMap[C.CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR] = InvalidGLSharegroupReference
}

Fix build issues on darwin.


package cli

import (
	"fmt"

	"github.com/jwaldrip/odin/cli/values"
)

// Flag returns the Value interface to the value of the named flag,
// returning nil if none exists.
func (cmd *CLI) Flag(name string) values.Value {
	flag := cmd.getFlag(name)
	value := cmd.flagValues[flag]
	return value
}

// Flags returns the flags as a map of strings with Values
func (cmd *CLI) Flags() values.Map {
	flags := make(values.Map)
	for name := range cmd.inheritedFlags.Merge(cmd.flags) {
		flags[name] = cmd.Flag(name)
	}
	return flags
}

func (cmd *CLI) getFlag(name string) *Flag {
	flag, exists := cmd.inheritedFlags.Merge(cmd.flags)[name]
	if !exists {
		panic(fmt.Sprintf("flag not defined %v", name))
	}
	return flag
}

func (cmd *CLI) hasFlags() bool {
	var internalFlagCount int
	if flag, ok := cmd.flags["help"]; ok && flag == cmd.flagHelp {
		internalFlagCount++
	}
	if flag, ok := cmd.flags["version"]; ok && flag == cmd.flagVersion {
		internalFlagCount++
	}
	return len(cmd.flags) > internalFlagCount
}

package cli

import (
	"fmt"

	"github.com/jwaldrip/odin/cli/values"
)

// Flag returns the Value interface to the value of the named flag,
// panics if none exists.
func (cmd *CLI) Flag(name string) values.Value {
	flag := cmd.getFlag(name)
	value := cmd.flagValues[flag]
	return value
}

// Flags returns the flags as a map of strings with Values
func (cmd *CLI) Flags() values.Map {
	flags := make(values.Map)
	for name := range cmd.inheritedFlags.Merge(cmd.flags) {
		flags[name] = cmd.Flag(name)
	}
	return flags
}

func (cmd *CLI) getFlag(name string) *Flag {
	flag, exists := cmd.inheritedFlags.Merge(cmd.flags)[name]
	if !exists {
		panic(fmt.Sprintf("flag not defined %v", name))
	}
	return flag
}

func (cmd *CLI) hasFlags() bool {
	var internalFlagCount int
	if flag, ok := cmd.flags["help"]; ok && flag == cmd.flagHelp {
		internalFlagCount++
	}
	if flag, ok := cmd.flags["version"]; ok && flag == cmd.flagVersion {
		internalFlagCount++
	}
	return len(cmd.flags) > internalFlagCount
}

Clarify behavior documented in tests.


package x509util

import (
	"crypto/x509"
	"encoding/asn1"
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"strings"
)

func getPermittedMethods(cert *x509.Certificate) (map[string]struct{}, error) {
	methodList := make(map[string]struct{})
	for _, extension := range cert.Extensions {
		if extension.Id.String() != constants.PermittedMethodListOID {
			continue
		}
		var lines []string
		rest, err := asn1.Unmarshal(extension.Value, &lines)
		if err != nil {
			return nil, err
		}
		if len(rest) > 0 {
			return nil, fmt.Errorf("%d extra bytes in method extension",
				len(rest))
		}
		for _, sm := range lines {
			if strings.Count(sm, ".") == 1 {
				methodList[sm] = struct{}{}
			} else {
				return nil, fmt.Errorf("bad line: \"%s\"", sm)
			}
		}
		return methodList, nil
	}
	// Fallback to deprecated location.
	for _, sm := range strings.Split(cert.Subject.CommonName, ",") {
		if strings.Count(sm, ".") == 1 {
			methodList[sm] = struct{}{}
		}
	}
	return methodList, nil
}

package x509util

import (
	"crypto/x509"
	"encoding/asn1"
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"strings"
)

func getPermittedMethods(cert *x509.Certificate) (map[string]struct{}, error) {
	methodList := make(map[string]struct{})
	for _, extension := range cert.Extensions {
		if extension.Id.String() != constants.PermittedMethodListOID {
			continue
		}
		var lines []string
		rest, err := asn1.Unmarshal(extension.Value, &lines)
		if err != nil {
			return nil, err
		}
		if len(rest) > 0 {
			return nil, fmt.Errorf("%d extra bytes in method extension",
				len(rest))
		}
		for _, sm := range lines {
			if strings.Count(sm, ".") == 1 {
				methodList[sm] = struct{}{}
			} else {
				return nil, fmt.Errorf("bad line: \"%s\"", sm)
			}
		}
		return methodList, nil
	}
	return methodList, nil
}

Remove deprecated methods encoding in lib/x509util.GetPermittedMethods().


package leetcode

// 6. ZigZag Conversion
func convert(s string, numRows int) string {
	if numRows == 1 {
		return s
	}

	strs := make([][]rune, numRows)
	diff := numRows - 2

	for i, c := range s {
		p := i % (numRows + diff)
		if p < numRows {
			strs[p] = append(strs[p], c)
		} else {
			p = (p - numRows - diff) * -1
			strs[p] = append(strs[p], c)
		}
	}

	res := ""
	for _, r := range strs {
		res += string(r)
	}
	return res
}

package leetcode

// 6. ZigZag Conversion
func convert(s string, numRows int) string {
	if numRows == 1 {
		return s
	}

	bs := make([][]byte, numRows)

	i := 0
	for i < len(s) {
		for j := 0; i < len(s) && j < numRows; j++ {
			bs[j] = append(bs[j], s[i])
			i++
		}
		for j := numRows - 2; i < len(s) && j > 0; j-- {
			bs[j] = append(bs[j], s[i])
			i++
		}
	}

	var res []byte
	for _, b := range bs {
		res = append(res, b...)
	}
	return string(res)
}

Fix 6. ZigZag Conversion with inner loop approach


package shell

import (
	"github.com/codegangsta/cli"
	"strings"
)

func SetUp() cli.Command {
	cmd := cli.Command{
		Name:   "shell",
		Usage:  "BQL shell",
		Action: Launch,
	}
	cmd.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "uri",
			Value:  "http://localhost:8090/api",
			Usage:  "target URI to launch",
			EnvVar: "URI",
		},
		cli.StringFlag{
			Name:   "version,v",
			Value:  "v1",
			Usage:  "SenserBee API version",
			EnvVar: "VERSION",
		},
	}
	return cmd
}

// Launch SensorBee's command line client tool.
func Launch(c *cli.Context) {
	host := c.String("uri")
	if !strings.HasSuffix(host, "/") {
		host += "/"
	}
	uri := host + c.String("version")

	cmds := []Command{}
	for _, c := range NewTopologiesCommands() {
		cmds = append(cmds, c)
	}
	for _, c := range NewFileLoadCommands() {
		cmds = append(cmds, c)
	}
	app := SetUpCommands(cmds)
	app.Run(uri)
}

package shell

import (
	"github.com/codegangsta/cli"
	"strings"
)

func SetUp() cli.Command {
	cmd := cli.Command{
		Name:        "shell",
		Usage:       "BQL shell",
		Description: "shell command launches an interactive shell for BQL",
		Action:      Launch,
	}
	cmd.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "uri",
			Value: "http://localhost:8090/",
			Usage: "target URI to launch",
		},
		cli.StringFlag{
			Name:  "version,v",
			Value: "v1",
			Usage: "SenserBee API version",
		},
	}
	return cmd
}

// Launch SensorBee's command line client tool.
func Launch(c *cli.Context) {
	host := c.String("uri") // TODO: validate URI
	if !strings.HasSuffix(host, "/") {
		host += "/"
	}
	uri := host + "api/" + c.String("version")

	cmds := []Command{}
	for _, c := range NewTopologiesCommands() {
		cmds = append(cmds, c)
	}
	for _, c := range NewFileLoadCommands() {
		cmds = append(cmds, c)
	}
	app := SetUpCommands(cmds)
	app.Run(uri)
}

Remove environment variables having too general names


package api_test

func (t *testSuite) TestProjectGroupIndex_Get() {
	t.T().Skip("Not yet implemented")
}

package api_test

import "testing"

func TestProjectGroupIndex_Get(t *testing.T) {
	t.Skip("Not yet implemented")
}

Change testify/suite to the stdlib *testing.T


// Copyright 2017 Google Inc.
//
// 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
//
//     https://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 ftime

import (
	"math"
	"math/rand"
	"time"
)

// ClientRetryTime determines how long to wait for an acknowledgement before
// sending a message to a client again. The normal implementation waits one
// hour. It is mutable primarily to support testing.
var ClientRetryTime = func() time.Time {
	return Now().Add(time.Hour)
}

// ServerRetryTime determines how long to wait before attempting to process a
// message again on the FS server. The normal implementation provides
// exponential backoff with jitter, with an initial wait of 1-2 min. It is
// mutable primarily to support testing.
var ServerRetryTime = func(retryCount uint32) time.Time {
	delay := float64(time.Minute) * math.Pow(1.1, float64(retryCount))
	delay *= 1.0 + rand.Float64()

	return Now().Add(time.Duration(delay))
}

// Copyright 2017 Google Inc.
//
// 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
//
//     https://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 ftime

import (
	"math"
	"math/rand"
	"time"
)

// ClientRetryTime determines how long to wait for an acknowledgement before
// sending a message to a client again. The normal implementation waits 15
// minutes. It is mutable primarily to support testing.
var ClientRetryTime = func() time.Time {
	return Now().Add(15 * time.Minute)
}

// ServerRetryTime determines how long to wait before attempting to process a
// message again on the FS server. The normal implementation provides
// exponential backoff with jitter, with an initial wait of 1-2 min. It is
// mutable primarily to support testing.
var ServerRetryTime = func(retryCount uint32) time.Time {
	delay := float64(time.Minute) * math.Pow(1.1, float64(retryCount))
	delay *= 1.0 + rand.Float64()

	return Now().Add(time.Duration(delay))
}

Reduce the wait time before re-sending a message.


package main

import "net"

type SessionManager struct {
	allSessions []Session
}

func (s *SessionManager) StartSession(conn *net.Conn) {
	var ses Session

	ses.Init(conn, s)
}

func (s *SessionManager) SendRequestToAllSessions(arwServer *ARWServer, obj ARWObject) {

	for ii := 0; ii < len(s.allSessions); ii++ {
		arwServer.SendRequestWithConn(s.allSessions[ii].GetConn(), obj)
	}
}

Send request to all sessions


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

package workers

import (
	"time"

	"github.com/juju/errors"

	"github.com/juju/juju/worker/dependency"
)

const (
	engineErrorDelay  = 3 * time.Second
	engineBounceDelay = 10 * time.Second
)

func newEngine() (dependency.Engine, error) {
	config := newEngineConfig()

	engine, err := dependency.NewEngine(config)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return engine, nil
}

func newEngineConfig() dependency.EngineConfig {
	return dependency.EngineConfig{
		IsFatal:       isFatal,
		MoreImportant: moreImportant,
		ErrorDelay:    engineErrorDelay,
		BounceDelay:   engineBounceDelay,
	}
}

func isFatal(err error) bool {
	return false
}

func moreImportant(err, worst error) error {
	return worst
}

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

package workers

import (
	"time"

	"github.com/juju/errors"

	"github.com/juju/juju/worker/dependency"
)

const (
	engineErrorDelay  = 3 * time.Second
	engineBounceDelay = 10 * time.Second
)

func newEngine() (dependency.Engine, error) {
	config := newEngineConfig()

	engine, err := dependency.NewEngine(config)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return engine, nil
}

func newEngineConfig() dependency.EngineConfig {
	return dependency.EngineConfig{
		IsFatal:       isFatal,
		MoreImportant: moreImportant,
		ErrorDelay:    engineErrorDelay,
		BounceDelay:   engineBounceDelay,
	}
}

// isFatal is an implementation of the IsFatal function in
// dependency.EnginConfig.
func isFatal(err error) bool {
	return false
}

// moreImportant is an implementation of the MoreImportant function in
// dependency.EnginConfig.
func moreImportant(err, worst error) error {
	return worst
}

Add doc comments to internal funcs.


// +build windows

/*
Copyright 2019 The Kubernetes 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 constants

const (
	// DefaultDockerCRISocket defines the default Docker CRI socket
	DefaultDockerCRISocket = "npipe:////./pipe/docker_engine"

	// PauseVersion indicates the default pause image version for kubeadm
	PauseVersion = "1.3.0"
)

// +build windows

/*
Copyright 2019 The Kubernetes 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 constants

const (
	// DefaultDockerCRISocket defines the default Docker CRI socket
	DefaultDockerCRISocket = "npipe:////./pipe/docker_engine"

	// PauseVersion indicates the default pause image version for kubeadm
	PauseVersion = "1.4.0"
)

Update Windows Pause version to 1.4.0


package command

import (
	"testing"
)

const (
	cmdText = "give"
	desc    = "Gives x y to player z"
	usage   = "Usage text"
	message = "/give 1 64 admin"
)

func TestCommandFramework(t *testing.T) {
	cf := NewCommandFramework("/")
	cmdHandler := func(msg string) {
		if msg != message {
			t.Errorf("Input message %s is not equal to received message %s .", message, msg)
		}
	}
	cmd := NewCommand(cmdText, desc, usage, cmdHandler)
	cf.AddCommand(cmd)
	cf.Message <- message
}

package command

import (
	"testing"
)

const (
	cmdText = "give"
	desc    = "Gives x y to player z"
	usage   = "Usage text"
	message = "/give 1 64 admin"
)

func TestCommandFramework(t *testing.T) {
	NewCommandFramework("/")
	// TODO: Write test cases for CommandFramework and all commands
}

Remove old test case of CommandFramework.


package deck_test

import (
	"github.com/whereswaldon/cryptage/deck"
	"testing"
)

func TestBigIntStringConverstion(t *testing.T) {
}

package deck_test

import (
	//	"github.com/whereswaldon/cryptage/deck"
	"testing"
)

func TestBigIntStringConverstion(t *testing.T) {
}

Fix old test fouling up compilation


package petfind

import (
	"errors"
	"time"
)

var ErrNotFound = errors.New("item not found")

// Pet holds information about each pet of the application.
type Pet struct {
	ID    int64
	Name  string
	Age   int
	Added time.Time
}

// Store describes the operations the application needs for persisting and
// retrieving data.
type Store interface {
	AddPet(*Pet) error
	GetAllPets() ([]Pet, error)

	CreateUser(*User) error
	GetUserByGithubID(githubID int64) (*User, error)
	GetUserBySessionID(sessionID string) (*User, error)

	CreateUserSession(*Session) error
	DeleteUserSession(sessionID string) error

	MakeSchema() error
	DropSchema() error
}

type User struct {
	ID       int64
	GithubID int64
	Login    string
	Name     string
	Email    string
	Added    time.Time
}

type Session struct {
	ID     string
	UserID int64
	Added  time.Time
}

// TODO(psimika): Useful article in case a custom type needs to be stored in
// the database:
//
// https://husobee.github.io/golang/database/2015/06/12/scanner-valuer.html

Add article TODO for storing custom types in db


package server

import (
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
)

var apiHost, jsBundleURL, dynoID, twitterAPIToken string
var webPort int

func initEnv() (err error) {
	twitterAPIToken = os.Getenv("TWITTER_TOKEN")
	webPort, err = strconv.Atoi(os.Getenv("PORT"))
	if err != nil || webPort == 0 {
		log.Println("PORT not set, using default")
		webPort = 8080
		err = nil
	}

	jsBundleURL = os.Getenv("JS_BUNDLE")
	if jsBundleURL == "" {
		return errors.New("Could not determing JS bundle URL")
	}

	dynoID = os.Getenv("HEROKU_DYNO_ID")

	apiHost = os.Getenv("API_HOST")
	if apiHost == "" {
		if dynoID == "" {
			return errors.New("Could not determine API URL")
		}
		apiHost = fmt.Sprintf("https://%s.herokuapp.com", dynoID)
		log.Println("API_HOST not set, using default: " + apiHost)
	}

	return
}

func getServeAddress() string {
	return fmt.Sprintf(":%d", webPort)
}

package server

import (
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
)

var apiHost, jsBundleURL, herokuAppName, twitterAPIToken string
var webPort int

func initEnv() (err error) {
	twitterAPIToken = os.Getenv("TWITTER_TOKEN")
	webPort, err = strconv.Atoi(os.Getenv("PORT"))
	if err != nil || webPort == 0 {
		log.Println("PORT not set, using default")
		webPort = 8080
		err = nil
	}

	jsBundleURL = os.Getenv("JS_BUNDLE")
	if jsBundleURL == "" {
		return errors.New("Could not determing JS bundle URL")
	}

	herokuAppName = os.Getenv("HEROKU_APP_NAME")

	apiHost = os.Getenv("API_HOST")
	if apiHost == "" {
		if herokuAppName == "" {
			return errors.New("Could not determine API URL")
		}
		apiHost = fmt.Sprintf("https://%s.herokuapp.com", herokuAppName)
		log.Println("API_HOST not set, using default: " + apiHost)
	}

	return
}

func getServeAddress() string {
	return fmt.Sprintf(":%d", webPort)
}

Rename variable to make more sense given expected value


package main

import (
	"flag"
	"fmt"
	"github.com/mat/besticon/besticon"
	"os"
)

func main() {
	all := flag.Bool("all", false, "Display all Icons, not just the best.")
	flag.Parse()

	if len(os.Args) <= 1 {
		fmt.Fprintf(os.Stderr, "please provide a URL.\n")
		os.Exit(100)
	}

	url := os.Args[len(os.Args)-1]

	icons, err := besticon.FetchIcons(url)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s:  failed to fetch icons: %s\n", url, err)
		os.Exit(1)
	}

	if *all {
		for _, img := range icons {
			if img.Width > 0 {
				fmt.Printf("%s:  %s\n", url, img.URL)
			}
		}
	} else {
		if len(icons) > 0 {
			best := icons[0]
			fmt.Printf("%s:  %s\n", url, best.URL)
		} else {
			fmt.Fprintf(os.Stderr, "%s:  no icons found\n", url)
			os.Exit(2)
		}
	}
}

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/mat/besticon/besticon"
)

func main() {
	besticon.SetLogOutput(ioutil.Discard) // Disable verbose logging

	all := flag.Bool("all", false, "Display all Icons, not just the best.")
	flag.Parse()

	if len(os.Args) <= 1 {
		fmt.Fprintf(os.Stderr, "please provide a URL.\n")
		os.Exit(100)
	}

	url := os.Args[len(os.Args)-1]

	icons, err := besticon.FetchIcons(url)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s:  failed to fetch icons: %s\n", url, err)
		os.Exit(1)
	}

	if *all {
		for _, img := range icons {
			if img.Width > 0 {
				fmt.Printf("%s:  %s\n", url, img.URL)
			}
		}
	} else {
		if len(icons) > 0 {
			best := icons[0]
			fmt.Printf("%s:  %s\n", url, best.URL)
		} else {
			fmt.Fprintf(os.Stderr, "%s:  no icons found\n", url)
			os.Exit(2)
		}
	}
}

Disable verbose logging in command line tool.


package cf_test

import (
	. "cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"path/filepath"
)

var _ = Describe("AppFiles", func() {
	fixturePath := filepath.Join("..", "fixtures", "applications")

	Describe("AppFilesInDir", func() {
		It("all files have '/' path separators", func() {
			files, err := AppFilesInDir(fixturePath)
			Expect(err).ShouldNot(HaveOccurred())

			for _, afile := range files {
				Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path)))
			}
		})

		It("excludes files based on the .cfignore file", func() {
			appPath := filepath.Join(fixturePath, "app-with-cfignore")
			files, err := AppFilesInDir(appPath)
			Expect(err).ShouldNot(HaveOccurred())

			paths := []string{}
			for _, file := range files {
				paths = append(paths, file.Path)
			}

			Expect(paths).To(Equal([]string{
				filepath.Join("dir1", "child-dir", "file3.txt"),
				filepath.Join("dir1", "file1.txt"),
			}))
		})
	})
})

package cf_test

import (
	. "cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"path/filepath"
	"path"
)

var _ = Describe("AppFiles", func() {
	fixturePath := filepath.Join("..", "fixtures", "applications")

	Describe("AppFilesInDir", func() {
		It("all files have '/' path separators", func() {
			files, err := AppFilesInDir(fixturePath)
			Expect(err).ShouldNot(HaveOccurred())

			for _, afile := range files {
				Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path)))
			}
		})

		It("excludes files based on the .cfignore file", func() {
			appPath := filepath.Join(fixturePath, "app-with-cfignore")
			files, err := AppFilesInDir(appPath)
			Expect(err).ShouldNot(HaveOccurred())

			paths := []string{}
			for _, file := range files {
				paths = append(paths, file.Path)
			}

			Expect(paths).To(Equal([]string{
				path.Join("dir1", "child-dir", "file3.txt"),
				path.Join("dir1", "file1.txt"),
			}))
		})
	})
})

Fix app files test on windows


package fs

import (
	"syscall"
	"time"
)

// StatAtime returns the Atim
func StatAtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Atim
}

// StatCtime returns the Ctim
func StatCtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Ctim
}

// StatMtime returns the Mtim
func StatMtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Mtim
}

// StatATimeAsTime returns st.Atim as a time.Time
func StatATimeAsTime(st *syscall.Stat_t) time.Time {
	return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert
}

package fs

import (
	"syscall"
	"time"
)

// StatAtime returns the Atim
func StatAtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Atim
}

// StatCtime returns the Ctim
func StatCtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Ctim
}

// StatMtime returns the Mtim
func StatMtime(st *syscall.Stat_t) syscall.Timespec {
	return st.Mtim
}

// StatATimeAsTime returns st.Atim as a time.Time
func StatATimeAsTime(st *syscall.Stat_t) time.Time {
	// The int64 conversions ensure the line compiles for 32-bit systems as well.
	return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert
}

Add comment about why an int64 conversion is needed in fs.StatATimeAsTime


package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

package main

import (
	"log"
	"os"
	"fmt"

	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
	fmt.Printf("print all")
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

Add test command (*It can be tested with `go install` to get local test cli)


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

package resource

import (
	"github.com/juju/errors"
)

// These are the valid kinds of resource origin.
const (
	OriginKindUnknown OriginKind = ""
	OriginKindUpload  OriginKind = "upload"
	OriginKindStore   OriginKind = "store"
)

var knownOriginKinds = map[OriginKind]bool{
	OriginKindUpload: true,
	OriginKindStore:  true,
}

// OriginKind identifies the kind of a resource origin.
type OriginKind string

// ParseOriginKind converts the provided string into an OriginKind.
// If it is not a known origin kind then an error is returned.
func ParseOriginKind(value string) (OriginKind, error) {
	o := OriginKind(value)
	if !knownOriginKinds[o] {
		return o, errors.Errorf("unknown origin %q", value)
	}
	return o, nil
}

// String returns the printable representation of the origin kind.
func (o OriginKind) String() string {
	return string(o)
}

// Validate ensures that the origin is correct.
func (o OriginKind) Validate() error {
	if !knownOriginKinds[o] {
		return errors.NewNotValid(nil, "unknown origin")
	}
	return nil
}

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

package resource

import (
	"github.com/juju/errors"
)

// These are the valid kinds of resource origin.
const (
	OriginKindUnknown OriginKind = ""
	OriginKindUpload  OriginKind = "upload"
	OriginKindStore   OriginKind = "store"
)

var knownOriginKinds = map[OriginKind]bool{
	OriginKindUpload: true,
	OriginKindStore:  true,
}

// OriginKind identifies the kind of a resource origin.
type OriginKind string

// ParseOriginKind converts the provided string into an OriginKind.
// If it is not a known origin kind then an error is returned.
func ParseOriginKind(value string) (OriginKind, error) {
	o := OriginKind(value)
	if !knownOriginKinds[o] {
		return OriginKindUnknown, errors.Errorf("unknown origin %q", value)
	}
	return o, nil
}

// String returns the printable representation of the origin kind.
func (o OriginKind) String() string {
	return string(o)
}

// Validate ensures that the origin is correct.
func (o OriginKind) Validate() error {
	if !knownOriginKinds[o] {
		return errors.NewNotValid(nil, "unknown origin")
	}
	return nil
}

Return OriginKindUnknown with parsing errors.


package main

import (
	"fmt"
	"os"

	"strings"

	"github.com/hackebrot/go-librariesio/librariesio"
)

func loadFromEnv(keys ...string) (map[string]string, error) {
	env := make(map[string]string)

	for _, key := range keys {
		v := os.Getenv(key)
		if v == "" {
			return nil, fmt.Errorf("environment variable %q is required", key)
		}
		env[key] = v
	}

	return env, nil
}

func main() {
	env, err := loadFromEnv("LIBRARIESIO_API_KEY")

	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, "%v\n", env)

	c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
	project, err := c.GetProject("pypi", "cookiecutter")

	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, "%v\n", project)
}

package main

import (
	"fmt"
	"os"

	"strings"

	"github.com/hackebrot/go-librariesio/librariesio"
)

func loadFromEnv(keys ...string) (map[string]string, error) {
	env := make(map[string]string)

	for _, key := range keys {
		v := os.Getenv(key)
		if v == "" {
			return nil, fmt.Errorf("environment variable %q is required", key)
		}
		env[key] = v
	}

	return env, nil
}

func main() {
	env, err := loadFromEnv("LIBRARIESIO_API_KEY")

	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, "%v\n", env)

	c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
	project, _, err := c.GetProject("pypi", "cookiecutter")

	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, "%v\n", project)
}

Update cmd to accept new return value


package main

import (
	"net/http"
	"log"
)

func Index(w http.ResponseWriter, r *http.Request) {
	body := NewRequest(r).GetBody()

	if config.FastPublish {
		if len(body) > 0 {
			servicesQueue.Publish(body)
		}
		return
	}

	service, err := NewService(body)
	response := NewResponse(w)

	if err != nil {
		response.Body.Error = true
		response.Body.Message = err.Error()
		response.Status = http.StatusUnprocessableEntity
		log.Printf(err.Error())
	} else {
		err := validate.Struct(service)
		if err == nil {
			servicesQueue.Publish(body)
			response.Body.Message = "Success"
			response.Status = http.StatusCreated
			log.Printf("Received: %s", string(body))
		} else {
			response.Body.Error = true
			response.Body.Message = err.Error()
			response.Status = http.StatusBadRequest
			log.Printf(err.Error())
		}
	}

	response.Write()
}

package main

import (
	"net/http"
	"log"
)

func Index(w http.ResponseWriter, r *http.Request) {
	body := NewRequest(r).GetBody()

	if config.FastPublish {
		if len(body) > 0 {
			servicesQueue.Publish(body)
		}
		return
	}

	service, err := NewService(body)
	response := NewResponse(w)

	if err != nil {
		response.Body.Error = true
		response.Body.Message = err.Error()
		response.Status = http.StatusUnprocessableEntity
		log.Printf(err.Error())
	} else {
		err := validate.Struct(service)
		if err == nil {
			servicesQueue.Publish(body)
			response.Body.Message = http.StatusText(http.StatusAccepted)
			response.Status = http.StatusAccepted
			log.Printf("Accepted: %s", string(body))
		} else {
			response.Body.Error = true
			response.Body.Message = err.Error()
			response.Status = http.StatusBadRequest
			log.Printf(err.Error())
		}
	}

	response.Write()
}

Set accepted status when successfully published.


// Package sockets provides helper functions to create and configure Unix or TCP sockets.
package sockets

import (
	"errors"
	"net"
	"net/http"
	"time"
)

// Why 32? See https://github.com/docker/docker/pull/8035.
const defaultTimeout = 32 * time.Second

// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system.
var ErrProtocolNotAvailable = errors.New("protocol not available")

// ConfigureTransport configures the specified Transport according to the
// specified proto and addr.
// If the proto is unix (using a unix socket to communicate) or npipe the
// compression is disabled.
func ConfigureTransport(tr *http.Transport, proto, addr string) error {
	switch proto {
	case "unix":
		return configureUnixTransport(tr, proto, addr)
	case "npipe":
		return configureNpipeTransport(tr, proto, addr)
	default:
		tr.Proxy = http.ProxyFromEnvironment
		dialer, err := DialerFromEnvironment(&net.Dialer{
			Timeout: defaultTimeout,
		})
		if err != nil {
			return err
		}
		tr.DialContext = dialer.DialContext
	}
	return nil
}

// Package sockets provides helper functions to create and configure Unix or TCP sockets.
package sockets

import (
	"errors"
	"net"
	"net/http"
	"time"
)

const defaultTimeout = 10 * time.Second

// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system.
var ErrProtocolNotAvailable = errors.New("protocol not available")

// ConfigureTransport configures the specified Transport according to the
// specified proto and addr.
// If the proto is unix (using a unix socket to communicate) or npipe the
// compression is disabled.
func ConfigureTransport(tr *http.Transport, proto, addr string) error {
	switch proto {
	case "unix":
		return configureUnixTransport(tr, proto, addr)
	case "npipe":
		return configureNpipeTransport(tr, proto, addr)
	default:
		tr.Proxy = http.ProxyFromEnvironment
		dialer, err := DialerFromEnvironment(&net.Dialer{
			Timeout: defaultTimeout,
		})
		if err != nil {
			return err
		}
		tr.DialContext = dialer.DialContext
	}
	return nil
}

Reduce default connection time to 10s (from 32s)


package henchman

import (
	"testing"
)

func TestPrepareTask(t *testing.T) {
	task := Task{"fake-uuid", "The {{ vars.variable1 }}", "The {{ vars.variable2 }}", false}
	vars := make(TaskVars)
	vars["variable1"] = "foo"
	vars["variable2"] = "bar"
	task.Prepare(&vars)
	if task.Name != "The foo" {
		t.Errorf("Template execution for Task.Name failed. Got - %s\n", task.Name)
	}
	if task.Action != "The bar" {
		t.Errorf("Template execution for Task.Action failed. Got - %s\n", task.Action)
	}
}

package henchman

import (
	"testing"
)

func TestPrepareTask(t *testing.T) {
	task := Task{"fake-uuid", "The {{ vars.variable1 }}", "{{ vars.variable2 }}:{{ machine.Hostname }}", false}
	machine := Machine{"foobar", nil}

	vars := make(TaskVars)
	vars["variable1"] = "foo"
	vars["variable2"] = "bar"
	task.prepare(&vars, &machine)

	if task.Name != "The foo" {
		t.Errorf("Template execution for Task.Name failed. Got - %s\n", task.Name)
	}
	if task.Action != "bar:foobar" {
		t.Errorf("Template execution for Task.Action failed. Got - %s\n", task.Action)
	}
}

Test cases for the machine context


// +build linux

package overlayutils // import "github.com/docker/docker/daemon/graphdriver/overlayutils"

import (
	"fmt"

	"github.com/docker/docker/daemon/graphdriver"
)

// ErrDTypeNotSupported denotes that the backing filesystem doesn't support d_type.
func ErrDTypeNotSupported(driver, backingFs string) error {
	msg := fmt.Sprintf("%s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.", driver, backingFs)
	if backingFs == "xfs" {
		msg += " Reformat the filesystem with ftype=1 to enable d_type support."
	}
	msg += " Backing filesystems without d_type support are not supported."

	return graphdriver.NotSupportedError(msg)
}

// +build linux

package overlayutils // import "github.com/docker/docker/daemon/graphdriver/overlayutils"

import (
	"fmt"

	"github.com/docker/docker/daemon/graphdriver"
)

// ErrDTypeNotSupported denotes that the backing filesystem doesn't support d_type.
func ErrDTypeNotSupported(driver, backingFs string) error {
	msg := fmt.Sprintf("%s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.", driver, backingFs)
	if backingFs == "xfs" {
		msg += " Reformat the filesystem with ftype=1 to enable d_type support."
	}

	if backingFs == "extfs" {
		msg += " Reformat the filesystem (or use tune2fs) with -O filetype flag to enable d_type support."
	}

	msg += " Backing filesystems without d_type support are not supported."

	return graphdriver.NotSupportedError(msg)
}

Add additional message when backendfs is extfs without d_type support


package litetunes

import (
	"errors"
	"fmt"
)

// MemoryQueue is an in-memory implementation of the Queue interface
type MemoryQueue struct {
	tracks []*Track
}

// NewMemoryQueue constructs a new MemoryQueue to use
func NewMemoryQueue() *MemoryQueue {
	return &MemoryQueue{tracks: []*Track{}}
}

// Queue adds a new track to the queue
func (m *MemoryQueue) Queue(t *Track) error {
	if curlen := len(m.tracks); cap(m.tracks) == curlen {
		bigger := make([]*Track, curlen, 2*curlen+1)
		copy(bigger, m.tracks)
		m.tracks = bigger
	}

	m.tracks = append(m.tracks, t)

	return nil
}

// Dequeue removes the track at the head of the queue
func (m *MemoryQueue) Dequeue() (*Track, error) {
	c := m.Count()

	if c < 1 {
		return nil, errors.New("No track to dequeue")
	}

	t := m.tracks[0]
	if t == nil {
		for k, v := range m.tracks {
			fmt.Printf("%d = %#v\n", k, v)
		}
	}

	m.tracks = m.tracks[1:]

	return t, nil
}

// Count returns the number of tracks in the queue
func (m *MemoryQueue) Count() int {
	return len(m.tracks)
}

package litetunes

import (
	"errors"
	"fmt"
)

// MemoryQueue is an in-memory implementation of the Queue interface
type MemoryQueue struct {
	tracks []*Track
}

// NewMemoryQueue constructs a new MemoryQueue to use
func NewMemoryQueue() *MemoryQueue {
	return &MemoryQueue{tracks: []*Track{}}
}

// Queue adds a new track to the queue
func (m *MemoryQueue) Queue(t *Track) error {
	if curlen := m.Count(); cap(m.tracks) == curlen {
		bigger := make([]*Track, curlen, 2*curlen+1)
		copy(bigger, m.tracks)
		m.tracks = bigger
	}

	m.tracks = append(m.tracks, t)

	return nil
}

// Dequeue removes the track at the head of the queue
func (m *MemoryQueue) Dequeue() (*Track, error) {
	c := m.Count()

	if c < 1 {
		return nil, errors.New("No track to dequeue")
	}

	t := m.tracks[0]
	if t == nil {
		for k, v := range m.tracks {
			fmt.Printf("%d = %#v\n", k, v)
		}
	}

	m.tracks = m.tracks[1:]

	return t, nil
}

// Count returns the number of tracks in the queue
func (m *MemoryQueue) Count() int {
	return len(m.tracks)
}

Use m.Count() even inside pointer-struct functions


package main

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/docopt/docopt-go"

	"github.com/anacrolix/torrent/metainfo"
)

var (
	builtinAnnounceList = [][]string{
		{"udp://tracker.openbittorrent.com:80"},
		{"udp://tracker.publicbt.com:80"},
		{"udp://tracker.istole.it:6969"},
	}
)

func main() {
	opts, err := docopt.Parse("Usage: torrent-create <root>", nil, true, "", true)
	if err != nil {
		panic(err)
	}
	root := opts["<root>"].(string)
	mi := metainfo.MetaInfo{
		AnnounceList: builtinAnnounceList,
	}
	mi.SetDefaults()
	err = mi.Info.BuildFromFilePath(root)
	if err != nil {
		log.Fatal(err)
	}
	err = mi.Info.GeneratePieces(func(fi metainfo.FileInfo) (io.ReadCloser, error) {
		return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
	})
	if err != nil {
		log.Fatalf("error generating pieces: %s", err)
	}
	err = mi.Write(os.Stdout)
	if err != nil {
		log.Fatal(err)
	}
}

package main

import (
	"log"
	"os"

	"github.com/anacrolix/tagflag"

	"github.com/anacrolix/torrent/metainfo"
)

var (
	builtinAnnounceList = [][]string{
		{"udp://tracker.openbittorrent.com:80"},
		{"udp://tracker.publicbt.com:80"},
		{"udp://tracker.istole.it:6969"},
	}
)

func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	var args struct {
		tagflag.StartPos
		Root string
	}
	tagflag.Parse(&args, tagflag.Description("Creates a torrent metainfo for the file system rooted at ROOT, and outputs it to stdout."))
	mi := metainfo.MetaInfo{
		AnnounceList: builtinAnnounceList,
	}
	mi.SetDefaults()
	err := mi.Info.BuildFromFilePath(args.Root)
	if err != nil {
		log.Fatal(err)
	}
	err = mi.Write(os.Stdout)
	if err != nil {
		log.Fatal(err)
	}
}

Tidy up flags and remove redundant function calls


// +build linux freebsd solaris

package builtin

import (
	"fmt"

	"github.com/docker/libnetwork/datastore"
	"github.com/docker/libnetwork/ipam"
	"github.com/docker/libnetwork/ipamapi"
	"github.com/docker/libnetwork/ipamutils"
)

// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error {
	var (
		ok                bool
		localDs, globalDs datastore.DataStore
	)

	if l != nil {
		if localDs, ok = l.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect local datastore passed to built-in ipam init")
		}
	}

	if g != nil {
		if globalDs, ok = g.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect global datastore passed to built-in ipam init")
		}
	}

	ipamutils.InitNetworks()

	a, err := ipam.NewAllocator(localDs, globalDs)
	if err != nil {
		return err
	}

	return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a)
}

// +build linux freebsd solaris darwin

package builtin

import (
	"fmt"

	"github.com/docker/libnetwork/datastore"
	"github.com/docker/libnetwork/ipam"
	"github.com/docker/libnetwork/ipamapi"
	"github.com/docker/libnetwork/ipamutils"
)

// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error {
	var (
		ok                bool
		localDs, globalDs datastore.DataStore
	)

	if l != nil {
		if localDs, ok = l.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect local datastore passed to built-in ipam init")
		}
	}

	if g != nil {
		if globalDs, ok = g.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect global datastore passed to built-in ipam init")
		}
	}

	ipamutils.InitNetworks()

	a, err := ipam.NewAllocator(localDs, globalDs)
	if err != nil {
		return err
	}

	return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a)
}

Fix ipams builtin package for darwin


package sudoku

type CellList []*Cell

type intList []int

func (self CellList) SameRow() bool {
	if len(self) == 0 {
		return true
	}
	row := self[0].Row
	for _, cell := range self {
		if cell.Row != row {
			return false
		}
	}
	return true
}

func (self CellList) CollectNums(fetcher func(*Cell) int) intList {
	var result intList
	for _, cell := range self {
		result = append(result, fetcher(cell))
	}
	return result
}

func (self intList) Same() bool {
	if len(self) == 0 {
		return true
	}
	target := self[0]
	for _, num := range self {
		if target != num {
			return false
		}
	}
	return true
}

package sudoku

type CellList []*Cell

type intList []int

func (self CellList) SameRow() bool {
	return self.CollectNums(func(cell *Cell) int {
		return cell.Row
	}).Same()

}

func (self CellList) CollectNums(fetcher func(*Cell) int) intList {
	var result intList
	for _, cell := range self {
		result = append(result, fetcher(cell))
	}
	return result
}

func (self intList) Same() bool {
	if len(self) == 0 {
		return true
	}
	target := self[0]
	for _, num := range self {
		if target != num {
			return false
		}
	}
	return true
}

Reimplement samerow in terms of CollectNums.


package config

import (
	"code.google.com/p/gcfg"
	"path/filepath"
)

type Config struct {
	RabbitMq struct {
		Host        string
		Username    string
		Password    string
		Port        string
		Vhost       string
		Queue       string
		Compression bool
	}
	Prefetch struct {
		Count     int
		Global    bool
	}
	Exchange struct {
		Name		string
		Autodelete	bool
		Type		string
		Durable		bool
	}
	Logs struct {
		Error string
		Info  string
	}
}

func LoadAndParse(location string) (*Config, error) {
	if !filepath.IsAbs(location) {
		location, err := filepath.Abs(location)

		if err != nil {
			return nil, err
		}

		location = location
	}

	cfg := Config{}
	if err := gcfg.ReadFileInto(&cfg, location); err != nil {
		return nil, err
	}

	return &cfg, nil
}

package config

import (
	"gopkg.in/gcfg.v1"
	"path/filepath"
)

type Config struct {
	RabbitMq struct {
		Host        string
		Username    string
		Password    string
		Port        string
		Vhost       string
		Queue       string
		Compression bool
	}
	Prefetch struct {
		Count     int
		Global    bool
	}
	Exchange struct {
		Name		string
		Autodelete	bool
		Type		string
		Durable		bool
	}
	Logs struct {
		Error string
		Info  string
	}
}

func LoadAndParse(location string) (*Config, error) {
	if !filepath.IsAbs(location) {
		location, err := filepath.Abs(location)

		if err != nil {
			return nil, err
		}

		location = location
	}

	cfg := Config{}
	if err := gcfg.ReadFileInto(&cfg, location); err != nil {
		return nil, err
	}

	return &cfg, nil
}

Update new repository for gcfg


package mfsr

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/ipfs/go-ipfs/thirdparty/assert"
)

func testVersionFile(v string, t *testing.T) (rp RepoPath) {
	name, err := ioutil.TempDir("", v)
	if err != nil {
		t.Fatal(err)
	}
	rp = RepoPath(name)
	return rp
}

func TestVersion(t *testing.T) {
	rp := RepoPath("")
	_, err := rp.Version()
	assert.Err(err, t, "Should throw an error when path is bad,")

	rp = RepoPath("/path/to/nowhere")
	_, err = rp.Version()
	if !os.IsNotExist(err) {
		t.Fatalf("Should throw an `IsNotExist` error when file doesn't exist: %v", err)
	}

	rp = testVersionFile("4", t)
	_, err = rp.Version()
	assert.Err(err, t, "Bad VersionFile")

	assert.Nil(rp.WriteVersion(4), t, "Trouble writing version")

	assert.Nil(rp.CheckVersion(4), t, "Trouble checking the verion")

	assert.Err(rp.CheckVersion(1), t, "Should throw an error for the wrong version.")
}

package mfsr

import (
	"io/ioutil"
	"os"
	"strconv"
	"testing"

	"github.com/ipfs/go-ipfs/thirdparty/assert"
)

func testVersionFile(v string, t *testing.T) (rp RepoPath) {
	name, err := ioutil.TempDir("", v)
	if err != nil {
		t.Fatal(err)
	}
	rp = RepoPath(name)
	return rp
}

func TestVersion(t *testing.T) {
	rp := RepoPath("")
	_, err := rp.Version()
	assert.Err(err, t, "Should throw an error when path is bad,")

	rp = RepoPath("/path/to/nowhere")
	_, err = rp.Version()
	if !os.IsNotExist(err) {
		t.Fatalf("Should throw an `IsNotExist` error when file doesn't exist: %v", err)
	}

	fsrepoV := 5

	rp = testVersionFile(strconv.Itoa(fsrepoV), t)
	_, err = rp.Version()
	assert.Err(err, t, "Bad VersionFile")

	assert.Nil(rp.WriteVersion(fsrepoV), t, "Trouble writing version")

	assert.Nil(rp.CheckVersion(fsrepoV), t, "Trouble checking the verion")

	assert.Err(rp.CheckVersion(1), t, "Should throw an error for the wrong version.")
}

Update Version to reflect fsrepo change


package algoliasearch

func checkGenerateSecuredAPIKey(params Map) error {
	if err := checkQuery(params,
		"restrictIndices",
		"restrictSources",
		"userToken",
		"validUntil",
	); err != nil {
		return err
	}

	for k, v := range params {
		switch k {
		case "restrictIndices", "restrictSources", "userToken":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "validUntil":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

func checkKey(params Map) error {
	for k, v := range params {
		switch k {
		case "acl", "indexes", "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		case "description", "queryParameters":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

package algoliasearch

func checkGenerateSecuredAPIKey(params Map) error {
	if err := checkQuery(params,
		"restrictIndices",
		"restrictSources",
		"userToken",
		"validUntil",
		"referers",
	); err != nil {
		return err
	}

	for k, v := range params {
		switch k {
		case "restrictIndices", "restrictSources", "userToken":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "validUntil":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		case "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		default:
			// OK
		}
	}

	return nil
}

func checkKey(params Map) error {
	for k, v := range params {
		switch k {
		case "acl", "indexes", "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		case "description", "queryParameters":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

Enable `referers` as parameter of GenerateSecuredAPIKey


package irc

import "testing"

func TestMessageString(t *testing.T) {
	type tcase struct {
		msg Message;
		expected string;
	};
	cases := []tcase {
		tcase {
			Message{Command: "command", Params: []string{}},
			"command"
		},
		tcase {
			Message{Command: "command", Params: []string{"one"}},
			"command :one"
		},
		tcase {
			Message{Command: "command", Params: []string{"one", "two"}},
			"command one :two"
		},
		tcase {
			Message{"prefix", "command", []string{"one", "two", "three four"}},
			":prefix command one two :three four"
		},
		tcase {
			Message{Prefix: "prefix", Command: "command"},
			"asdf"
		},
	};

	for i, tc := range cases {
		s := tc.msg.String();
		if s != tc.expected {
			t.Errorf("Case %d: expected \"%s\", got \"%s\"", i, tc.expected, s)
		}
	}
}

package irc

import "testing"

func TestMessageString(t *testing.T) {
	type tcase struct {
		msg Message;
		expected string;
	};
	cases := []tcase {
		tcase {
			Message{Command: "command", Params: []string{}},
			"command"
		},
		tcase {
			Message{Command: "command", Params: []string{"one"}},
			"command :one"
		},
		tcase {
			Message{Command: "command", Params: []string{"one", "two"}},
			"command one :two"
		},
		tcase {
			Message{"prefix", "command", []string{"one", "two", "three four"}},
			":prefix command one two :three four"
		},
	};

	for i, tc := range cases {
		s := tc.msg.String();
		if s != tc.expected {
			t.Errorf("Case %d: expected \"%s\", got \"%s\"", i, tc.expected, s)
		}
	}
}

Remove dummy failure test case


package models

import (
	"log"

	"github.com/gobuffalo/envy"
	"github.com/gobuffalo/packr/v2"
	"github.com/gobuffalo/pop"
	"github.com/nleof/goyesql"
)

// DB is a connection to your database to be used
// throughout your application.
var DB *pop.Connection

// Q is a map of SQL queries
var Q goyesql.Queries

func init() {
	var err error
	env := envy.Get("GO_ENV", "development")
	DB, err = pop.Connect(env)
	if err != nil {
		log.Fatal(err)
	}
	pop.Debug = env == "development"
	box := packr.New("./sql", "./sql")
	sql, err := box.MustBytes("queries.sql")
	if err != nil {
		log.Fatal(err)
	}
	Q = goyesql.MustParseBytes(sql)
}

package models

import (
	"log"

	"github.com/gobuffalo/envy"
	"github.com/gobuffalo/packr/v2"
	"github.com/gobuffalo/pop"
	"github.com/nleof/goyesql"
)

// DB is a connection to your database to be used
// throughout your application.
var DB *pop.Connection

// Q is a map of SQL queries
var Q goyesql.Queries

func init() {
	var err error
	env := envy.Get("GO_ENV", "development")
	DB, err = pop.Connect(env)
	if err != nil {
		log.Fatal(err)
	}
	pop.Debug = env == "development"
	box := packr.New("./sql", "./sql")
	sql, err := box.Find("queries.sql")
	if err != nil {
		log.Fatal(err)
	}
	Q = goyesql.MustParseBytes(sql)
}

Fix deprecated API warning in buffalo packr


package bot

import (
	"strings"

	"github.com/arachnist/gorepost/irc"
)

func ping(output chan irc.Message, msg irc.Message) {
	if strings.Split(msg.Trailing, " ")[0] != ":ping" {
		return
	}

	output <- irc.Message{
		Command:  "PRIVMSG",
		Params:   []string{msg.Prefix.Name},
		Trailing: "pingity pong",
	}
}

func init() {
	AddCallback("PRIVMSG", "ping", ping)
}

package bot

import (
	"strings"

	"github.com/arachnist/gorepost/irc"
)

func ping(output chan irc.Message, msg irc.Message) {
	if strings.Split(msg.Trailing, " ")[0] != ":ping" {
		return
	}

	output <- irc.Message{
		Command:  "PRIVMSG",
		Params:   []string{msg.Prefix.Name},
		Trailing: "pingity pong",
	}
}

func init() {
	AddCallback("PRIVMSG", "msgping", ping)
}

Use a different identifier for user :ping command


package p01

import (
	"strconv"
	"fmt"
)

func Solve(input string) (string, string) {
	return solve(input, 1), solve(input, len(input)/2)
}

func solve(input string, lookahead int) string {
	sum := 0

	for i := 0; i < len(input); i += 1 {
		if input[i] == input[(i+lookahead)%len(input)] {
			v, err := strconv.ParseInt(string(input[i]), 10, 64)
			if err != nil {
				panic("Cannot parse " + err.Error())
			}
			sum += int(v)
		}
	}
	return fmt.Sprintf("%d", sum)
}

package p01

import (
	"fmt"
	"common"
)

func Solve(input string) (string, string) {
	return solve(input, 1), solve(input, len(input)/2)
}

func solve(input string, lookahead int) string {
	sum := 0
	for i := 0; i < len(input); i += 1 {
		if input[i] == input[(i+lookahead)%len(input)] {
			sum += int(common.ToIntOrPanic(string(input[i])))
		}
	}
	return fmt.Sprintf("%d", sum)
}

Make 2017.01 shorter by using custom parse function.


package main

import (
	"github.com/sean-duffy/xlsx"
	"strconv"
)

func main() {

	c := []xlsx.Column{
		xlsx.Column{Name: "Col1", Width: 10},
		xlsx.Column{Name: "Col2", Width: 10},
	}

	sh := xlsx.NewSheetWithColumns(c, "MySheet")

	for i := 0; i < 10; i++ {

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: strconv.Itoa(i + 1),
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}

		sh.AppendRow(r)
	}

	err := sh.SaveToFile("test.xlsx")
	_ = err
}

package main

import (
	"github.com/sean-duffy/xlsx"
	"strconv"
)

func main() {

	c := []xlsx.Column{
		xlsx.Column{Name: "Col1", Width: 10},
		xlsx.Column{Name: "Col2", Width: 10},
	}

	sh := xlsx.NewSheetWithColumns(c)
	sh.Title = "MySheet"

	for i := 0; i < 10; i++ {

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: strconv.Itoa(i + 1),
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}

		sh.AppendRow(r)
	}

	err := sh.SaveToFile("test.xlsx")
	_ = err
}

Change example to conform to API


// Copyright 2010 The draw2d Authors. All rights reserved.
// created: 21/11/2010 by Laurent Le Goff

package draw2d

type Path interface {
	// Return the current point of the path
	LastPoint() (x, y float64)
	// Create a new subpath that start at the specified point
	MoveTo(x, y float64)
	// Create a new subpath that start at the specified point
	// relative to the current point
	RMoveTo(dx, dy float64)
	// Add a line to the current subpath
	LineTo(x, y float64)
	// Add a line to the current subpath
	// relative to the current point
	RLineTo(dx, dy float64)

	QuadCurveTo(cx, cy, x, y float64)
	RQuadCurveTo(dcx, dcy, dx, dy float64)
	CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64)
	RCubicCurveTo(dcx1, dcy1, dcx2, dcy2, dx, dy float64)
	ArcTo(cx, cy, rx, ry, startAngle, angle float64)
	RArcTo(dcx, dcy, rx, ry, startAngle, angle float64)
	Close()
}

// Copyright 2010 The draw2d Authors. All rights reserved.
// created: 21/11/2010 by Laurent Le Goff

package draw2d

// PathBuilder define method that create path
type Path interface {
	// Return the current point of the current path
	LastPoint() (x, y float64)

	// MoveTo start a new path at (x, y) position
	MoveTo(x, y float64)

	// LineTo add a line to the current path
	LineTo(x, y float64)

	// QuadCurveTo add a quadratic curve to the current path
	QuadCurveTo(cx, cy, x, y float64)

	// CubicCurveTo add a cubic bezier curve to the current path
	CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64)

	// ArcTo add an arc to the path
	ArcTo(cx, cy, rx, ry, startAngle, angle float64)

	// Close the current path
	Close()
}

Remove unecessary method in Path interface


package uploader

import (
	"fmt"
	"os"
	"launchpad.net/goamz/aws"
	"launchpad.net/goamz/s3"
)

const (
	defaultS3BufferSize = 5 * 1024 * 1024
)

type S3 struct {
	Bucket     *s3.Bucket
	BufferSize int64
}

func (s3Uploader *S3) Init() error {
	s3Region := os.Getenv("S3_REGION")
	region, ok := aws.Regions[s3Region]
	if !ok {
		return fmt.Errorf("Fail to find S3 region %s\n", s3Region)
	}

	auth := aws.Auth{AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"), SecretKey: os.Getenv("AWS_SECRET_KEY")}
	s := s3.New(auth, region)
	s3Uploader.Bucket = s.Bucket(os.Getenv("S3_BUCKET"))
	s3Uploader.BufferSize = defaultS3BufferSize

	return nil
}

func (s3Uploader *S3) Upload(destPath, contentType string, f *os.File) error {
	writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.AuthenticatedRead)
	if err != nil {
		return err
	}

	parts, err := writer.PutAll(f, s3Uploader.BufferSize)
	if err != nil {
		return err
	}

	return writer.Complete(parts)
}

package uploader

import (
	"fmt"
	"os"

	"launchpad.net/goamz/aws"
	"launchpad.net/goamz/s3"
)

const (
	defaultS3BufferSize = 5 * 1024 * 1024
)

type S3 struct {
	Bucket     *s3.Bucket
	BufferSize int64
}

func (s3Uploader *S3) Init() error {
	s3Region := os.Getenv("S3_REGION")
	region, ok := aws.Regions[s3Region]
	if !ok {
		return fmt.Errorf("Fail to find S3 region %s\n", s3Region)
	}

	auth := aws.Auth{AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"), SecretKey: os.Getenv("AWS_SECRET_KEY")}
	s := s3.New(auth, region)
	s3Uploader.Bucket = s.Bucket(os.Getenv("S3_BUCKET"))
	s3Uploader.BufferSize = defaultS3BufferSize

	return nil
}

func (s3Uploader *S3) Upload(destPath, contentType string, f *os.File) error {
	writer, err := s3Uploader.Bucket.InitMulti(destPath, contentType, s3.PublicRead)
	if err != nil {
		return err
	}

	parts, err := writer.PutAll(f, s3Uploader.BufferSize)
	if err != nil {
		return err
	}

	return writer.Complete(parts)
}

Change upload file to public read


package gstrings

import (
	"github.com/wallclockbuilder/testify/assert"
	"testing"
)

func TestSize(t *testing.T) {
	assert := assert.New(t)
	assert.Equal(5, Size("hello"))
}

package gstrings

import (
	"fmt"
	"github.com/wallclockbuilder/testify/assert"
	"testing"
)

func ExampleSize(){
	fmt.Println(Size("hello"))
	// Output: 5
}

func TestSize(t *testing.T) {
	assert := assert.New(t)
	assert.Equal(5, Size("hello"))
}

Add documentation example for Size()


package ActiveObject

import (
	"errors"
	"time"
)

//ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval
type ActiveObjectWithInterval struct {
	workerFunction func(params ...interface{})
	ticker         *time.Ticker
	duration       time.Duration
	doneChannel    chan bool
}

func NewActiveObjectWithInterval(duration time.Duration) *ActiveObjectWithInterval {

	return &ActiveObjectWithInterval{duration: duration, doneChannel: make(chan bool)}
}

func (activeObject *ActiveObjectWithInterval) SetWorkerFunction(workerFunction func(params ...interface{})) {
	activeObject.workerFunction = workerFunction
}

func (activeObject *ActiveObjectWithInterval) Run(params ...interface{}) error {
	if activeObject.ticker != nil {
		return errors.New("Already running")
	}

	activeObject.ticker = time.NewTicker(activeObject.duration)

	go func() {
		for {
			select {
			case <-activeObject.ticker.C:
				activeObject.workerFunction(params)

			case <-activeObject.doneChannel:
				return
			}
		}
	}()

	return nil
}

func (activeObject *ActiveObjectWithInterval) ForceStop() {
	activeObject.doneChannel <- true
}

package ActiveObject

import (
	"errors"
	"time"
)

//ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval
type ActiveObjectWithInterval struct {
	workerFunction func(params ...interface{})
	ticker         *time.Ticker
	duration       time.Duration
	doneChannel    chan bool
}

func NewActiveObjectWithInterval(duration time.Duration) *ActiveObjectWithInterval {

	return &ActiveObjectWithInterval{duration: duration, doneChannel: make(chan bool)}
}

func (activeObject *ActiveObjectWithInterval) SetWorkerFunction(workerFunction func(params ...interface{})) {
	activeObject.workerFunction = workerFunction
}

func (activeObject *ActiveObjectWithInterval) Run(params ...interface{}) error {
	if activeObject.ticker != nil {
		return errors.New("Already running")
	}

	activeObject.ticker = time.NewTicker(activeObject.duration)

	go func() {
		for {
			select {
			case <-activeObject.ticker.C:
				activeObject.workerFunction(params)

			case <-activeObject.doneChannel:
				activeObject.ticker.Stop()
				return
			}
		}
	}()

	return nil
}

func (activeObject *ActiveObjectWithInterval) ForceStop() {
	activeObject.doneChannel <- true
}

Make sure the ticker stopped when ActiveObject.ForceStop() called


package dragon

import (
	"bytes"
	"strings"
	"testing"
)

func TestOut(t *testing.T) {
	libChan := make(chan lib)

	go func() {
		libChan <- lib{
			pkg:    "dragon",
			object: "Imports",
			path:   "github.com/monochromegane/dragon-imports",
		}
		close(libChan)
	}()

	expect := `// AUTO-GENERATED BY dragon-imports

package imports

var stdlib = map[string]map[string]bool{`

	buf := &bytes.Buffer{}
	out(libChan, buf)

	actual := buf.String()
	if !strings.HasPrefix(actual, expect) {
		t.Errorf("out should have prefix\n%s\n  but\n%s", expect, actual)
	}

	contains := []string{
		`"github.com/monochromegane/dragon-imports":map[string]bool{"Imports":true}`,
		`"unsafe":map[string]bool{`,
	}

	for _, s := range contains {
		if !strings.Contains(actual, s) {
			t.Errorf("out should contain \n%s\n  but\n%s", s, actual)
		}
	}
}

package dragon

import (
	"bytes"
	"strings"
	"testing"
)

func TestOut(t *testing.T) {
	libChan := make(chan lib)

	go func() {
		libChan <- lib{
			object: "Imports",
			path:   "github.com/monochromegane/dragon-imports",
		}
		libChan <- lib{
			object: "Imports",
			path:   "github.com/someone/dragon-imports",
		}
		close(libChan)
	}()

	expect := `// AUTO-GENERATED BY dragon-imports

package imports

var stdlib = map[string]map[string]bool{`

	buf := &bytes.Buffer{}
	out(libChan, buf)

	actual := buf.String()
	if !strings.HasPrefix(actual, expect) {
		t.Errorf("out should have prefix\n%s\n  but\n%s", expect, actual)
	}

	contains := []string{
		`"github.com/monochromegane/dragon-imports":map[string]bool{"Imports":true}`,
		`"github.com/someone/dragon-imports":map[string]bool{"Imports":true}`,
		`"unsafe":map[string]bool{`,
	}

	for _, s := range contains {
		if !strings.Contains(actual, s) {
			t.Errorf("out should contain \n%s\n  but\n%s", s, actual)
		}
	}
}

Add duplicated package pattern test.


package common

import (
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func listEC2Regions() []string {
	var regions []string
	// append regions that are not part of autogenerated list
	regions = append(regions, "us-gov-west-1", "cn-north-1", "cn-northwest-1")

	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))

	ec2conn := ec2.New(sess)
	resultRegions, _ := ec2conn.DescribeRegions(nil)
	for _, region := range resultRegions.Regions {
		regions = append(regions, *region.RegionName)
	}

	return regions
}

// ValidateRegion returns true if the supplied region is a valid AWS
// region and false if it's not.
func ValidateRegion(region string) bool {
	for _, valid := range listEC2Regions() {
		if region == valid {
			return true
		}
	}
	return false
}

package common

import (
	"flag"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func listEC2Regions() []string {
	var regions []string
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))

	ec2conn := ec2.New(sess)
	resultRegions, _ := ec2conn.DescribeRegions(nil)
	for _, region := range resultRegions.Regions {
		regions = append(regions, *region.RegionName)
	}

	return regions
}

// ValidateRegion returns true if the supplied region is a valid AWS
// region and false if it's not.
func ValidateRegion(region string) bool {

	// To pass tests
	if v := flag.Lookup("test.v"); v != nil || v.Value.String() == "true" {
		regions := []string{
			"us-east-1",
			"us-east-2",
			"us-west-1",
		}
		for _, valid := range regions {
			if region == valid {
				return true
			}
		}
	}

	// Normal run
	for _, valid := range listEC2Regions() {
		if region == valid {
			return true
		}
	}
	return false
}

Modify Validate Region for test cases


package models

import (
  "path"
  "io/ioutil"
  "os"
  "encoding/json"
  "ghighlighter/utils"
)

type GhHighlights struct {
  items []GhHighlight
}

func (m *GhHighlights) GetAll() []GhHighlight {
  m.Read()
  return m.items
}

func highlightsFilePath() string {
  return path.Join(utils.DataDir(), "highlights.json")
}

func (m *GhHighlights) Read() {
  data, error := ioutil.ReadFile(highlightsFilePath())
  if error != nil && !os.IsExist(error) {
    m.Write()
    m.Read()
  }

  var tmpItems []GhHighlight
  json.Unmarshal(data, &tmpItems)

  m.items = make([]GhHighlight, len(tmpItems))
  for _, highlight := range tmpItems {
    m.items = append(m.items, highlight)
  }
}

func (m *GhHighlights) Write() {
  if m.items == nil {
    m.items = make([]GhHighlight, 0)
  }

  data, error := json.Marshal(m.items)
  if error != nil { return }

  error = ioutil.WriteFile(highlightsFilePath(), data, 0755)
}

func Highlights() *GhHighlights {
  highlights := &GhHighlights{}
  highlights.Read()
  return highlights
}

package models

import (
  "path"
  "io/ioutil"
  "os"
  "encoding/json"
  "ghighlighter/utils"
)

type GhHighlights struct {
  Items []GhHighlight
}

func highlightsFilePath() string {
  return path.Join(utils.DataDir(), "highlights.json")
}

func (m *GhHighlights) Read() {
  data, error := ioutil.ReadFile(highlightsFilePath())
  if error != nil && !os.IsExist(error) {
    m.Write()
    m.Read()
  }

  var tmpItems []GhHighlight
  json.Unmarshal(data, &tmpItems)

  for _, highlight := range tmpItems {
    m.Items = append(m.Items, highlight)
  }
}

func (m *GhHighlights) Write() {
  if m.Items == nil {
    m.Items = make([]GhHighlight, 0)
  }

  data, error := json.Marshal(m.Items)
  if error != nil { return }

  error = ioutil.WriteFile(highlightsFilePath(), data, 0755)
}

func Highlights() *GhHighlights {
  highlights := &GhHighlights{}
  highlights.Read()
  return highlights
}

Remove Highlights.GetAll and make Items public


package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/labstack/echo"
	"github.com/labstack/gommon/log"
)

func main() {
	// Setup
	e := echo.New()
	e.Logger.SetLevel(log.INFO)
	e.GET("/", func(c echo.Context) error {
		time.Sleep(5 * time.Second)
		return c.JSON(http.StatusOK, "OK")
	})

	// Start server
	go func() {
		if err := e.Start(":1323"); err != nil {
			e.Logger.Info("shutting down the server")
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 10 seconds.
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := e.Shutdown(ctx); err != nil {
		e.Logger.Fatal(err)
	}
}

package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/labstack/echo"
	"github.com/labstack/gommon/log"
)

func main() {
	// Setup
	e := echo.New()
	e.Logger.SetLevel(log.INFO)
	e.GET("/", func(c echo.Context) error {
		time.Sleep(5 * time.Second)
		return c.JSON(http.StatusOK, "OK")
	})

	// Start server
	go func() {
		if err := e.Start(":1323"); err != nil {
			e.Logger.Info("shutting down the server")
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 10 seconds.
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := e.Shutdown(ctx); err != nil {
		e.Logger.Fatal(err)
	}
}

Use buffered channel for graceful shutdown


// +build !linux,cgo

package lfs

import (
	"io"
)

func CloneFile(writer io.Writer, reader io.Reader) (bool, error) {
	return false, nil
}

// +build !linux !cgo

package lfs

import (
	"io"
)

func CloneFile(writer io.Writer, reader io.Reader) (bool, error) {
	return false, nil
}

Fix non linux with cgo build condition


package platforms

import (
	"reflect"
	"runtime"
	"testing"

	specs "github.com/opencontainers/image-spec/specs-go/v1"
)

func TestDefault(t *testing.T) {
	expected := specs.Platform{
		OS:           runtime.GOOS,
		Architecture: runtime.GOARCH,
	}
	p := DefaultSpec()
	if !reflect.DeepEqual(p, expected) {
		t.Fatalf("default platform not as expected: %#v != %#v", p, expected)
	}

	s := Default()
	if s != Format(p) {
		t.Fatalf("default specifier should match formatted default spec: %v != %v", s, p)
	}
}

package platforms

import (
	"reflect"
	"runtime"
	"testing"

	specs "github.com/opencontainers/image-spec/specs-go/v1"
)

func TestDefault(t *testing.T) {
	expected := specs.Platform{
		OS:           runtime.GOOS,
		Architecture: runtime.GOARCH,
		Variant:      cpuVariant,
	}
	p := DefaultSpec()
	if !reflect.DeepEqual(p, expected) {
		t.Fatalf("default platform not as expected: %#v != %#v", p, expected)
	}

	s := Default()
	if s != Format(p) {
		t.Fatalf("default specifier should match formatted default spec: %v != %v", s, p)
	}
}

Add Variant field to default test expected result


package main

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/fsbench"
	"os"
)

// Benchmark the read speed of the underlying block device for a given file.
func main() {
	pathname := "/"
	if len(os.Args) == 2 {
		pathname = os.Args[1]
	}
	bytesPerSecond, blocksPerSecond, err := fsbench.GetReadSpeed(pathname)
	if err != nil {
		fmt.Printf("Error! %s\n", err)
		return
	}
	fmt.Printf("speed=%d MiB/s ", bytesPerSecond>>20)
	if blocksPerSecond > 0 {
		fmt.Printf("%d blocks/s\n", blocksPerSecond)
	} else {
		fmt.Println("I/O accounting not available")
	}
}

package main

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/fsbench"
	"os"
)

// Benchmark the read speed of the underlying block device for a given file.
func main() {
	pathname := "/"
	if len(os.Args) == 2 {
		pathname = os.Args[1]
	}
	bytesPerSecond, blocksPerSecond, err := fsbench.GetReadSpeed(pathname)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error! %s\n", err)
		return
	}
	fmt.Printf("speed=%d MiB/s ", bytesPerSecond>>20)
	if blocksPerSecond > 0 {
		fmt.Printf("%d blocks/s\n", blocksPerSecond)
	} else {
		fmt.Println("I/O accounting not available")
	}
}

Change fsbench utility to write errors to stderr rather than stdout.


package exp12

import (
	"sync"

	"github.com/shurcooL/go/exp/13"
	"github.com/shurcooL/go/vcs"

	. "gist.github.com/7802150.git"
)

// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// rootPath -> *VcsState
var repos = make(map[string]*exp13.VcsState)
var reposLock sync.Mutex

type Directory struct {
	path string

	Repo *exp13.VcsState

	DepNode2
}

func (this *Directory) Update() {
	if vcs := vcs.New(this.path); vcs != nil {
		reposLock.Lock()
		if repo, ok := repos[vcs.RootPath()]; ok {
			this.Repo = repo
		} else {
			this.Repo = exp13.NewVcsState(vcs)
			repos[vcs.RootPath()] = this.Repo
		}
		reposLock.Unlock()
	}
}

func NewDirectory(path string) *Directory {
	this := &Directory{path: path}
	// No DepNode2I sources, so each instance can only be updated (i.e. initialized) once
	return this
}

package exp12

import (
	"sync"

	"github.com/shurcooL/go/exp/13"
	"github.com/shurcooL/go/vcs"

	. "gist.github.com/7802150.git"
)

// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// rootPath -> *VcsState
var repos = make(map[string]*exp13.VcsState)
var reposLock sync.Mutex

// TODO: Use FileUri or similar type instead of string for clean path to repo root.
// path -> *Directory
var directories = make(map[string]*Directory)
var directoriesLock sync.Mutex

type Directory struct {
	path string

	Repo *exp13.VcsState

	DepNode2
}

func (this *Directory) Update() {
	if vcs := vcs.New(this.path); vcs != nil {
		reposLock.Lock()
		if repo, ok := repos[vcs.RootPath()]; ok {
			this.Repo = repo
		} else {
			this.Repo = exp13.NewVcsState(vcs)
			repos[vcs.RootPath()] = this.Repo
		}
		reposLock.Unlock()
	}
}

func newDirectory(path string) *Directory {
	this := &Directory{path: path}
	// No DepNode2I sources, so each instance can only be updated (i.e. initialized) once
	return this
}

func LookupDirectory(path string) *Directory {
	directoriesLock.Lock()
	defer directoriesLock.Unlock()
	if dir := directories[path]; dir != nil {
		return dir
	} else {
		dir = newDirectory(path)
		directories[path] = dir
		return dir
	}
}

Replace NewDirectory() with LookupDirectory() that reuses *Directory for same path.


package store

// TypeGetter is a func used to determine the concrete type of a context or
// endpoint metadata by returning a pointer to an instance of the object
// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext)
type TypeGetter func() interface{}

// NamedTypeGetter is a TypeGetter associated with a name
type NamedTypeGetter struct {
	name       string
	typeGetter TypeGetter
}

// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
	return NamedTypeGetter{
		name:       name,
		typeGetter: getter,
	}
}

// Config is used to configure the metadata marshaler of the context store
type Config struct {
	contextType   TypeGetter
	endpointTypes map[string]TypeGetter
}

// SetEndpoint set an endpoint typing information
func (c Config) SetEndpoint(name string, getter TypeGetter) {
	c.endpointTypes[name] = getter
}

// NewConfig creates a config object
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
	res := Config{
		contextType:   contextType,
		endpointTypes: make(map[string]TypeGetter),
	}
	for _, e := range endpoints {
		res.endpointTypes[e.name] = e.typeGetter
	}
	return res
}

package store

// TypeGetter is a func used to determine the concrete type of a context or
// endpoint metadata by returning a pointer to an instance of the object
// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext)
type TypeGetter func() interface{}

// NamedTypeGetter is a TypeGetter associated with a name
type NamedTypeGetter struct {
	name       string
	typeGetter TypeGetter
}

// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
	return NamedTypeGetter{
		name:       name,
		typeGetter: getter,
	}
}

// Config is used to configure the metadata marshaler of the context store
type Config struct {
	contextType   TypeGetter
	endpointTypes map[string]TypeGetter
}

// SetEndpoint set an endpoint typing information
func (c Config) SetEndpoint(name string, getter TypeGetter) {
	c.endpointTypes[name] = getter
}

// ForeachEndpointType calls cb on every endpoint type registered with the Config
func (c Config) ForeachEndpointType(cb func(string, TypeGetter) error) error {
	for n, ep := range c.endpointTypes {
		if err := cb(n, ep); err != nil {
			return err
		}
	}
	return nil
}

// NewConfig creates a config object
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
	res := Config{
		contextType:   contextType,
		endpointTypes: make(map[string]TypeGetter),
	}
	for _, e := range endpoints {
		res.endpointTypes[e.name] = e.typeGetter
	}
	return res
}

Add a helper to iterate over all endpoint types in a context store


package util

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
)

func CallBrowser(url string) error {
	fmt.Fprintf(os.Stderr, "Running a browser to open %s...\r\n", url)

	var attr os.ProcAttr
	attr.Sys = &syscall.SysProcAttr{HideWindow: false}
	attr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}

	path, err := exec.LookPath("cmd")
	if err != nil {
		return err
	}
	// so on windows when you're using cmd you have to escape ampersands with the ^ character.
	// ¯\(º_o)/¯
	url = strings.Replace(url, "&", "^&", -1)
	proc, err := os.StartProcess(path, []string{path, "/C", "start", url }, &attr)
	if err != nil {

		return err
	}

	_, err = proc.Wait()
	return err
}

package util

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
)

func CallBrowser(url string) error {
	fmt.Fprintf(os.Stderr, "Running a browser to open %s...\r\n", url)

	var attr os.ProcAttr
	attr.Sys = &syscall.SysProcAttr{HideWindow: true}
	attr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}

	path, err := exec.LookPath("cmd")
	if err != nil {
		return err
	}
	// so on windows when you're using cmd you have to escape ampersands with the ^ character.
	// ¯\(º_o)/¯
	url = strings.Replace(url, "&", "^&", -1)
	proc, err := os.StartProcess(path, []string{path, "/C", "start", url}, &attr)
	if err != nil {

		return err
	}

	_, err = proc.Wait()
	return err
}

Set HideWindow: true for the cmd exe.


package orm_test

import (
	"fmt"
	"github.com/nerdzeu/nerdz-api/orm"
	"testing"
)

var user orm.User

func init() {
	err := user.New(1)
	if err != nil {
		panic(fmt.Sprintf("No error should happen when create existing user, but got: %+v", err))
	}
}

func TestGetContactInfo(t *testing.T) {
	info := user.GetContactInfo()
	if info == nil {
		t.Error("null info")
	}

	fmt.Printf("%v\n", info)
}

func TestGetPersonalInfo(t *testing.T) {
	info := user.GetContactInfo()
	if info == nil {
		t.Error("null info")
	}

	fmt.Printf("%v\n", info)
}

func TestGetBoardInfo(t *testing.T) {
	info := user.GetBoardInfo()
	if info == nil {
		t.Error("null info")
	}

	fmt.Printf("%v\n", info)
}

package orm_test

import (
	"fmt"
	"github.com/nerdzeu/nerdz-api/orm"
	"testing"
)

var user orm.User

func init() {
	err := user.New(1)
	if err != nil {
		panic(fmt.Sprintf("No error should happen when create existing user, but got: %+v", err))
	}
}

func TestGetContactInfo(t *testing.T) {
	info := user.GetContactInfo()
	if info == nil {
		t.Error("null info")
	}
}

func TestGetPersonalInfo(t *testing.T) {
	info := user.GetPersonalInfo()
	if info == nil {
		t.Error("null info")
	}

	fmt.Printf("Struct: %+v\nINTERESTES:", *info)
    for i, elem := range info.Interests {
        fmt.Printf("%d) %s\n",i,elem)
    }

    fmt.Println("Quotes")
    for i, elem := range info.Quotes {
        fmt.Printf("%d) %s\n",i,elem)
    }

}

func TestGetBoardInfo(t *testing.T) {
	info := user.GetBoardInfo()
	if info == nil {
		t.Error("null info")
	}

    // If whitelist is not empty, the output will be huge (if tested with -v flag)
	fmt.Printf("%+v\n", *info)
}

Add tests (check with -v flag)


// 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 btrees

// checkSymmetry returns true if the l binary
// tree is symmetric to the r binary tree.
func checkSymmetry(l, r *BTree) bool {
	switch {
	case l == nil && r == nil:
		return true
	case l != nil && r != nil:
		return l.Data == r.Data &&
			checkSymmetry(l.left, r.right) &&
			checkSymmetry(l.right, r.left)
	}
	return false
}

// IsSymmetric returns true if t is a symmetric binary tree.
func IsSymmetric(t *BTree) bool {
	if t == nil {
		return true
	}
	return checkSymmetry(t.left, t.right)
}

// 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 btrees

// IsSymmetric returns true if t is a symmetric binary tree.
func IsSymmetric(t *BTree) bool {
	if t == nil {
		return true
	}

	var checkSymmetry func(l, r *BTree) bool
	checkSymmetry = func(l, r *BTree) bool {
		switch {
		case l == nil && r == nil:
			return true
		case l != nil && r != nil:
			return l.Data == r.Data &&
				checkSymmetry(l.left, r.right) &&
				checkSymmetry(l.right, r.left)
		}
		return false
	}
	return checkSymmetry(t.left, t.right)
}

Refactor recursion helper function to use function literal


/*
   Copyright The containerd 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 version

import "runtime"

var (
	// Package is filled at linking time
	Package = "github.com/containerd/containerd"

	// Version holds the complete version number. Filled in at linking time.
	Version = "1.6.0-beta.3+unknown"

	// Revision is filled with the VCS (e.g. git) revision being used to build
	// the program at linking time.
	Revision = ""

	// GoVersion is Go tree's version.
	GoVersion = runtime.Version()
)

/*
   Copyright The containerd 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 version

import "runtime"

var (
	// Package is filled at linking time
	Package = "github.com/containerd/containerd"

	// Version holds the complete version number. Filled in at linking time.
	Version = "1.6.0-beta.4+unknown"

	// Revision is filled with the VCS (e.g. git) revision being used to build
	// the program at linking time.
	Revision = ""

	// GoVersion is Go tree's version.
	GoVersion = runtime.Version()
)

Prepare release notes for v1.6.0-beta.4


package main

import (
	"log"
	"net/http"

	"github.com/ParadropLabs/node"
)

// var client *rabric.Client

func main() {
	node.Log()

	// Pass certificate here
	s := node.CreateNode("pd.routers.aardvark")

	server := &http.Server{
		Handler: s,
		Addr:    ":8000",
	}

	log.Fatal(server.ListenAndServe())
}

package main

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

	"github.com/ParadropLabs/node"
)

// var client *rabric.Client

func main() {
	node.Log()

	// Pass certificate here
	s := node.CreateNode("pd.routers.aardvark")

	server := &http.Server{
		Handler: s,
		Addr:    ":8000",
	}

	certFile := os.Getenv("EXIS_CERT")
	keyFile := os.Getenv("EXIS_KEY")

	if certFile != "" && keyFile != "" {
		log.Fatal(server.ListenAndServeTLS(certFile, keyFile))
	} else {
		log.Fatal(server.ListenAndServe())
	}
}

Use TLS if given a key and cert.


package main

import (
	"flag"
	"fmt"
	"log"
	"net"

	"github.com/umahmood/geoip"
)

// command line flags.
var ip string

func init() {
	flag.StringVar(&ip, "ip", "", "IP to geo locate can be v4 or v6 address.")
	flag.Parse()

	if ip != "" {
		addr := net.ParseIP(ip)
		if addr == nil {
			log.Fatalln("not a valid IP address.")
		}
	}
}

func main() {
	loc, err := geoip.Location(ip)
	if err != nil {
		log.Fatalln(err)
	}

	for k, v := range loc {
		fmt.Println(k, ":", v)
	}
}

package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/umahmood/geoip"
)

// command line flags.
var ip string

func init() {
	flag.StringVar(&ip, "ip", "", "IP to geo locate can be v4/v6 address or domain name.")
	flag.Parse()
}

func main() {
	loc, err := geoip.Location(ip)
	if err != nil {
		log.Fatalln(err)
	}

	for k, v := range loc {
		fmt.Println(k, ":", v)
	}
}

Remove check to see if -ip flag is valid address format


package model

// SourceCD
// 0 = unknown
// 1 = carthage
// 2 = cocoapods
// 3 = submodule

// Dependency has project dependency and source distination.
type Dependency struct {
	ProjectUUID          string `json:"project_uuid"`
	DependentProjectUUID string `json:"dependent_project_uuid"`

	SourceCD int `json:"source_cd"`
}

package model

// SourceCD
// 0 = unknown
// 1 = carthage
// 2 = cocoapods
// 3 = submodule

// Dependency has project dependency and source distination.
type Dependency struct {
	ProjectUUID          string `json:"project_uuid" gorm:"ForeignKey:UUID"`
	DependentProjectUUID string `json:"dependent_project_uuid" gorm:"ForeignKey:UUID"`

	SourceCD int `json:"source_cd"`
}

Set foreign key information to Dependency


package leetcode

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	n1, n2 := head, head
	for i := 0; i < n; i++ {
		n2 = n2.Next
	}
	if n2 == nil {
		return head.Next
	}
	for n2.Next != nil {
		n1 = n1.Next
		n2 = n2.Next
	}
	n1.Next = n1.Next.Next
	return head
}

package leetcode

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	/* 4 ms
	var count int
	for node := head; node != nil; node = node.Next {
		count++
	}
	if n = count - n + 1; n == 1 {
		return head.Next
	}
	for node := head; node != nil; node = node.Next {
		if n--; n == 1 {
			if next := node.Next; next != nil {
				node.Next = next.Next
			}
			break
		}
	}
	return head
	*/
	n1, n2 := head, head
	for i := 0; i < n; i++ {
		n2 = n2.Next
	}
	if n2 == nil {
		return head.Next
	}
	for n2.Next != nil {
		n1 = n1.Next
		n2 = n2.Next
	}
	n1.Next = n1.Next.Next
	return head
}

Remove Nth Node From End of List


package service

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNotFoundLoginShouldReturnError(t *testing.T) {
	nf := &NotFound{}
	token, err := nf.Login()
	assert.NotNil(t, err)
	assert.Equal(t, "Service not found", err.Error())
	assert.Equal(t, "", token)
}

Add test for NotFound Login


// Logging helpers
package autosite

import (
	"net/http"
)

// LoggerFunc returns a logger from a http request.
type LoggerFunc func(*http.Request) Logger

// Logger specifies logging functions.
type Logger interface {
	// Debugf formats its arguments according to the format, analogous to fmt.Printf,
	// and records the text as a log message at Debug level.
	Debugf(format string, args ...interface{})

	// Infof is like Debugf, but at Info level.
	Infof(format string, args ...interface{})

	// Warningf is like Debugf, but at Warning level.
	Warningf(format string, args ...interface{})

	// Errorf is like Debugf, but at Error level.
	Errorf(format string, args ...interface{})

	// Criticalf is like Debugf, but at Critical level.
	Criticalf(format string, args ...interface{})
}

// Logging helpers
package autosite

import (
	"net/http"

	"github.com/golang/glog"
)

// LoggerFunc returns a logger from a http request.
type LoggerFunc func(*http.Request) Logger

// Logger specifies logging functions.
//
// The methods are chosen to match the logging methods from
// appengine.Context, without needing to depend on appengine.
type Logger interface {
	// Debugf formats its arguments according to the format, analogous to fmt.Printf,
	// and records the text as a log message at Debug level.
	Debugf(format string, args ...interface{})

	// Infof is like Debugf, but at Info level.
	Infof(format string, args ...interface{})

	// Warningf is like Debugf, but at Warning level.
	Warningf(format string, args ...interface{})

	// Errorf is like Debugf, but at Error level.
	Errorf(format string, args ...interface{})

	// Criticalf is like Debugf, but at Critical level.
	Criticalf(format string, args ...interface{})
}

// Glogger implements Logger using package glog.
//
// Note that Glogger should not be used on appengine, since attempting
// to write to disk causes a panic.
type Glogger struct{}

// Debugf formats its arguments according to the format, analogous to fmt.Printf,
// and records the text as a log message at Debug level.
func (Glogger) Debugf(format string, args ...interface{}) {
	glog.V(1).Infof(format, args...)
}

// Infof is like Debugf, but at Info level.
func (Glogger) Infof(format string, args ...interface{}) {
	glog.Infof(format, args...)
}

// Warningf is like Debugf, but at Warning level.
func (Glogger) Warningf(format string, args ...interface{}) {
	glog.Warningf(format, args...)
}

// Errorf is like Debugf, but at Error level.
func (Glogger) Errorf(format string, args ...interface{}) {
	glog.Errorf(format, args...)
}

// Criticalf is like Debugf, but at Critical level.
func (Glogger) Criticalf(format string, args ...interface{}) {
	glog.Fatalf(format, args...)
}

Add Glogger, Logger that uses package glog


package cleanhttp

import (
	"net"
	"net/http"
	"time"
)

// DefaultTransport returns a new http.Transport with the same default values
// as http.DefaultTransport
func DefaultTransport() *http.Transport {
	return &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
	}
}

// DefaultClient returns a new http.Client with the same default values as
// http.Client, but with a non-shared Transport
func DefaultClient() *http.Client {
	return &http.Client{
		Transport: DefaultTransport(),
	}
}

package cleanhttp

import (
	"net"
	"net/http"
	"runtime"
	"time"
)

// DefaultTransport returns a new http.Transport with the same default values
// as http.DefaultTransport
func DefaultTransport() *http.Transport {
	transport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
	}
	SetFinalizer(transport)
	return transport
}

// DefaultClient returns a new http.Client with the same default values as
// http.Client, but with a non-shared Transport
func DefaultClient() *http.Client {
	return &http.Client{
		Transport: DefaultTransport(),
	}
}

func SetFinalizer(transport *http.Transport) {
	runtime.SetFinalizer(&transport, FinalizeTransport)
}

func FinalizeTransport(t **http.Transport) {
	(*t).CloseIdleConnections()
}

Set a finalizer function on the transport to close idle connections.


package data

import (
	"time"

	"github.com/jinzhu/gorm"

	// DB adapters
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
)

var db gorm.DB

type Check struct {
	Id  int64
	URL string
}

type Result struct {
	Timestamp time.Time
	Status    int
	Success   bool
	IP        string
}

func InitDatabase() (err error) {
	db, err = gorm.Open("sqlite3", "/tmp/goffee.db")
	if err != nil {
		return err
	}

	db.AutoMigrate(&Check{}, &Result{})

	return nil
}

func (c Check) Create() error {
	r := db.Create(c)
	return r.Error
}

func Checks() ([]Check, error) {
	checks := []Check{}
	r := db.Find(&checks)
	return checks, r.Error
}

package data

import (
	"time"

	"github.com/jinzhu/gorm"

	// DB adapters
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
)

var db gorm.DB

type Check struct {
	Id        int64
	URL       string `gorm:"column:url"`
	Status    int    // status code of last result
	Success   bool   // success status of last result
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Result struct {
	Id        int64
	CreatedAt time.Time
	Status    int
	Success   bool
	IP        string `gorm:"column:ip"`
	CheckId   int64
}

func InitDatabase() (err error) {
	db, err = gorm.Open("sqlite3", "/tmp/goffee.db")
	if err != nil {
		return err
	}

	db.AutoMigrate(&Check{}, &Result{})

	return nil
}

func Checks() ([]Check, error) {
	var checks []Check
	res := db.Find(&checks)
	return checks, res.Error
}

func (c *Check) Create() error {
	res := db.Create(c)
	return res.Error
}

func (c *Check) AddResult(r *Result) error {
	tx := db.Begin()

	r.CheckId = c.Id
	res := tx.Create(r)
	if res.Error != nil {
		tx.Rollback()
		return res.Error
	}

	c.Status = r.Status
	c.Success = r.Success
	res = tx.Save(c)
	if res.Error != nil {
		tx.Rollback()
		return res.Error
	}

	tx.Commit()
	return nil
}

func (c *Check) Results() ([]Result, error) {
	var results []Result
	res := db.Model(c).Related(&results)
	return results, res.Error
}

Make it possible to create and fetch results and checks


package data

type Command struct {
    Id string `json:"id"`
    ProcessId string `json:"processId"`
    Name string `json:"name"`
    Body string `json:"body"`
}

package data

type Command struct {
    Id string `json:"id"`
    ProcessId string `json:"processId"`
    Name string `json:"name"`
    Body interface{} `json:"body"`
}

Add generic behavior to body field, now it can be a simple or complex type