package notificationsettings

import (
	"socialapi/workers/common/handler"
	"socialapi/workers/common/mux"
)

func AddHandlers(m *mux.Mux) {

	m.AddHandler(
		handler.Request{
			Handler:  Create,
			Name:     "notification-settings-create",
			Type:     handler.PostRequest,
			Endpoint: "/channel/{id}/notificationsettings",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Get,
			Name:     "notification-settings-list",
			Type:     handler.GetRequest,
			Endpoint: "/notificationsettings/{id}",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Update,
			Name:     "notification-settings-update",
			Type:     handler.PostRequest,
			Endpoint: "/notificationsettings/{id}",
		},
	)
}

package notificationsettings

import (
	"socialapi/workers/common/handler"
	"socialapi/workers/common/mux"
)

func AddHandlers(m *mux.Mux) {

	m.AddHandler(
		handler.Request{
			Handler:  Create,
			Name:     "notification-settings-create",
			Type:     handler.PostRequest,
			Endpoint: "/channel/{id}/notificationsettings",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Get,
			Name:     "notification-settings-get",
			Type:     handler.GetRequest,
			Endpoint: "/channel/{id}/notificationsettings",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Update,
			Name:     "notification-settings-update",
			Type:     handler.PostRequest,
			Endpoint: "/notificationsettings/{id}",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Delete,
			Name:     "notification-settings-delete",
			Type:     handler.DeleteRequest,
			Endpoint: "/channel/{id}/notificationsettings",
		},
	)
}

Delete endpoint is added for notification setting


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

package gocyclo

import (
	"go/ast"
	"strings"
)

type directives []string

func (ds directives) HasIgnore() bool {
	return ds.isPresent("ignore")
}

func (ds directives) isPresent(name string) bool {
	for _, d := range ds {
		if d == name {
			return true
		}
	}
	return false
}

func parseDirectives(doc *ast.CommentGroup) directives {
	if doc == nil {
		return directives{}
	}
	const prefix = "//gocyclo:"
	var ds directives
	for _, comment := range doc.List {
		if strings.HasPrefix(comment.Text, prefix) {
			ds = append(ds, strings.TrimPrefix(comment.Text, prefix))
		}
	}
	return ds
}

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

package gocyclo

import (
	"go/ast"
	"strings"
)

type directives []string

func (ds directives) HasIgnore() bool {
	return ds.isPresent("ignore")
}

func (ds directives) isPresent(name string) bool {
	for _, d := range ds {
		if d == name {
			return true
		}
	}
	return false
}

func parseDirectives(doc *ast.CommentGroup) directives {
	if doc == nil {
		return directives{}
	}
	const prefix = "//gocyclo:"
	var ds directives
	for _, comment := range doc.List {
		if strings.HasPrefix(comment.Text, prefix) {
			ds = append(ds, strings.TrimSpace(strings.TrimPrefix(comment.Text, prefix)))
		}
	}
	return ds
}

Allow ignore directive with trailing spaces


package tracker

import (
	"os"
	"testing"

	"github.com/powerman/narada-go/narada/staging"
)

func TestMain(m *testing.M) { os.Exit(staging.TearDown(m.Run())) }

package tracker

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

	"github.com/powerman/narada-go/narada/staging"
)

func TestMain(m *testing.M) { os.Exit(staging.TearDown(m.Run())) }

func readTestFile(t *testing.T, path string) []byte {
	b, err := ioutil.ReadFile(filepath.Join("var", "testdata", path))
	if err != nil {
		pwd, err2 := os.Getwd()
		t.Fatal(err, pwd, err2)
	}
	return b
}

Add helper function to readfiles from testdata folder


package symboltable

type StringToIntST interface {
	Put(key string, val int)
	Get(key string) (int, bool)
	Delete(key string)
}
//changed

Revert "test after new machine setup"


package uploader

import (
	"errors"
	"github.com/matthew-andrews/s3up/objects"
	"sync"
)

type s3ClientInterface interface {
	UploadFile(string, objects.File) error
}

func Upload(service s3ClientInterface, bucket string, files []objects.File, concurrency int) []error {
	ec := make(chan error, len(files))
	if len(files) < 1 {
		return []error{errors.New("No files found for upload to S3.  (Directories are ignored)")}
	}

	var sem = make(chan bool, concurrency)
	var wg sync.WaitGroup

	for _, file := range files {
		wg.Add(1)
		sem <- true
		go func(file objects.File) {
			defer wg.Done()
			defer func() { <-sem }()
			if err := service.UploadFile(bucket, file); err != nil {
				ec <- err
			}
		}(file)
	}

	wg.Wait()
	close(ec)
	var errs []error
	if len(ec) > 0 {
		for err := range ec {
			errs = append(errs, err)
		}
	}

	return errs
}

package uploader

import (
	"errors"
	"github.com/matthew-andrews/s3up/objects"
	"sync"
)

type s3ClientInterface interface {
	UploadFile(string, objects.File) error
}

func Upload(service s3ClientInterface, bucket string, files []objects.File, concurrency int) []error {
	if len(files) < 1 {
		return []error{errors.New("No files found for upload to S3.  (Directories are ignored)")}
	}

	ec := make(chan error, len(files))
	sem := make(chan bool, concurrency)
	var wg sync.WaitGroup

	for _, file := range files {
		wg.Add(1)
		sem <- true
		go func(file objects.File) {
			defer wg.Done()
			defer func() { <-sem }()
			if err := service.UploadFile(bucket, file); err != nil {
				ec <- err
			}
		}(file)
	}

	wg.Wait()
	close(ec)
	var errs []error
	if len(ec) > 0 {
		for err := range ec {
			errs = append(errs, err)
		}
	}

	return errs
}

Tidy up code a little


package storage

import (
	"io"

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

type ClientImplCloser interface {
	ClientImpl
	Close() error
}

// Represents data storage for an unspecified torrent.
type ClientImpl interface {
	OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error)
}

// Data storage bound to a torrent.
type TorrentImpl struct {
	Piece func(metainfo.Piece) PieceImpl
	Close func() error
	// Storages that share the same value, will provide a pointer to the same function.
	Capacity *func() *int64
}

// Interacts with torrent piece data. Optional interfaces to implement include io.WriterTo, such as
// when a piece supports a more efficient way to write out incomplete chunks
type PieceImpl interface {
	// These interfaces are not as strict as normally required. They can
	// assume that the parameters are appropriate for the dimensions of the
	// piece.
	io.ReaderAt
	io.WriterAt
	// Called when the client believes the piece data will pass a hash check.
	// The storage can move or mark the piece data as read-only as it sees
	// fit.
	MarkComplete() error
	MarkNotComplete() error
	// Returns true if the piece is complete.
	Completion() Completion
}

type Completion struct {
	Complete bool
	Ok       bool
}

package storage

import (
	"io"

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

type ClientImplCloser interface {
	ClientImpl
	Close() error
}

// Represents data storage for an unspecified torrent.
type ClientImpl interface {
	OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error)
}

// Data storage bound to a torrent.
type TorrentImpl struct {
	Piece func(p metainfo.Piece) PieceImpl
	Close func() error
	// Storages that share the same value, will provide a pointer to the same function.
	Capacity *func() *int64
}

// Interacts with torrent piece data. Optional interfaces to implement include io.WriterTo, such as
// when a piece supports a more efficient way to write out incomplete chunks
type PieceImpl interface {
	// These interfaces are not as strict as normally required. They can
	// assume that the parameters are appropriate for the dimensions of the
	// piece.
	io.ReaderAt
	io.WriterAt
	// Called when the client believes the piece data will pass a hash check.
	// The storage can move or mark the piece data as read-only as it sees
	// fit.
	MarkComplete() error
	MarkNotComplete() error
	// Returns true if the piece is complete.
	Completion() Completion
}

type Completion struct {
	Complete bool
	Ok       bool
}

Add default param name in TorrentImpl.Piece func


package commands

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

func init() {
	RootCmd.AddCommand(&cobra.Command{
		Use:   "cp [name]",
		Short: "Copy a credential to the clipboard",
		Long: `The copy command is used to copy a credential's password
to the clipboard.
            `,
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) != 1 {
				fmt.Println("USAGE: copy [name]")
				os.Exit(1)
			}

			os.Exit(Copy(args...))
		},
	})
}

func Copy(args ...string) int {
	safe, err := loadSafe()
	if err != nil {
		return handleError(err)
	}

	if err := safe.Copy(args[0]); err != nil {
		return handleError(err)
	}

	return 0
}

package commands

import (
	"fmt"
	"os"

	"github.com/bndw/pick/utils"
	"github.com/spf13/cobra"
)

func init() {
	RootCmd.AddCommand(&cobra.Command{
		Use:   "cp [name]",
		Short: "Copy a credential to the clipboard",
		Long: `The copy command is used to copy a credential's password
to the clipboard.
            `,
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) != 1 {
				fmt.Println("USAGE: copy [name]")
				os.Exit(1)
			}

			os.Exit(Copy(args...))
		},
	})
}

func Copy(args ...string) int {
	safe, err := loadSafe()
	if err != nil {
		return handleError(err)
	}

	account, err := safe.Get(args[0])
	if err != nil {
		return handleError(err)
	}

	if err := utils.CopyToClipboard(account.Password); err != nil {
		handleError(err)
	}

	return 0
}

Copy command uses safe's Get method


// Copyright (C) 2016 AppNeta, Inc. All rights reserved.

package tv_test

import (
	"github.com/appneta/go-traceview/v1/tv"
	"golang.org/x/net/context"
)

func ExampleBeginProfile(ctx context.Context) {
	defer tv.BeginProfile(ctx, "example").End()
	// ... do something ...
}

func ExampleBeginProfile_func(ctx context.Context) {
	// typically this would be used in a named function
	func() {
		defer tv.BeginProfile(ctx, "example_func").End()
		// ... do something else ...
	}()
}

// Copyright (C) 2016 AppNeta, Inc. All rights reserved.

package tv_test

import (
	"time"

	"github.com/appneta/go-traceview/v1/tv"
	"golang.org/x/net/context"
)

func slowFunc(ctx context.Context) {
	defer tv.BeginProfile(ctx, "slowFunc").End()
	// ... do something else ...
	time.Sleep(1 * time.Second)
}

func Example() {
	ctx := tv.NewContext(context.Background(), tv.NewTrace("myLayer"))
	slowFunc(ctx)
	tv.EndTrace(ctx)
}

Update godoc Profile example to use whole file example


// Copyright 2010  The "go-linoise" Authors
//
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE file.
//
// This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for more details.

package linoise

import (
	"os"
	"testing"
	"fmt"

	"github.com/kless/go-term/term"
)

var stdin = 0

func Test(t *testing.T) {
	term.MakeRaw(stdin)
	defer term.RestoreTermios()

	hist, err := NewHistory("/tmp/go-history")
	if err != nil {
		t.Error(err)
	}
	hist.Load()

	ln := NewLine(os.Stdin, os.Stdout, hist, "matrix> ")
	if err = ln.Run(); err != nil {
		fmt.Println(err)
	} else {
		hist.Save()
	}
}

// Copyright 2010  The "go-linoise" Authors
//
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE file.
//
// This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for more details.

package linoise

import (
	"fmt"
	"os"
	"testing"

	"github.com/kless/go-term/term"
)

func Test(t *testing.T) {
	term.MakeRaw(Input.(*os.File).Fd())
	defer term.RestoreTermios()

	hist, err := NewHistory("/tmp/go-history")
	if err != nil {
		t.Error(err)
	}
	hist.Load()

	ln := NewLine(hist, "matrix> ")
	if err = ln.Run(); err != nil {
		fmt.Println(err)
	} else {
		hist.Save()
	}
}

Use a type assertion on the io.Reader to make it an os.File, and to access so to its FD


package packet

import "github.com/spf13/cobra"

func deleteCmd() *cobra.Command {
	cmd := &cobra.Command{}
	return cmd
}

package packet

import (
	"errors"
	"fmt"

	"github.com/spf13/cobra"
)

func deleteCmd() *cobra.Command {
	var deleteAll bool
	cmd := &cobra.Command{
		Use:   "delete",
		Short: "Delete machines from the Packet.net project. This will destroy machines. Be ready.",
		Long: `Delete machines from the Packet.net project.

This command destroys machines on the project that is being managed with this tool.

It will destroy machines in the project, regardless of whether the machines were provisioned with this tool.

Be ready.
		`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return doDelete(cmd, args, deleteAll)
		},
	}
	cmd.Flags().BoolVar(&deleteAll, "all", false, "Delete all machines in the project.")
	return cmd
}

func doDelete(cmd *cobra.Command, args []string, deleteAll bool) error {
	if !deleteAll && len(args) != 1 {
		return errors.New("You must provide the hostname of the machine to be deleted, or use the --all flag to destroy all machines in the project")
	}
	hostname := ""
	if !deleteAll {
		hostname = args[0]
	}
	client, err := newFromEnv()
	if err != nil {
		return err
	}
	nodes, err := client.ListNodes()
	if err != nil {
		return err
	}
	for _, n := range nodes {
		if hostname == n.Host || deleteAll {
			if err := client.DeleteNode(n.ID); err != nil {
				return err
			}
			fmt.Println("Deleted", n.Host)
		}
	}
	return nil
}

Add support for deleting packet machines


package riak_cs_service

import (
	"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
	. "github.com/onsi/ginkgo"
)

var _ = Describe("Riak CS Nodes Register a Route", func() {
	It("Allows users to access the riak-cs service using external url instead of IP of single machine after register the route", func() {
		endpointURL := TestConfig.RiakCsScheme + TestConfig.RiakCsHost + "/riak-cs/ping"

		runner.NewCmdRunner(runner.Curl("-k", endpointURL), TestContext.ShortTimeout()).WithOutput("OK").Run()
	})
})

var _ = Describe("Riak Broker Registers a Route", func() {
	It("Allows users to access the riak-cs broker using a url", func() {
		endpointURL := "http://" + TestConfig.BrokerHost + "/v2/catalog"

		// check for 401 because it means we reached the endpoint, but did not supply credentials.
		// a failure would be a 404
		runner.NewCmdRunner(runner.Curl("-k", "-s", "-w", "%{http_code}", endpointURL, "-o", "/dev/null"), TestContext.ShortTimeout()).WithOutput("401").Run()
	})
})

package riak_cs_service

import (
	"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
	. "github.com/onsi/ginkgo"
)

var _ = Describe("Riak CS Nodes Register a Route", func() {
	It("Allows users to access the riak-cs service using external url instead of IP of single machine after register the route", func() {
		endpointURL := TestConfig.RiakCsScheme + TestConfig.RiakCsHost + "/riak-cs/ping"

		runner.NewCmdRunner(runner.Curl("-k", endpointURL), TestContext.ShortTimeout()).WithOutput("OK").Run()
	})
})

var _ = Describe("Riak Broker Registers a Route", func() {
	It("Allows users to access the riak-cs broker using a url", func() {
		endpointURL := "https://" + TestConfig.BrokerHost + "/v2/catalog"

		// check for 401 because it means we reached the endpoint, but did not supply credentials.
		// a failure would be a 404
		runner.NewCmdRunner(runner.Curl("-k", "-s", "-w", "%{http_code}", endpointURL, "-o", "/dev/null"), TestContext.ShortTimeout()).WithOutput("401").Run()
	})
})

Replace hardcoded reference to http with https


package darts

import "math"

func Score(x, y float64) int {
	if isInnerCircle(x, y) {
		return 10
	} else if isMiddleCircle(x, y) {
		return 5
	} else if isOuterCircle(x, y) {
		return 1
	}
	return 0
}

func isInnerCircle(x float64, y float64) bool {
	return distanceToCenter(x, y) <= 1
}

func isMiddleCircle(x float64, y float64) bool {
	return distanceToCenter(x, y) <= 5
}

func isOuterCircle(x float64, y float64) bool {
	return distanceToCenter(x, y) <= 10
}

func distanceToCenter(x float64, y float64) float64 {
	return math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))
}

package darts

import "math"

const innerRadius = 1
const middleRadius = 5
const outerRadius = 10

func Score(x, y float64) int {
	if isInCircle(x, y, innerRadius) {
		return 10
	} else if isInCircle(x, y, middleRadius) {
		return 5
	} else if isInCircle(x, y, outerRadius) {
		return 1
	}
	return 0
}

func isInCircle(x float64, y float64, radius int) bool {
	return distanceToCenter(x, y) <= float64(radius)
}

func distanceToCenter(x float64, y float64) float64 {
	return math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))
}

Refactor to use one isInCircle func


package cf

import (
	"encoding/json"
	"strings"
	"time"

	. "github.com/onsi/gomega"

	"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)

//var CfApiTimeout = 30 * time.Second

type GenericResource struct {
	Metadata struct {
		Guid string `json:"guid"`
	} `json:"metadata"`
}

type QueryResponse struct {
	Resources []GenericResource `struct:"resources"`
}

var ApiRequest = func(method, endpoint string, response interface{}, timeout time.Duration, data ...string) {
	request := Cf(
		"curl",
		endpoint,
		"-X", method,
		"-d", strings.Join(data, ""),
	)

	runner.NewCmdRunner(request, timeout).Run()

	if response != nil {
		err := json.Unmarshal(request.Out.Contents(), response)
		Expect(err).ToNot(HaveOccurred())
	}
}

package cf

import (
	"encoding/json"
	"strings"
	"time"

	. "github.com/onsi/gomega"

	"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)

//var CfApiTimeout = 30 * time.Second

type GenericResource struct {
	Metadata struct {
		Guid string `json:"guid"`
	} `json:"metadata"`
}

type QueryResponse struct {
	Resources []GenericResource `struct:"resources"`
}

var ApiRequest = func(method, endpoint string, response interface{}, timeout time.Duration, data ...string) {
	args := []string{
		"curl",
		endpoint,
		"-X", method,
	}

	dataArg := strings.Join(data, "")
	if len(dataArg) > 0 {
		args = append(args, "-d", dataArg)
	}

	request := Cf(args...)
	runner.NewCmdRunner(request, timeout).Run()

	if response != nil {
		err := json.Unmarshal(request.Out.Contents(), response)
		Expect(err).ToNot(HaveOccurred())
	}

}

Update ApiRequest to not pass -d for empty data


package background

import (
	"image"
	"os/exec"
	"os/user"
	"path/filepath"
)

// Set the background on windows.
func Set(img image.Image) error {
	// Get the absolute path of the directory.
	usr, err := user.Current()
	if err != nil {
		return err
	}
	imgPath := filepath.Join(usr.HomeDir, ".local", "share", "himawari", "background.png")

	// Create the file.
	if err := createFile(img, imgPath); err != nil {
		return err
	}

	// Set the background (gnome3 only atm)
	err = exec.Command(
		"gsettings", "set", "org.gnome.desktop.background",
		"picture-uri", "file://"+imgPath,
	).Run()

	// Set background mode (again, testing on gnome3)
	err = exec.Command(
		"gsettings", "set", "org.gnome.desktop.background",
		"picture-options", "scaled",
	).Run()

	return err
}

package background

import (
	"image"
	"os/exec"
	"os/user"
	"path/filepath"
)

// Set the background on windows.
func Set(img image.Image) error {
	// Get the absolute path of the directory.
	usr, err := user.Current()
	if err != nil {
		return err
	}
	imgPath := filepath.Join(usr.HomeDir, ".local", "share", "himawari", "background.png")

	// Create the file.
	if err := createFile(img, imgPath); err != nil {
		return err
	}

	// Darken background area
	err = exec.Command(
		"gsettings", "set", "org.gnome.desktop.background",
		"primary-color", "#000000",
	).Run()

	// Set the background (gnome3 only atm)
	err = exec.Command(
		"gsettings", "set", "org.gnome.desktop.background",
		"picture-uri", "file://"+imgPath,
	).Run()

	// Set background mode (again, testing on gnome3)
	err = exec.Command(
		"gsettings", "set", "org.gnome.desktop.background",
		"picture-options", "scaled",
	).Run()

	return err
}

Make primary-color consistent with image.


package algoliasearch

type Key struct {
	ACL                    []string `json:"acl"`
	CreatedAt              int      `json:"createdAt,omitempty"`
	Description            string   `json:"description,omitempty"`
	Indexes                []string `json:"indexes,omitempty"`
	MaxHitsPerQuery        int      `json:"maxHitsPerQuery,omitempty"`
	MaxQueriesPerIPPerHour int      `json:"maxQueriesPerIPPerHour,omitempty"`
	QueryParamaters        string   `json:"queryParameters,omitempty"`
	Referers               []string `json:"referers,omitempty"`
	Validity               int      `json:"validity,omitempty"`
	Value                  string   `json:"value,omitempty"`
}

type listAPIKeysRes struct {
	Keys []Key `json:"keys"`
}

type AddKeyRes struct {
	CreatedAt string `json:"createdAt"`
	Key       string `json:"key"`
}

type UpdateKeyRes struct {
	Key       string `json:"key"`
	UpdatedAt string `json:"updatedAt"`
}

package algoliasearch

type Key struct {
	ACL                    []string `json:"acl"`
	CreatedAt              int      `json:"createdAt,omitempty"`
	Description            string   `json:"description,omitempty"`
	Indexes                []string `json:"indexes,omitempty"`
	MaxHitsPerQuery        int      `json:"maxHitsPerQuery,omitempty"`
	MaxQueriesPerIPPerHour int      `json:"maxQueriesPerIPPerHour,omitempty"`
	QueryParameters        string   `json:"queryParameters,omitempty"`
	Referers               []string `json:"referers,omitempty"`
	Validity               int      `json:"validity,omitempty"`
	Value                  string   `json:"value,omitempty"`
}

type listAPIKeysRes struct {
	Keys []Key `json:"keys"`
}

type AddKeyRes struct {
	CreatedAt string `json:"createdAt"`
	Key       string `json:"key"`
}

type UpdateKeyRes struct {
	Key       string `json:"key"`
	UpdatedAt string `json:"updatedAt"`
}

Add QueryParameters in Key struct to fix typo


package orm

import "testing"

func TestOrm(t *testing.T) {
	testConfig := map[string]interface{}{
		"connection_string": "test_data/db/empty_test.db",
		"driver":            "sqlite3",
	}
	emptyDeps := make(map[string]interface{})

	t.Run("Init", func(t *testing.T) {
		_, err := Init(emptyDeps, testConfig)
		if err != nil {
			t.Errorf("Encountered an error: %s", err.Error())
		}
	})
}

package orm

import "testing"
import "github.com/mattn/go-sqlite3"

func TestOrm(t *testing.T) {
	testConfig := map[string]interface{}{
		"connection_string": "test_data/db/empty_test.db",
		"driver":            "sqlite3",
	}
	emptyDeps := make(map[string]interface{})

	t.Run("InitInvalidConf", func(t *testing.T) {
		conf := testConfig
		conf["connection_string"] = "test_data/db/not_exist.db"
		_, err := Init(emptyDeps, conf)
		if err == nil {
			t.Errorf("Invalid conf unexpectedly did not return an error.")
		}
		switch err.(type) {
		case sqlite3.Error:
			return
		}
		t.Errorf("Unexpected error: " + err.Error())
	})
}

Change orm test to make it pass


package builtins

import "github.com/coel-lang/coel/src/lib/core"

// Equal checks if all arguments are equal or not, and returns true if so or false otherwise.
var Equal = core.NewStrictFunction(
	core.NewSignature(nil, nil, "args", nil, nil, ""),
	func(ts ...*core.Thunk) core.Value {
		l := ts[0]

		if v := checkEmptyList(l, core.True); v != nil {
			return v
		}

		e := core.PApp(core.First, l)
		l = core.PApp(core.Rest, l)

		for {
			if v := checkEmptyList(l, core.True); v != nil {
				return v
			}

			v := core.PApp(core.Equal, e, core.PApp(core.First, l)).Eval()
			b, ok := v.(core.BoolType)

			if !ok {
				return core.NotBoolError(v)
			} else if !b {
				return core.False
			}

			l = core.PApp(core.Rest, l)
		}
	})

package builtins

import "github.com/coel-lang/coel/src/lib/core"

// Equal checks if all arguments are equal or not, and returns true if so or false otherwise.
var Equal = core.NewLazyFunction(
	core.NewSignature(nil, nil, "args", nil, nil, ""),
	func(ts ...*core.Thunk) core.Value {
		l := ts[0]

		if v := checkEmptyList(l, core.True); v != nil {
			return v
		}

		e := core.PApp(core.First, l)
		l = core.PApp(core.Rest, l)

		for {
			if v := checkEmptyList(l, core.True); v != nil {
				return v
			}

			v := core.PApp(core.Equal, e, core.PApp(core.First, l)).Eval()
			b, ok := v.(core.BoolType)

			if !ok {
				return core.NotBoolError(v)
			} else if !b {
				return core.False
			}

			l = core.PApp(core.Rest, l)
		}
	})

Mark Equal function as lazy


package api

// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
	ConversationToken  string          `json:"conversation_token"`
	ExpectUserResponse bool            `json:"expect_user_response"`
	ExpectedInputs     []ExpectedInput `json:"expected_inputs"`
	FinalResponse_     FinalResponse   `json:"final_response"`
}

type ExpectedInput struct {
	PossibleIntents []ExpectedIntent `json:"possible_intents"`
}

type ExpectedIntent struct {
	Intent          string         `json:"intent"`
	InputValueSpec_ InputValueSpec `json:"input_value_spec"`
}

type FinalResponse struct {
	SpeechResponse_ SpeechResponse `json:"speech_response"`
}

type InputValueSpec struct {
	PermissionValueSpec_ PermissionValueSpec `json:"permission_value_spec"`
}

type PermissionValueSpec struct {
	OptContext  string   `json:"opt_context"`
	Permissions []string `json:"permissions"`
}

type SpeechResponse struct {
	TextToSpeech string `json:"text_to_speech"`
	SSML         string `json:"ssml"`
}

package api

// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
	ConversationToken  *string         `json:"conversation_token"`
	ExpectUserResponse bool            `json:"expect_user_response"`
	ExpectedInputs     []ExpectedInput `json:"expected_inputs"`
	FinalResponse_     FinalResponse   `json:"final_response"`
}

type ExpectedInput struct {
	PossibleIntents []ExpectedIntent `json:"possible_intents"`
}

type ExpectedIntent struct {
	Intent          string         `json:"intent"`
	InputValueSpec_ InputValueSpec `json:"input_value_spec"`
}

type FinalResponse struct {
	SpeechResponse_ SpeechResponse `json:"speech_response"`
}

type InputValueSpec struct {
	PermissionValueSpec_ PermissionValueSpec `json:"permission_value_spec"`
}

type PermissionValueSpec struct {
	OptContext  string   `json:"opt_context"`
	Permissions []string `json:"permissions"`
}

type SpeechResponse struct {
	TextToSpeech string `json:"text_to_speech"`
	SSML         string `json:"ssml"`
}

Change conversation token to a pointer to allow it to be null in the json


package fetcher

import (
	"fmt"
	"testing"

	"github.com/drkaka/lg"
)

func TestGetMessage(t *testing.T) {
	lg.InitLogger(true)

	jCmd := fmt.Sprintf("journalctl -u hooks -o json -n 20")
	results, err := GetMessages("hooks", "ssh", "leeq@192.168.1.201", jCmd)
	if err != nil {
		t.Fatal(err)
	}

	for _, one := range results {
		fmt.Println("Message: ", string(one.Message))
	}
}

package fetcher

// func TestGetMessage(t *testing.T) {
// 	lg.InitLogger(true)

// 	jCmd := fmt.Sprintf("journalctl -u hooks -o json -n 20")
// 	results, err := GetMessages("hooks", "ssh", "leeq@192.168.1.201", jCmd)
// 	if err != nil {
// 		t.Fatal(err)
// 	}

// 	for _, one := range results {
// 		fmt.Println("Message: ", string(one.Message))
// 	}
// }

Comment out the fetcher test method.


package media

import (
	"net/http"
	"github.com/gorilla/mux"
	"strconv"
	"io/ioutil"
)

func GetMedia(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	f := vars["idMedia"]
	idMedia, _ := strconv.Atoi(f)

	if idMedia > 0 {

		config, err := ioutil.ReadFile("data/media.config.json")
		check(err)

		if err == nil {
			w.Write([]byte(config))
		}
	}
}

func check(e error) {
	if e != nil {
		panic(e)
	}
}

package media

import (
	"net/http"
	"github.com/gorilla/mux"
	"strconv"
	"io/ioutil"
	"encoding/json"
	"errors"
)

var Medias []Media

func LoadMedias() {
	content, err := ioutil.ReadFile("data/media.config.json")
	check(err)

	err = json.Unmarshal(content, &Medias)
	check(err)
}

func GetMedia(idMedia int) (*Media, error) {
	for _, m := range Medias {
		if idMedia == m.ID {
			return &m, nil
		}
	}

	return nil, errors.New("NO_MEDIA_FOUND")
}

func HandleGetMedia(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	f := vars["idMedia"]
	idMedia, _ := strconv.Atoi(f)

	m, err := GetMedia(idMedia)
	if err != nil {
		writeResponseWithError(w, http.StatusNotFound)
		return
	}

	b, err := json.Marshal(*m)
	if err != nil {
		writeResponseWithError(w, http.StatusNotFound)
		return
	}

	w.Write([]byte(b))

}

func writeResponseWithError(w http.ResponseWriter, errorCode int) {
	w.WriteHeader(errorCode)
}

func check(e error) {
	if e != nil {
		panic(e)
	}
}

Load medias configuration from memory


package server

import (
	"github.com/vulcand/oxy/forward"
	"github.com/vulcand/oxy/roundrobin"
	"github.com/vulcand/oxy/stream"
	"net/http"
	"net/url"
)

type ReverseProxy struct {
	stream *stream.Streamer
}

func NewReverseProxy(backends []string) *ReverseProxy {
	fwd, _ := forward.New()
	lb, _ := roundrobin.New(fwd)
	for _, backend := range backends {
		target, _ := url.Parse(backend)
		lb.UpsertServer(target)
	}
	stream, _ := stream.New(lb, stream.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`))
	return &ReverseProxy{stream: stream}
}

func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rp.stream.ServeHTTP(w, r)
}

package server

import (
	"github.com/vulcand/oxy/forward"
	"github.com/vulcand/oxy/roundrobin"
	"github.com/vulcand/oxy/stream"
	"github.com/vulcand/oxy/cbreaker"
	"net/http"
	"net/url"
)

type ReverseProxy struct {
	stream *stream.Streamer
}

func NewReverseProxy(backends []string) *ReverseProxy {
	fwd, _ := forward.New()
	cb, _ := cbreaker.New(fwd, `NetworkErrorRatio() > 0.5`)
	lb, _ := roundrobin.New(cb)
	for _, backend := range backends {
		target, _ := url.Parse(backend)
		lb.UpsertServer(target)
	}
	stream, _ := stream.New(lb, stream.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`))
	return &ReverseProxy{stream: stream}
}

func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rp.stream.ServeHTTP(w, r)
}

Add circuit breaker middle to revserse proxy


// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.

package afp

import (
	"os"
	"log"
)

const CHAN_BUF_LEN = 64

//Constants to specify the type of a given filter
const (
	PIPE_SOURCE = iota
	PIPE_SINK
	PIPE_LINK
)

const HEADER_LENGTH = (1 + // Version
	1 + // Channels
	1 + // SampleSize
	4 + // SampleRate
	4 + // FrameSize
	8) // ContentLength

type StreamHeader struct {
	Version       int8
	Channels      int8
	SampleSize    int8
	SampleRate    int32
	FrameSize     int32
	ContentLength int64
}

type Context struct {
	HeaderSource <-chan StreamHeader
	HeaderSink   chan<- StreamHeader
	Source       <-chan [][]float32
	Sink         chan<- [][]float32

	Verbose   bool
	Err, Info *log.Logger
}

type Filter interface {
	GetType() int
	Init(*Context, []string) os.Error
	Start()
	Stop() os.Error
}

// Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.

package afp

import (
	"os"
	"log"
)

const CHAN_BUF_LEN = 64

//Constants to specify the type of a given filter
const (
	PIPE_SOURCE = iota
	PIPE_SINK
	PIPE_LINK
)

const HEADER_LENGTH = (
	1 + // Version
	1 + // Channels
	1 + // SampleSize
	4 + // SampleRate
	4 + // FrameSize
	8 // ContentLength
)
type StreamHeader struct {
	Version       int8
	Channels      int8
	SampleSize    int8
	SampleRate    int32
	FrameSize     int32
	ContentLength int64
}

type Context struct {
	HeaderSource <-chan StreamHeader
	HeaderSink   chan<- StreamHeader
	Source       <-chan [][]float32
	Sink         chan<- [][]float32

	Verbose   bool
	Err, Info *log.Logger
}

type Filter interface {
	GetType() int
	Init(*Context, []string) os.Error
	Start()
	Stop() os.Error
}

Reformat HEADER_LENGTH calc slightly for readability


package gohost

// HosterEndpoint is an interface for an endpoint that can be hosted.
type HosterEndpoint interface {
	// Serve hosts the endpoint.
	Serve()
}

package gohost

// HosterEndpoint is an interface for an endpoint that can be hosted.
type HosterEndpoint interface {
	// Serve hosts the endpoint.
	Serve() error
}

Update interface to return an error.


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 thrift

type TServer interface {
	ProcessorFactory() TProcessorFactory
	ServerTransport() TServerTransport
	InputTransportFactory() TTransportFactory
	OutputTransportFactory() TTransportFactory
	InputProtocolFactory() TProtocolFactory
	OutputProtocolFactory() TProtocolFactory

	// Starts the server
	Serve() error
	// Stops the server. This is optional on a per-implementation basis. Not
	// all servers are required to be cleanly stoppable.
	Stop() error
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 thrift

type TServer interface {
	ProcessorFactory() TProcessorFactory
	ServerTransport() TServerTransport
	InputTransportFactory() TTransportFactory
	OutputTransportFactory() TTransportFactory
	InputProtocolFactory() TProtocolFactory
	OutputProtocolFactory() TProtocolFactory

	// Starts the server
	Serve() error
	// Stops the server. This is optional on a per-implementation basis. Not
	// all servers are required to be cleanly stoppable.
	Stop() error
	SetErrorLogger(func(error))
}

Add SetLogger to the TServer interface


package git

import (
	"fmt"
	"os"
	"testing"
)

func TestRevParseSingle(t *testing.T) {
	repo := createTestRepo(t)
	defer os.RemoveAll(repo.Workdir())

	commitId, _ := seedTestRepo(t, repo)
	fmt.Println(commitId)

	revSpec, err := repo.RevParse("HEAD")
	checkFatal(t, err)

	checkObject(t, revSpec.From(), commitId)
}

func checkObject(t *testing.T, obj Object, id *Oid) {
	if obj == nil {
		t.Fatalf("bad object")
	}

	if !obj.Id().Equal(id) {
		t.Fatalf("bad object, expected %s, got %s", id.String(), obj.Id().String())
	}
}

Add simple test for `rev-parse HEAD`.


package actionerror

import "fmt"

// RevisionNotFoundError is returned when a requested application is not
// found.
type RevisionNotFoundError struct {
	Version int
	App     string
}

func (e RevisionNotFoundError) Error() string {
	return fmt.Sprintf("Revision '%d' for app '%s' not found", e.Version, e.App)
}

type RevisionAmbiguousError struct {
	Version int
}

func (e RevisionAmbiguousError) Error() string {
	return fmt.Sprintf("More than one revision '%d' found", e.Version)
}

package actionerror

import "fmt"

// RevisionNotFoundError is returned when a requested application is not
// found.
type RevisionNotFoundError struct {
	Version int
}

func (e RevisionNotFoundError) Error() string {
	return fmt.Sprintf("Revision (%d) not found", e.Version)
}

type RevisionAmbiguousError struct {
	Version int
}

func (e RevisionAmbiguousError) Error() string {
	return fmt.Sprintf("More than one revision (%d) found", e.Version)
}

Change revision command error message format


package util

import (
	"fmt"
	"io/ioutil"
)

// WriteTempFile creates a temporary file and returns its name
func WriteTempFile(prefix string, content string) string {
	tmpFile, err := ioutil.TempFile("", "aptomi-"+prefix)
	if err != nil {
		panic("Failed to create temp file")
	}
	defer tmpFile.Close() // nolint: errcheck

	_, err = tmpFile.Write([]byte(content))
	if err != nil {
		panic("Failed to write to temp file")
	}

	return tmpFile.Name()
}

// EnsureSingleFile ensures that only one file matches the list of files
func EnsureSingleFile(files []string) (string, error) {
	if len(files) <= 0 {
		return "", fmt.Errorf("no files found")
	}
	if len(files) > 1 {
		return "", fmt.Errorf("more than one file found")
	}
	return files[0], nil
}

Remove no more used EnsureSingleFile helper


// Package callinfo stores custom values into the Context
// (related to the RPC source)
package callinfo

import (
	"html/template"

	"golang.org/x/net/context"
)

// CallInfo is the extra data stored in the Context
type CallInfo interface {
	// RemoteAddr is the remote address information for this rpc call.
	RemoteAddr() string

	// Username is associated with this rpc call, if any.
	Username() string

	// Text is a text version of this connection, as specifically as possible.
	Text() string

	// HTML represents this rpc call connection in a web-friendly way.
	HTML() template.HTML
}

// internal type and value
type key string

var callInfoKey key = "vt.CallInfo"

// NewContext adds the provided CallInfo to the context
func NewContext(ctx context.Context, ci CallInfo) context.Context {
	return context.WithValue(ctx, callInfoKey, ci)
}

// FromContext returns the CallInfo value stored in ctx, if any.
func FromContext(ctx context.Context) (CallInfo, bool) {
	ci, ok := ctx.Value(callInfoKey).(CallInfo)
	return ci, ok
}

// Package callinfo stores custom values into the Context
// (related to the RPC source)
package callinfo

import (
	"html/template"

	"golang.org/x/net/context"
)

// CallInfo is the extra data stored in the Context
type CallInfo interface {
	// RemoteAddr is the remote address information for this rpc call.
	RemoteAddr() string

	// Username is associated with this rpc call, if any.
	Username() string

	// Text is a text version of this connection, as specifically as possible.
	Text() string

	// HTML represents this rpc call connection in a web-friendly way.
	HTML() template.HTML
}

// internal type and value
type key int

var callInfoKey key = 0

// NewContext adds the provided CallInfo to the context
func NewContext(ctx context.Context, ci CallInfo) context.Context {
	return context.WithValue(ctx, callInfoKey, ci)
}

// FromContext returns the CallInfo value stored in ctx, if any.
func FromContext(ctx context.Context) (CallInfo, bool) {
	ci, ok := ctx.Value(callInfoKey).(CallInfo)
	return ci, ok
}

Use 0 as the context key


package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/benbjohnson/sieve"
)

var (
	addr = flag.String("addr", ":6900", "HTTP address")
)

func usage() {
	fmt.Fprintln(os.Stderr, "usage: sieve [opts]")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	// Read configuration.
	flag.Usage = usage
	flag.Parse()

	// Setup the database.
	var db = sieve.NewDB()

	// TODO(benbjohnson): Read STDIN into the database.

	// Serve root handler.
	fmt.Printf("Listening on http://localhost%s\n", *addr)
	log.Fatal(http.ListenAndServe(*addr, sieve.NewHandler(db)))
}

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/benbjohnson/sieve"
)

var (
	addr = flag.String("addr", ":6900", "HTTP address")
)

func usage() {
	fmt.Fprintln(os.Stderr, "usage: sieve [opts]")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	// Read configuration.
	flag.Usage = usage
	flag.Parse()

	// Setup the database.
	var db = sieve.NewDB()

	// Read STDIN into the database.
	go load(os.Stdin, db)

	// Serve root handler.
	fmt.Printf("Listening on http://localhost%s\n", *addr)
	log.Fatal(http.ListenAndServe(*addr, sieve.NewHandler(db)))
}

// Parses a reader and streams it into the database.
func load(r io.Reader, db *sieve.DB) {
	var decoder = json.NewDecoder(r)
	for {
		// Parse individual row from JSON.
		var row = &sieve.Row{}
		if err := decoder.Decode(&row.Data); err == io.EOF {
			break
		} else if err != nil {
			log.Println("err:", err)
			continue
		}

		// Add it to the database.
		db.Append(row)
	}
}

Add JSON parsing on STDIN.


package main

import (
	"testing"

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

func TestTimestampParser(t *testing.T) {
	tsNano := ParseTimestamp("1411534805453497432")
	assert.Equal(t, tsNano, 1411534805453497432, "Invalid ns")

	tsNano = ParseTimestamp("1411534805453497")
	assert.Equal(t, tsNano, 1411534805453497000, "Invalid us")

	tsNano = ParseTimestamp("1411534805453")
	assert.Equal(t, tsNano, 1411534805453000000, "Invalid ms")

	tsNano = ParseTimestamp("1411534805")
	assert.Equal(t, tsNano, 1411534805000000000, "Invalid s")
}

Use testify package for unit testing


package main

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

	"github.com/andrewslotin/doppelganger/git"
)

var (
	reposTemplate = template.Must(template.ParseFiles("templates/repos/index.html.template"))
)

type ReposHandler struct {
	repositories git.RepositoryService
}

func NewReposHandler(repositoryService git.RepositoryService) *ReposHandler {
	return &ReposHandler{
		repositories: repositoryService,
	}
}

func (handler *ReposHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	startTime := time.Now()

	if repoName := req.FormValue("repo"); repoName != "" {
		NewRepoClient(handler.repositories).ServeHTTP(w, req)
		return
	}

	repos, err := handler.repositories.All()
	if err != nil {
		log.Printf("failed to get repos (%s) %s", err, req)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	if err := reposTemplate.Execute(w, repos); err != nil {
		log.Printf("failse to render repos/index with %d entries (%s)", len(repos), err)
	} else {
		log.Printf("rendered repos/index with %d entries [%s]", len(repos), time.Since(startTime))
	}
}

package main

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

	"github.com/andrewslotin/doppelganger/git"
)

var (
	reposTemplate = template.Must(template.ParseFiles("templates/repos/index.html.template"))
)

type ReposHandler struct {
	repositories git.RepositoryService
}

func NewReposHandler(repositoryService git.RepositoryService) *ReposHandler {
	return &ReposHandler{
		repositories: repositoryService,
	}
}

func (handler *ReposHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	startTime := time.Now()

	if repoName := req.FormValue("repo"); repoName != "" {
		NewRepoClient(handler.repositories).ServeHTTP(w, req)
		return
	}

	repos, err := handler.repositories.All()
	if err != nil {
		log.Printf("failed to get repos (%s) %s", err, req)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	if err := reposTemplate.Execute(w, repos); err != nil {
		log.Printf("failed to render repos/index with %d entries (%s)", len(repos), err)
	} else {
		log.Printf("rendered repos/index with %d entries [%s]", len(repos), time.Since(startTime))
	}
}

Fix typo in log message


// Copyright 2016 The Gosl 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 qpck

/*
#cgo linux LDFLAGS: -lopenblas -llapack -lgfortran -lm

#cgo windows LDFLAGS: -lopenblas -lgfortran -lm

#cgo darwin LDFLAGS: -L/usr/local/opt/openblas/lib -L/usr/local/Cellar/gcc/7.3.0/lib/gcc/7/ -lopenblas -lgfortran -lm
*/
import "C"

// Copyright 2016 The Gosl 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 qpck

/*
#cgo linux LDFLAGS: -lopenblas -llapack -lgfortran -lm

#cgo windows LDFLAGS: -lopenblas -lgfortran -lm

#cgo darwin LDFLAGS: -L/usr/local/opt/openblas/lib -L/usr/local/Cellar/gcc/7.3.0_1/lib/gcc/7/ -lopenblas -lgfortran -lm
*/
import "C"

Update gfortran directory on macOS


package cli

import "fmt"

import (
	"sync"

	"github.com/jessevdk/go-flags"
)

var (
	globalParser      *flags.Parser
	globalParserSetup sync.Once
)

func parser() *flags.Parser {
	globalParserSetup.Do(func() {
		globalParser = flags.NewNamedParser("cypress", flags.Default|flags.PassAfterNonOption)
	})

	return globalParser
}

func addCommand(name, short, long string, cmd interface{}) {
	_, err := parser().AddCommand(name, short, long, cmd)
	if err != nil {
		panic(err)
	}
}

func Run(args []string) int {
	defer Lifecycle.RunCleanup()

	Lifecycle.Start()

	_, err := parser().Parse()
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return 1
	}

	return 0
}

package cli

import "fmt"

import (
	"sync"

	"github.com/jessevdk/go-flags"
)

var (
	globalParser      *flags.Parser
	globalParserSetup sync.Once
)

func parser() *flags.Parser {
	globalParserSetup.Do(func() {
		globalParser = flags.NewNamedParser("cypress", flags.Default|flags.PassAfterNonOption)
	})

	return globalParser
}

func addCommand(name, short, long string, cmd interface{}) {
	_, err := parser().AddCommand(name, short, long, cmd)
	if err != nil {
		panic(err)
	}
}

func Run(args []string) int {
	defer Lifecycle.RunCleanup()

	Lifecycle.Start()

	_, err := parser().Parse()
	if err != nil {
		if ferr, ok := err.(*flags.Error); ok {
			if ferr.Type == flags.ErrHelp {
				return 1
			}
		}

		fmt.Printf("Error: %s\n", err)
		return 1
	}

	return 0
}

Fix double printing the help output


package subnet

const (
	//Queue from TUN -> router(server) / remote end (client)
	pktInMaxBuff  = 150
	pktOutMaxBuff = 150

	devMtuSize     = 1500
	devPktBuffSize = 4096

	//Queue from network clients to ingestion
	servMaxInboundPktQueue = 80
	//Queue out to each network client
	servPerClientPktQueue = 40
)

package subnet

const (
	//Queue from TUN -> router(server) / remote end (client)
	pktInMaxBuff  = 150
	pktOutMaxBuff = 150

	devMtuSize     = 1500
	devPktBuffSize = 4096

	//Queue from network clients to ingestion
	servMaxInboundPktQueue = 400
	//Queue out to each network client
	servPerClientPktQueue = 200
)

Test increasing server queue sizes


package switchboard

import "encoding/json"

type backendsPresenter struct {
	backends Backends
}

func NewBackendsPresenter(backends Backends) backendsPresenter {
	return backendsPresenter{
		backends: backends,
	}
}

func (bp backendsPresenter) Present() ([]byte, error) {
	backendsResponse := []string{}
	for range bp.backends.All() {
		backendsResponse = append(backendsResponse, "")
	}

	return json.Marshal(backendsResponse)
}

package switchboard

import "encoding/json"

type backendsPresenter struct {
	backends Backends
}

func NewBackendsPresenter(backends Backends) backendsPresenter {
	return backendsPresenter{
		backends: backends,
	}
}

func (bp backendsPresenter) Present() ([]byte, error) {
	backendsResponse := []string{}
	for _ = range bp.backends.All() {
		backendsResponse = append(backendsResponse, "")
	}

	return json.Marshal(backendsResponse)
}

Use 1.3.3. compatible syntax for now


package main

import (
	"fmt"
	"runtime"

	"github.com/datawire/ambassador/pkg/supervisor"
)

var notifyRAI *RunAsInfo

// Notify displays a desktop banner notification to the user
func Notify(p *supervisor.Process, message string) {
	if notifyRAI == nil {
		var err error
		notifyRAI, err = GuessRunAsInfo(p)
		if err != nil {
			p.Log(err)
			notifyRAI = &RunAsInfo{}
		}
	}

	var args []string
	switch runtime.GOOS {
	case "darwin":
		script := fmt.Sprintf("display notification \"Edge Control Daemon\" with title \"%s\"", message)
		args = []string{"osascript", "-e", script}
	case "linux":
		args = []string{"notify-send", "Edge Control Daemon", message}
	default:
		return
	}

	p.Logf("NOTIFY: %s", message)
	cmd := notifyRAI.Command(p, args...)
	if err := cmd.Run(); err != nil {
		p.Logf("ERROR while notifying: %v", err)
	}
}

// MaybeNotify displays a notification only if a value changes
func MaybeNotify(p *supervisor.Process, name string, old, new bool) {
	if old != new {
		Notify(p, fmt.Sprintf("%s: %t -> %t", name, old, new))
	}
}

package main

import (
	"fmt"
	"runtime"

	"github.com/datawire/ambassador/pkg/supervisor"
)

var (
	notifyRAI     *RunAsInfo
	notifyEnabled = false
)

// Notify displays a desktop banner notification to the user
func Notify(p *supervisor.Process, message string) {
	p.Logf("----------------------------------------------------------------------")
	p.Logf("NOTIFY: %s", message)
	p.Logf("----------------------------------------------------------------------")

	if !notifyEnabled {
		return
	}

	if notifyRAI == nil {
		var err error
		notifyRAI, err = GuessRunAsInfo(p)
		if err != nil {
			p.Log(err)
			notifyRAI = &RunAsInfo{}
		}
	}

	var args []string
	switch runtime.GOOS {
	case "darwin":
		script := fmt.Sprintf("display notification \"Edge Control Daemon\" with title \"%s\"", message)
		args = []string{"osascript", "-e", script}
	case "linux":
		args = []string{"notify-send", "Edge Control Daemon", message}
	default:
		return
	}

	cmd := notifyRAI.Command(p, args...)
	if err := cmd.Run(); err != nil {
		p.Logf("ERROR while notifying: %v", err)
	}
}

// MaybeNotify displays a notification only if a value changes
func MaybeNotify(p *supervisor.Process, name string, old, new bool) {
	if old != new {
		Notify(p, fmt.Sprintf("%s: %t -> %t", name, old, new))
	}
}

Make it possible to disable notifications; disable them


package yaml

import (
	"github.com/rancher/norman/types"
)

func NewFormatter(next types.Formatter) types.Formatter {
	return func(request *types.APIContext, resource *types.RawResource) {
		resource.Links["yaml"] = request.URLBuilder.Link("yaml", resource)
		if next != nil {
			next(request, resource)
		}
	}
}

package yaml

import (
	"github.com/rancher/norman/types"
)

func NewFormatter(next types.Formatter) types.Formatter {
	return func(request *types.APIContext, resource *types.RawResource) {
		if next != nil {
			next(request, resource)
		}
		resource.Links["yaml"] = request.URLBuilder.Link("yaml", resource)
	}
}

Fix yaml link for workloads


package main

import (
	"bytes"
	"github.com/Cistern/sflow"
	"net"
)

func sFlowParser(buffer []byte) {
	reader := bytes.NewReader(buffer)
	d := sflow.NewDecoder(reader)
	dgram, err := d.Decode()
	if err != nil {
		println(err)
		return
	}
	for _, sample := range dgram.Samples {
		println(sample)
	}
}

func sFlowListener() (err error) {
	// Start listening UDP socket, check if it started properly
	UDPAddr, err := net.ResolveUDPAddr("udp", ":6343")
	conn, err := net.ListenUDP("udp", UDPAddr)
	if err != nil {
		return err
	}

	var buffer []byte
	for {
		conn.ReadFromUDP(buffer)
		sFlowParser(buffer)
	}

	return nil
}

package main

import (
	"bytes"
	"fmt"
	"github.com/Cistern/sflow"
	"net"
	"time"
)

func sFlowParser(buffer []byte) {
	reader := bytes.NewReader(buffer)
	d := sflow.NewDecoder(reader)
	dgram, err := d.Decode()
	if err != nil {
		println(err)
		return
	}
	for _, sample := range dgram.Samples {
		println(sample)
	}
}

func sFlowListener(AppConfig app_config) (err error) {
	defer wait.Done()

	var udp_addr = fmt.Sprintf("[%s]:%d", AppConfig.SFlowConfig.Address, AppConfig.SFlowConfig.Port)

	DebugLogger.Println("Binding sFlow listener to", udp_addr)

	UDPAddr, err := net.ResolveUDPAddr("udp", udp_addr)
	if err != nil {
		ErrorLogger.Println(err)
		return err
	}
	conn, err := net.ListenUDP("udp", UDPAddr)
	if err != nil {
		ErrorLogger.Println(err)
		return err
	}

	var buffer []byte
	for running {
		/*
		  Normally read would block, but we want to be able to break this
		  loop gracefuly. So add read timeout and every 0.1s check if it is
		  time to finish
		*/
		conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
		var read, _, err = conn.ReadFromUDP(buffer)
		if read > 0 && err != nil {
			sFlowParser(buffer)
		}

	}

	conn.Close()

	return nil
}

Break listener operation for graceful exit


package main

import (
    "os"

    "github.com/intelsdi-x/pulse/control/plugin"
    "github.com/intelsdi-x/pulse/plugin/publisher/pulse-publisher-hana/hana"
)

func main() {
    meta := hana.Meta()
    plugin.Start(meta, hana.NewHANAPublisher(), os.Args[1])
}

package main

import (
	"os"

	"github.com/intelsdi-x/pulse-plugin-publisher-hana/hana"
	"github.com/intelsdi-x/pulse/control/plugin"
)

func main() {
	meta := hana.Meta()
	plugin.Start(meta, hana.NewHANAPublisher(), os.Args[1])
}

Fix import path for hana package


package main

import (
	"github.com/thomasf/drone-mvn/mavendeploy"
	"github.com/drone/drone-plugin-go/plugin"
)

func main() {
	workspace := plugin.Workspace{}
	repo := plugin.Repo{}
	build := plugin.Build{}
	vargs := mavendeploy.Maven{}

	plugin.Param("repo", &repo)
	plugin.Param("build", &build)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	vargs.WorkspacePath(workspace.Path)

	err := vargs.Publish()
	if err != nil {
		panic(err)
	}
}

package main

import (
	"flag"
	"os"

	"github.com/drone/drone-plugin-go/plugin"
	"github.com/thomasf/drone-mvn/mavendeploy"
)

// testExpressions allows for quickly testing source/regexp patterns against
// files via the command line.
func testExpressions() {
	var regexp, source string
	flag.StringVar(&regexp, "regexp", "", "regular expression to test")
	flag.StringVar(&source, "source", "", "source expression to test")
	flag.Parse()
	if regexp != "" && source != "" {
		mvn := mavendeploy.Maven{
			Artifact: mavendeploy.Artifact{
				GroupID:    "GROUPID",
				ArtifactID: "ARTIFACTID",
				Version:    "99.99.99",
				Extension:  "EXTENSION",
			},
			Args: mavendeploy.Args{
				Debug:  true,
				Source: source,
				Regexp: regexp,
			},
		}
		mvn.WorkspacePath(".")
		err := mvn.Prepare()
		if err != nil {
			panic(err)
		}
		os.Exit(0)
	}
}

func main() {
	testExpressions()
	workspace := plugin.Workspace{}
	repo := plugin.Repo{}
	build := plugin.Build{}
	vargs := mavendeploy.Maven{}

	plugin.Param("repo", &repo)
	plugin.Param("build", &build)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	vargs.WorkspacePath(workspace.Path)

	err := vargs.Publish()
	if err != nil {
		panic(err)
	}
}

Add command line option to test source/regexp


package main

import (
	"fmt"
	"os"

	"github.com/sosedoff/musicbot/bot"
)

func main() {
	if os.Getenv("MOPIDY_HOST") == "" {
		fmt.Println("MOPIDY_HOST is not provided")
		return
	}

	if os.Getenv("SLACK_TOKEN") == "" {
		fmt.Println("SLACK_TOKEN is not provided")
		return
	}

	if os.Getenv("SLACK_CHANNEL") == "" {
		fmt.Println("SLACK_CHANNEL is not provided")
		return
	}

	bot := bot.NewBot(bot.BotConfig{
		MopidyHost: os.Getenv("MOPIDY_HOST"),
		SlackToken: os.Getenv("SLACK_TOKEN"),
		Channel:    os.Getenv("SLACK_CHANNEL"),
	})

	bot.Run()

	// dummy
	chexit := make(chan bool)
	<-chexit
}

package main

import (
	"fmt"
	"os"

	"github.com/jessevdk/go-flags"
	"github.com/sosedoff/musicbot/bot"
)

var options struct {
	MopidyHost   string `long:"mopidy" description:"Mopidy server host:port" env:"MOPIDY_HOST"`
	SlackToken   string `long:"slack-token" description:"Slack integration token" env:"SLACK_TOKEN"`
	SlackChannel string `long:"slack-channel" description:"Slack channel name" default:"general" env:"SLACK_CHANNEL"`
	Debug        bool   `short:"d" long:"debug" description:"Enable debugging mode" default:"false"`
}

func init() {
	_, err := flags.ParseArgs(&options, os.Args)

	if err != nil {
		os.Exit(1)
	}

	if options.MopidyHost == "" {
		fmt.Println("Error: Mopidy host is not provided")
		os.Exit(1)
	}

	if options.SlackToken == "" {
		fmt.Println("Error: Slack token is not provided")
		os.Exit(1)
	}
}

func main() {
	bot := bot.NewBot(bot.BotConfig{
		MopidyHost: options.MopidyHost,
		SlackToken: options.SlackToken,
		Channel:    options.SlackChannel,
	})

	bot.Run()

	// dummy
	chexit := make(chan bool)
	<-chexit
}

Implement flags via third-party package


// FLiP.Earth is the website for the Friendly Linux Players community.
//
// See https://FriendlyLinuxPlayers.org for the live website and
// https://github.com/FriendlyLinuxPlayers/flip.earth for the code.
package main

import (
	"fmt"

	_ "github.com/friendlylinuxplayers/flip.earth/config"
	_ "github.com/friendlylinuxplayers/flip.earth/router"
	_ "github.com/friendlylinuxplayers/flip.earth/server"
	"github.com/friendlylinuxplayers/flip.earth/service"
	cs "github.com/friendlylinuxplayers/flip.earth/service/config"
)

// TODO refactor out everything so main only contains minimal code
func main() {
	b := new(service.Builder)
	configDef := service.Definition{
		Name:        "config",
		Initializer: cs.Reader{},
	}
	b.Insert(configDef)
	container, error := b.Build()
	if error != nil {
		panic(error)
	}

	service, error := container.Get("config")
	if error != nil {
		panic(error)
	}
	fmt.Printf("Config %+v \n", service)
}

Add a doc comment for the whole project.


package main

import (
	"fmt"
	"github.com/joaodias/hugito-app/handlers"
	"net/http"
)

func main() {
	router := handlers.NewRouter()
	router.Handle("repositories get", handlers.GetRepository)
	router.Handle("repository validate", handlers.ValidateRepository)
	router.Handle("content list", handlers.GetContentList)
	router.Handle("content get", handlers.GetFileContent)
	router.Handle("content create", handlers.CreateContent)
	router.Handle("content update", handlers.UpdateContent)
	router.Handle("content remove", handlers.RemoveContent)
	router.Handle("user get", handlers.GetUser)
	router.Handle("authenticate", handlers.Authenticate)
	http.Handle("/", router)
	fmt.Print("Go app initialized in port 4000.")
	http.ListenAndServe(":4000", nil)
}

package main

import (
	"fmt"
	"github.com/joaodias/hugito-app/handlers"
	"net/http"
	"os"
)

func main() {
	router := handlers.NewRouter()
	router.Handle("repositories get", handlers.GetRepository)
	router.Handle("repository validate", handlers.ValidateRepository)
	router.Handle("content list", handlers.GetContentList)
	router.Handle("content get", handlers.GetFileContent)
	router.Handle("content create", handlers.CreateContent)
	router.Handle("content update", handlers.UpdateContent)
	router.Handle("content remove", handlers.RemoveContent)
	router.Handle("user get", handlers.GetUser)
	router.Handle("authenticate", handlers.Authenticate)
	http.Handle("/", router)
	port := os.Getenv("PORT")
	fmt.Print("Go app initialized in port " + port + ".\n")
	http.ListenAndServe(":"+port, nil)
}

Add support to an env port assignment


package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/ecnahc515/gist-playground/gist"
	"github.com/google/go-github/github"
)

var token string

func init() {
	token = os.Getenv("GISTPLAYGROUND_TOKEN")
}

func main() {
	flag.Parse()
	args := flag.Args()

	httpClient := gist.NewCachingHttpClient(token, nil, nil)
	client := github.NewClient(httpClient)

	if len(args) < 1 {
		fmt.Println("Error, must provide at least one argument.")
		os.Exit(1)
	}

	switch args[0] {
	case "serve":
		// set up http server
	default:
		// passing in a url for a gist
		id := args[0]
		gst, _, err := client.Gists.Get(id)
		if err != nil {
			fmt.Println("Error retrieving gist:", err.Error())
			os.Exit(1)
		}
		var content string
		content, err = gist.FindMain(gst)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println(content)
	}
}

package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"github.com/ecnahc515/gist-playground/gist"
	"github.com/google/go-github/github"
	"github.com/gregjones/httpcache/diskcache"
)

const cacheDir = "gist_playground_cache"

var token string

func init() {
	token = os.Getenv("GISTPLAYGROUND_TOKEN")
}

func NewDiskCache() *diskcache.Cache {
	tmpDir := os.TempDir()
	path := filepath.Join(tmpDir, cacheDir)
	return diskcache.New(path)
}

func main() {
	flag.Parse()
	args := flag.Args()

	if len(args) < 1 {
		fmt.Println("Error, must provide at least one argument.")
		os.Exit(1)
	}

	switch args[0] {
	case "serve":
		// set up http server
	default:
		cache := NewDiskCache()
		httpClient := gist.NewCachingHttpClient(token, cache, nil)
		client := github.NewClient(httpClient)

		// passing in a url for a gist
		id := args[0]
		gst, _, err := client.Gists.Get(id)
		if err != nil {
			fmt.Println("Error retrieving gist:", err.Error())
			os.Exit(1)
		}
		var content string
		content, err = gist.FindMain(gst)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println(content)
	}
}

Use disk cache when accepting CLI params.


package brats_test

import (
	"github.com/cloudfoundry/libbuildpack/bratshelper"
	"github.com/cloudfoundry/libbuildpack/cutlass"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Go buildpack", func() {
	bratshelper.UnbuiltBuildpack("go", CopyBrats)
	bratshelper.DeployingAnAppWithAnUpdatedVersionOfTheSameBuildpack(CopyBrats)
	bratshelper.StagingWithBuildpackThatSetsEOL("go", func(_ string) *cutlass.App {
		return CopyBrats("1.8.7")
	})
	bratshelper.StagingWithADepThatIsNotTheLatest("go", CopyBrats)
	bratshelper.StagingWithCustomBuildpackWithCredentialsInDependencies(CopyBrats)
	bratshelper.DeployAppWithExecutableProfileScript("go", CopyBrats)
	bratshelper.DeployAnAppWithSensitiveEnvironmentVariables(CopyBrats)

	bratshelper.ForAllSupportedVersions("go", CopyBrats, func(goVersion string, app *cutlass.App) {
		PushApp(app)

		By("installs the correct go version", func() {
			Expect(app.Stdout.String()).To(ContainSubstring("Installing go " + goVersion))
		})
		By("runs a simple webserver", func() {
			Expect(app.GetBody("/")).To(ContainSubstring("Hello World!"))
		})
	})
})

package brats_test

import (
	"github.com/cloudfoundry/libbuildpack/bratshelper"
	"github.com/cloudfoundry/libbuildpack/cutlass"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Go buildpack", func() {
	bratshelper.UnbuiltBuildpack("go", CopyBrats)
	bratshelper.DeployingAnAppWithAnUpdatedVersionOfTheSameBuildpack(CopyBrats)
	bratshelper.StagingWithBuildpackThatSetsEOL("go", func(_ string) *cutlass.App {
		return CopyBrats("1.8.7")
	})
	bratshelper.StagingWithADepThatIsNotTheLatest("go", func(_ string) *cutlass.App {
		return CopyBrats("1.8.6")
	})

	bratshelper.StagingWithCustomBuildpackWithCredentialsInDependencies(CopyBrats)
	bratshelper.DeployAppWithExecutableProfileScript("go", CopyBrats)
	bratshelper.DeployAnAppWithSensitiveEnvironmentVariables(CopyBrats)

	bratshelper.ForAllSupportedVersions("go", CopyBrats, func(goVersion string, app *cutlass.App) {
		PushApp(app)

		By("installs the correct go version", func() {
			Expect(app.Stdout.String()).To(ContainSubstring("Installing go " + goVersion))
		})
		By("runs a simple webserver", func() {
			Expect(app.GetBody("/")).To(ContainSubstring("Hello World!"))
		})
	})
})

Fix go version in another brats test


package path

import (
	"fmt"
	"github.com/aybabtme/graph"
)

type PathFinder interface {
	HasPathTo(to int) bool
	PathTo(to int) []int
}

type TremauxDFS struct {
	g      graph.Graph
	from   int
	marked []bool
	edgeTo []int
}

func BuildTremauxDFS(g graph.Graph, from int) PathFinder {

	t := TremauxDFS{
		g:      g,
		from:   from,
		marked: make([]bool, g.V()),
		edgeTo: make([]int, g.V()),
	}

	var visit func(v int)

	steps := 0

	visit = func(v int) {

		t.marked[v] = true
		for _, adj := range g.Adj(v) {
			steps++
			if !t.marked[adj] {
				t.edgeTo[adj] = v
				visit(adj)
			}
		}
	}

	visit(from)

	return t
}

func (t TremauxDFS) HasPathTo(to int) bool {
	return t.marked[to]
}

func (t TremauxDFS) PathTo(to int) []int {
	return []int{}
}

package path

import (
	"github.com/aybabtme/graph"
)

type PathFinder interface {
	HasPathTo(to int) bool
	PathTo(to int) []int
}

type TremauxDFS struct {
	g      graph.Graph
	from   int
	marked []bool
	edgeTo []int
}

func BuildTremauxDFS(g graph.Graph, from int) PathFinder {

	if from < 0 {
		panic("Can't start DFS from vertex v < 0")
	}

	if from >= g.V() {
		panic("Can't start DFS from vertex v >= total vertex count")
	}

	t := TremauxDFS{
		g:      g,
		from:   from,
		marked: make([]bool, g.V()),
		edgeTo: make([]int, g.V()),
	}

	var visit func(v int)

	steps := 0

	visit = func(v int) {

		t.marked[v] = true
		for _, adj := range g.Adj(v) {
			steps++
			if !t.marked[adj] {
				t.edgeTo[adj] = v
				visit(adj)
			}
		}
	}

	visit(from)

	return t
}

func (t TremauxDFS) HasPathTo(to int) bool {
	return t.marked[to]
}

func (t TremauxDFS) PathTo(to int) []int {
	return []int{}
}

Remove unused import. Parameter checking.


package termite

import (
	"fmt"
	"http"
)

func (me *WorkerDaemon) httpHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<title>Termite worker</title>")
	fmt.Fprintf(w, "
Termite worker status
")
	fmt.Fprintf(w, "
")
	me.masterMapMutex.Lock()
	defer me.masterMapMutex.Unlock()

	for k, v := range me.masterMap {
		fmt.Fprintf(w, "\n******\nMirror: %s\n\n", k)
		v.httpHandler(w, r)
	}
	fmt.Fprintf(w, "
")
}

func (me *Mirror) httpHandler(w http.ResponseWriter, r *http.Request) {
	me.fuseFileSystemsMutex.Lock()
	defer me.fuseFileSystemsMutex.Unlock()

	for _, v := range me.workingFileSystems {
		fmt.Fprintf(w, "FS:\n%s\n", v)
	}
	fmt.Fprintf(w, "%d unused filesystems.", len(me.fuseFileSystems))
}

func (me *WorkerDaemon) ServeHTTPStatus(port int) {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		me.httpHandler(w, r)
	})
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}

package termite

import (
	"fmt"
	"http"
)

func (me *WorkerDaemon) httpHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<title>Termite worker</title>")
	fmt.Fprintf(w, "
Termite worker status
")
	fmt.Fprintf(w, "")
	me.masterMapMutex.Lock()
	defer me.masterMapMutex.Unlock()

	for k, v := range me.masterMap {
		fmt.Fprintf(w, "
Mirror

<tt>%s</tt>\n", k)
		v.httpHandler(w, r)
	}
	fmt.Fprintf(w, "")
}

func (me *Mirror) httpHandler(w http.ResponseWriter, r *http.Request) {
	me.fuseFileSystemsMutex.Lock()
	defer me.fuseFileSystemsMutex.Unlock()

	for _, v := range me.workingFileSystems {
		fmt.Fprintf(w, "
FS:\n%s\n", v)
	}
	fmt.Fprintf(w, "
%d unused filesystems.", len(me.fuseFileSystems))
}

func (me *WorkerDaemon) ServeHTTPStatus(port int) {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		me.httpHandler(w, r)
	})
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}

Drop <pre> to make long commands readable.


package firewall

import (
	"net"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
)

// Firewall represents a LXD firewall.
type Firewall interface {
	String() string
	Compat() (bool, error)

	NetworkSetupForwardingPolicy(networkName string, ipVersion uint, allow bool) error
	NetworkSetupOutboundNAT(networkName string, subnet *net.IPNet, srcIP net.IP, append bool) error
	NetworkSetupDHCPDNSAccess(networkName string, ipVersion uint) error
	NetworkSetupDHCPv4Checksum(networkName string) error
	NetworkClear(networkName string, ipVersion uint) error

	InstanceSetupBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error
	InstanceClearBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error

	InstanceSetupProxyNAT(projectName string, instanceName string, deviceName string, listen *deviceConfig.ProxyAddress, connect *deviceConfig.ProxyAddress) error
	InstanceClearProxyNAT(projectName string, instanceName string, deviceName string) error

	InstanceSetupRPFilter(projectName string, instanceName string, deviceName string, hostName string) error
	InstanceClearRPFilter(projectName string, instanceName string, deviceName string) error
}

package firewall

import (
	"net"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	drivers "github.com/lxc/lxd/lxd/firewall/drivers"
)

// Firewall represents a LXD firewall.
type Firewall interface {
	String() string
	Compat() (bool, error)

	NetworkSetup(networkName string, opts drivers.Opts) error
	NetworkClear(networkName string, ipVersion uint) error

	InstanceSetupBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error
	InstanceClearBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error

	InstanceSetupProxyNAT(projectName string, instanceName string, deviceName string, listen *deviceConfig.ProxyAddress, connect *deviceConfig.ProxyAddress) error
	InstanceClearProxyNAT(projectName string, instanceName string, deviceName string) error

	InstanceSetupRPFilter(projectName string, instanceName string, deviceName string, hostName string) error
	InstanceClearRPFilter(projectName string, instanceName string, deviceName string) error
}

Add NetworkSetup and remove feature specific network setup functions


/* Demonstrate a streaming REST API, where the data is "flushed" to the client ASAP.

The Curl Demo:

        curl -i http://127.0.0.1:8080/stream

*/
package main

import (
	"fmt"
	"github.com/ant0ine/go-json-rest"
	"net/http"
	"time"
)

func main() {

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		rest.Route{"GET", "/stream", StreamThings},
	)
	http.ListenAndServe(":8080", &handler)
}

type Thing struct {
	Name string
}

func StreamThings(w *rest.ResponseWriter, r *rest.Request) {
	cpt := 0
	for {
		cpt++
		w.WriteJson(
			&Thing{
				Name: fmt.Sprintf("thing #%d", cpt),
			},
		)
		// Flush the buffer to client
		w.Flush()
		// wait 3 seconds
		time.Sleep(time.Duration(3) * time.Second)
	}
}

/* Demonstrate a streaming REST API, where the data is "flushed" to the client ASAP.

The stream format is a Line Delimited JSON.

The Curl Demo:

        curl -i http://127.0.0.1:8080/stream

        HTTP/1.1 200 OK
        Content-Type: application/json
        Date: Sun, 16 Feb 2014 00:39:19 GMT
        Transfer-Encoding: chunked

        {"Name":"thing #1"}
        {"Name":"thing #2"}
        {"Name":"thing #3"}

*/
package main

import (
	"fmt"
	"github.com/ant0ine/go-json-rest"
	"net/http"
	"time"
)

func main() {

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		DisableJsonIndent:        true,
	}
	handler.SetRoutes(
		rest.Route{"GET", "/stream", StreamThings},
	)
	http.ListenAndServe(":8080", &handler)
}

type Thing struct {
	Name string
}

func StreamThings(w *rest.ResponseWriter, r *rest.Request) {
	cpt := 0
	for {
		cpt++
		w.WriteJson(
			&Thing{
				Name: fmt.Sprintf("thing #%d", cpt),
			},
		)
		w.Write([]byte("\n"))
		// Flush the buffer to client
		w.Flush()
		// wait 3 seconds
		time.Sleep(time.Duration(3) * time.Second)
	}
}

Make the stream format a Line Delimited JSON


package main

import (
	"image/color"
	"time"

	"github.com/voxelbrain/pixelpixel/imageutils"
	"github.com/voxelbrain/pixelpixel/protocol"
)

func main() {
	c := protocol.PixelPusher()
	img := protocol.NewPixel()

	dImg := imageutils.DimensionChanger(img, 4, 1)
	for i := 0; i < 5; i++ {
		if i < 3 {
			dImg.Set(i, 0, color.RGBA{uint8(100 + i*70), 0, 0, 255})
		} else if i == 3 {
			dImg.Set(i, 0, color.RGBA{0, 255, 0, 255})
		} else {
			panic("CRASH")
		}
		c <- img
		time.Sleep(1 * time.Second)
	}
}

package main

import (
	"fmt"
	"image"
	"time"

	"github.com/voxelbrain/pixelpixel/imageutils"
	"github.com/voxelbrain/pixelpixel/protocol"
)

func main() {
	c := protocol.PixelPusher()
	img := protocol.NewPixel()

	dImg := imageutils.DimensionChanger(img, 4, 6)
	for i := 0; i < 5; i++ {
		color := imageutils.Green
		if i > 3 {
			panic("CRASH")
		} else if i == 3 {
			color = imageutils.Red
		}
		imageutils.FillRectangle(dImg, image.Rect(0, 0, 4, 6), imageutils.Black)
		imageutils.DrawText(dImg, image.Rect(0, 0, 4, 6), color, fmt.Sprintf("%d", 3-i))
		c <- img
		time.Sleep(1 * time.Second)
	}
}

Rewrite crash with actual textual countdown


package regexp

import (
	"testing"

	"github.com/tonyhb/govalidate/rules"
)

func TestRegexp(t *testing.T) {
	object := rules.ValidationData{
		Field: "Test",
		Args:  []interface{}{"^[a-zA-Z]{3,5}[0-9]+$"},
	}

	var valid = []interface{}{
		"aaaaa0",
		"aaa123456789",
	}
	var invalid = []interface{}{
		1,
		'a',
		"0aaa0",
	}

	for _, v := range invalid {
		object.Value = v
		if err := Regexp(object); err == nil {
			t.Errorf("Expected error with invalid values")
		}
	}

	for _, v := range valid {
		object.Value = v
		if err := Regexp(object); err != nil {
			t.Errorf("Unexpected error with valid values")
		}
	}
}

package regexp

import (
	"testing"

	"github.com/tonyhb/govalidate/rules"
)

func TestRegexp(t *testing.T) {
	object := rules.ValidationData{
		Field: "Test",
		Args:  []string{"/^[a-zA-Z]{3,5}[0-9]+$/"},
	}

	var valid = []interface{}{
		"aaaaa0",
		"aaa123456789",
	}
	var invalid = []interface{}{
		1,
		'a',
		"0aaa0",
	}

	for _, v := range invalid {
		object.Value = v
		if err := Regexp(object); err == nil {
			t.Errorf("Expected error with invalid values")
		}
	}

	for _, v := range valid {
		object.Value = v
		if err := Regexp(object); err != nil {
			t.Errorf("Unexpected error with valid values")
		}
	}
}

Fix separate regexp tests with changed arg type


package adapter

import (
	"github.com/domain-query-language/dql-server/src/server/vm/handler"
)

type Adapter interface {

	Next() (Handleable, error)
}

// Make it easy to get the correct type out, no need for casting based on "HandleableType"
type Handleable interface {

	Type() HandleableType
	Command() handler.Command
	Query() handler.Query
}

type HandleableType string

const (
	CMD HandleableType = "command"
	QRY = "query"
)

// Simple implementation
type SimpleHandleable struct {

	typ HandleableType
	cmd handler.Command
	qry handler.Query
}

func (h *SimpleHandleable) Type() {

	return h.typ;
}

func (h *SimpleHandleable) Command() handler.Command {

	return h.cmd
}

func (h *SimpleHandleable) Query() handler.Query {

	return h.qry
}

// Helper methods to make creating it easier
func NewCommand(cmd handler.Command) Handleable {

	return &SimpleHandleable{CMD, cmd, nil}
}

func NewQuery(qry handler.Query) Handleable {

	return &SimpleHandleable{QRY, qry, nil}
}

package adapter

import (
	"github.com/domain-query-language/dql-server/src/server/vm/handler"
)

type Adapter interface {

	Next() (Handleable, error)
}

// Make it easy to get the correct type out, no need for casting based on "HandleableType"
type Handleable struct {

	typ HandleableType
	command handler.Command
	query handler.Query
}

type HandleableType string

const (
	CMD HandleableType = "command"
	QRY = "query"
)

// Helper methods to make creating it easier
func NewCommand(cmd handler.Command) *Handleable {

	return &Handleable{CMD, cmd, nil}
}

func NewQuery(qry handler.Query) *Handleable {

	return &Handleable{QRY, qry, nil}
}

Refactor to just use a struct instead of an interface


package main

import (
	"io/ioutil"
	"net/http/httptest"
	"strings"
	"testing"

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

func TestNonHandledEndpoint(t *testing.T) {
	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	w := httptest.NewRecorder()
	NewRouter().ServeHTTP(w, req)

	resp := w.Result()
	body, _ := ioutil.ReadAll(resp.Body)
	respString := string(body)

	require.Equal(t, 404, resp.StatusCode)
	require.Contains(t, strings.ToLower(respString), "not found")
}

func TestRoot(t *testing.T) {
	req := httptest.NewRequest("GET", "http://example.com/", nil)
	w := httptest.NewRecorder()
	NewRouter().ServeHTTP(w, req)

	resp := w.Result()
	body, _ := ioutil.ReadAll(resp.Body)
	respString := string(body)

	require.Equal(t, 200, resp.StatusCode)
	require.Equal(t, "Welcome!\n", respString)
}

package main

import (
	"io/ioutil"
	"net/http/httptest"
	"strings"
	"testing"

	"encoding/json"
	"github.com/stretchr/testify/require"
	"todolist/repo"
)

func TestNonHandledEndpoint(t *testing.T) {
	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	w := httptest.NewRecorder()
	NewRouter().ServeHTTP(w, req)

	resp := w.Result()
	body, _ := ioutil.ReadAll(resp.Body)
	respString := string(body)

	require.Equal(t, 404, resp.StatusCode)
	require.Contains(t, strings.ToLower(respString), "not found")
}

func TestRoot(t *testing.T) {
	req := httptest.NewRequest("GET", "http://example.com/", nil)
	w := httptest.NewRecorder()
	NewRouter().ServeHTTP(w, req)

	resp := w.Result()
	body, _ := ioutil.ReadAll(resp.Body)
	respString := string(body)

	require.Equal(t, 200, resp.StatusCode)
	require.Equal(t, "Welcome!\n", respString)
}

func TestTodoIndex(t *testing.T) {
	repository = repo.NewInMemoryRepo()
	bytes, _ := json.Marshal(repository.FindAll())
	expected := string(bytes) + "\n"

	req := httptest.NewRequest("GET", "http://example.com/todos", nil)
	w := httptest.NewRecorder()
	NewRouter().ServeHTTP(w, req)

	resp := w.Result()
	body, _ := ioutil.ReadAll(resp.Body)
	respString := string(body)

	require.Equal(t, 200, resp.StatusCode)
	require.Equal(t, expected, respString)
}

Add unit test for the /todos endpoint


package server

import (
	"fmt"
	"html/template"
	"net/http"
	"net/url"
)

func RootHandler(w http.ResponseWriter, r *http.Request, processes []*Process) {
	tmpl, err := template.ParseFiles("templates/root.html")
	if err != nil {
		fmt.Printf("Error parsing template")
	}
	if err := tmpl.Execute(w, processes); err != nil {
		fmt.Printf(err.Error())
		panic(err)
	}
}

func ElectionHandler(w http.ResponseWriter, r *http.Request, processes []*Process) {
	processes[1].God <- &Force{Election: &True}
	fmt.Fprintf(w, "Forcing an election")
}

func LagHandler(w http.ResponseWriter, r *http.Request) {
	if _, err := template.ParseFiles("templates/lag.html"); err != nil {
		http.Error(w, "Error parsing lag template", http.StatusInternalServerError)
	} else {
		if err := r.ParseForm(); err != nil {
			http.Error(w, "Error parsing lag", http.StatusInternalServerError)
			return
		}
		lag, err := getFormValues(&r.Form)
		if err != nil {
			http.Error(w, "Unable to get form values", http.StatusInternalServerError)
		}
		//	t.Execute(w, userInput)
		fmt.Fprintf(w, "Adding %s lag", lag)
	}
}

func getFormValues(form *url.Values) (lag string, err error) {
	for key, value := range *form {
		switch key {
		case "lag":
			return value[0], nil
		case "processId":
			return value[0], nil
		default:
			return "", fmt.Errorf("Unable to parse form")
		}
	}
	return "", fmt.Errorf("No form values")
}

package server

import (
	"fmt"
	"html/template"
	"net/http"
)

func RootHandler(w http.ResponseWriter, r *http.Request, processes []*Process) {
	tmpl, err := template.ParseFiles("templates/root.html")
	if err != nil {
		fmt.Printf("Error parsing template")
	}
	if err := tmpl.Execute(w, processes); err != nil {
		fmt.Printf(err.Error())
		panic(err)
	}
}

func ElectionHandler(w http.ResponseWriter, r *http.Request, processes []*Process) {
	processes[1].God <- &Force{Election: &True}
	fmt.Fprintf(w, "Forcing an election")
}

func LagHandler(w http.ResponseWriter, r *http.Request) {
	if _, err := template.ParseFiles("templates/lag.html"); err != nil {
		http.Error(w, "Error parsing lag template", http.StatusInternalServerError)
	} else {
		if err := r.ParseForm(); err != nil {
			http.Error(w, "Error parsing lag", http.StatusInternalServerError)
			return
		}
		fmt.Fprintf(w, "Adding lag")
	}
}

Remove form submission, simply add lag


package glock

import (
	"github.com/stathat/consistent"
)

func initServersPool(endpoints []string) *consistent.Consistent {
	cons := consistent.New()
	for _, endpoint := range endpoints {
		// TODO: First check if endpoint is live
		cons.Add(endpoint)
	}
	return cons
}

package glock

import (
	"net"

	"github.com/stathat/consistent"
)

func initServersPool(endpoints []string) *consistent.Consistent {
	cons := consistent.New()
	for _, endpoint := range endpoints {
		conn, err := net.Dial("tcp", endpoint)
		if err == nil {
			cons.Add(endpoint)
			conn.Close()
		}
	}
	return cons
}

Check endpoint status first before adding into the hash table


package retry

import (
	"net/http"
	"time"

	"github.com/cenkalti/backoff/v4"
	"github.com/pkg/errors"
)

// MaybeRetryRequest is an internal implementation detail of this module. It
// shouldn't be used by users of the geoipupdate Go library. You can use the
// RetryFor field of geoipupdate.Config if you'd like to retry failed requests
// when using the library directly.
func MaybeRetryRequest(c *http.Client, retryFor time.Duration, req *http.Request) (*http.Response, error) {
	exp := backoff.NewExponentialBackOff()
	exp.MaxElapsedTime = retryFor
	var resp *http.Response
	err := backoff.Retry(
		func() error {
			var err error
			resp, err = c.Do(req)
			return errors.Wrap(err, "error performing http request")
		},
		exp,
	)
	return resp, err
}

package retry

import (
	"net/http"
	"time"

	"github.com/cenkalti/backoff/v4"
	"github.com/pkg/errors"
)

// MaybeRetryRequest is an internal implementation detail of this module. It
// shouldn't be used by users of the geoipupdate Go library. You can use the
// RetryFor field of geoipupdate.Config if you'd like to retry failed requests
// when using the library directly.
func MaybeRetryRequest(c *http.Client, retryFor time.Duration, req *http.Request) (*http.Response, error) {
	if retryFor < 0 {
		return nil, errors.New("negative retry duration")
	}
	exp := backoff.NewExponentialBackOff()
	exp.MaxElapsedTime = retryFor
	var resp *http.Response
	err := backoff.Retry(
		func() error {
			var err error
			resp, err = c.Do(req)
			return errors.Wrap(err, "error performing http request")
		},
		exp,
	)
	return resp, err
}

Raise errors on incorrect library usage


package kitsu

import "testing"

func TestNewClient(t *testing.T) {
	c := NewClient(nil)

	if got, want := c.BaseURL.String(), defaultBaseURL; got != want {
		t.Errorf("NewClient BaseURL is %v, want %v", got, want)
	}
}

func TestNewRequest(t *testing.T) {
	c := NewClient(nil)

	inURL, outURL := "/foo", defaultBaseURL+"foo"
	req, _ := c.NewRequest("GET", inURL, nil)

	// Test that the base URL is added to the endpoint.
	if got, want := req.URL.String(), outURL; got != want {
		t.Errorf("NewRequest(%q) URL is %q, want %q", inURL, got, want)
	}
}

func TestClient_NewRequest_badEndpoint(t *testing.T) {
	c := NewClient(nil)
	inURL := "%foo"
	_, err := c.NewRequest("GET", inURL, nil)
	if err == nil {
		t.Errorf("NewRequest(%q) should return parse err", inURL)
	}
}

package kitsu

import (
	"net/url"
	"testing"
)

func TestNewClient(t *testing.T) {
	c := NewClient(nil)

	if got, want := c.BaseURL.String(), defaultBaseURL; got != want {
		t.Errorf("NewClient BaseURL is %v, want %v", got, want)
	}
}

func TestClient_NewRequest(t *testing.T) {
	c := NewClient(nil)

	inURL, outURL := "/foo", defaultBaseURL+"foo"
	req, _ := c.NewRequest("GET", inURL, nil)

	// Test that the client's base URL is added to the endpoint.
	if got, want := req.URL.String(), outURL; got != want {
		t.Errorf("NewRequest(%q) URL is %q, want %q", inURL, got, want)
	}
}

func TestClient_NewRequest_badURL(t *testing.T) {
	c := NewClient(nil)
	inURL := ":"
	_, err := c.NewRequest("GET", inURL, nil)
	if err == nil {
		t.Errorf("NewRequest(%q) should return parse err", inURL)
	}
	if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
		t.Errorf("Expected URL parse error, got %+v", err)
	}
}

Add parse error test for bad URL case


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

// +build gccgo

package vsphere

const (
	providerType = "vsphere"
)

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

// +build gccgo

// This file exists so that this package will remain importable under
// GCCGo. In particular, see provider/all/all.go. All other files in
// this package do not build under GCCGo (see lp:1440940).

package vsphere

const (
	providerType = "vsphere"
)

Add a comment explaining the reason for the build constraints.


package main

import (
  "log"
  "os"
  "path"
)

func main() {
  if len(os.Args) != 3 {
    log.Fatalf("Usage: %s input-file output-file", path.Base(os.Args[0]))
  }
  i, err := os.Open(os.Args[1])
  if err != nil {
    log.Fatalf("Cannot open %q for reading", os.Args[1])
  }
  defer i.Close()
  o, err := os.Create(os.Args[2])
  if err != nil {
    log.Fatalf("Cannot create new file %q", os.Args[2])
  }
  defer o.Close()
}

package main

import (
  "bufio"
  "io"
  "log"
  "os"
  "path"
)

func main() {
  if len(os.Args) != 3 {
    log.Fatalf("Usage: %s input-file output-file", path.Base(os.Args[0]))
  }

  i, err := os.Open(os.Args[1])
  if err != nil {
    log.Fatalf("Cannot open %q for reading: %v", os.Args[1], err)
  }
  defer i.Close()
  r := bufio.NewReader(i)

  o, err := os.Create(os.Args[2])
  if err != nil {
    log.Fatalf("Cannot create new file %q: %v", os.Args[2], err)
  }
  defer o.Close()
  w := bufio.NewWriter(o)

  for {
    line, err := r.ReadString('\n')
    if len(line) > 0 {
      if _, werr := w.WriteString(line); werr != nil {
        log.Fatalf("Error writing to file: %v", werr)
      }
    }
    if err == io.EOF {
      break
    }
    if err != nil {
      log.Fatalf("Error whilst reading file: %v", err)
    }
  }
}

Add reading/writing logic (but at the moment just echo--no processing logic).


// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0

package globalvar

import (
	"log"
)

const Version = "4.66.0"
const ReleaseDate = "2022-03-04"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}

// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0

package globalvar

import (
	"log"
)

const Version = "4.66.0"
const ReleaseDate = "2022-03-02"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}

Update release date with 2022-03-02


package g

import (
	"time"
)

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

package g

import (
	"time"
)

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

Update cfg.json in release package.


package runewidth

import (
	"syscall"
)

var (
	kernel32   = syscall.NewLazyDLL("kernel32")
	procGetACP = kernel32.NewProc("GetACP")
)

func IsEastAsian() bool {
	r1, _, _ := procGetACP.Call()
	if r1 == 0 {
		return false
	}

	switch int(r1) {
	case 932, 51932, 936, 949, 950:
		return true
	}

	return false
}

package runewidth

import (
	"syscall"
)

var (
	kernel32               = syscall.NewLazyDLL("kernel32")
	procGetConsoleOutputCP = kernel32.NewProc("GetConsoleOutputCP")
)

func IsEastAsian() bool {
	r1, _, _ := procGetConsoleOutputCP.Call()
	if r1 == 0 {
		return false
	}

	switch int(r1) {
	case 932, 51932, 936, 949, 950:
		return true
	}

	return false
}

Use GetConsoleCP instead of GetACP


package util

import (
	"encoding/json"
	"io"
)

// DecodeJSON decodes json
func DecodeJSON(src io.Reader, dst interface{}) error {
	decoder := json.NewDecoder(src)
	err := decoder.Decode(dst)
	return err
}

// EncodeJSON encodes json
func EncodeJSON(dst io.Writer, src interface{}) error {
	encoder := json.NewEncoder(dst)
	err := encoder.Encode(src)
	return err
}

func WriteErrorJSON(dst io.Writer, errorMsg string) error {
	response := make(map[string]interface{})
	response["ok"] = false
	response["failureReason"] = "Request does not have the header \"Content-Type: application-json\""
	return EncodeJSON(dst, response)
}

Add utility function for writing failure JSON msgs


package main

import (
	"fmt"
)

func main() {
	fmt.Printf("Hello world!\n")
}

package main

import (
	"fmt"
)

func main() {

	for i := 1; i <= 10; i++ {
		sum := SumN(i)
		list := ListDivisors(sum)

		fmt.Printf("%02d: %d %v\n", i, sum, list)
	}
}

func SumN(n int) int {
	return (n * (n + 1)) / 2
}

func ListDivisors(n int) []int {

	divisors := make([]int, 0)

	for i := 1; i <= n/2; i++ {
		if n%i == 0 {
			divisors = append(divisors, i)
		}
	}

	divisors = append(divisors, n)
	return divisors
}

Add Sum and Divisor Algorithms


package client

import (
	"time"

	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
)

type Client interface {
	Init()
	Call(ctx context.Context, serviceName, endpoint string, req proto.Message, res proto.Message) error
}

var defaultTimeout time.Duration = 1 * time.Second

var DefaultClient Client = NewRabbitClient()

func Request(ctx context.Context, serviceName, endpoint string, req proto.Message, res proto.Message) error {
	return DefaultClient.Call(ctx, serviceName, endpoint, req, res)
}

package client

import (
	"time"

	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
)

type Client interface {
	Init()
	Call(ctx context.Context, service, endpoint string, req proto.Message, res proto.Message) error
}

var defaultTimeout time.Duration = 1 * time.Second

var DefaultClient Client = NewRabbitClient()

// Request sends a request to a service using the DefaultClient
func Request(ctx context.Context, service, endpoint string, req proto.Message, res proto.Message) error {
	return DefaultClient.Call(ctx, service, endpoint, req, res)
}

Tidy up serviceName variable naming


package mock

import (
	"testing"

	"github.com/micro/go-micro/errors"

	"golang.org/x/net/context"
)

func TestClient(t *testing.T) {
	response := []MockResponse{
		{Method: "Foo.Bar", Response: map[string]interface{}{"foo": "bar"}},
		{Method: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
	}

	c := NewClient(Response("go.mock", response))

	for _, r := range response {
		req := c.NewJsonRequest("go.mock", r.Method, map[string]interface{}{"foo": "bar"})
		var rsp map[string]interface{}

		err := c.Call(context.TODO(), req, &rsp)

		if err != r.Error {
			t.Fatalf("Expecter error %v got %v", r.Error, err)
		}

		t.Log(rsp)
	}

}

package mock

import (
	"testing"

	"github.com/micro/go-micro/errors"

	"golang.org/x/net/context"
)

func TestClient(t *testing.T) {
	type TestRequest struct {
		Param string
	}

	response := []MockResponse{
		{Method: "Foo.Bar", Response: map[string]interface{}{"foo": "bar"}},
		{Method: "Foo.Struct", Response: &TestRequest{Param: "aparam"}},
		{Method: "Foo.Fail", Error: errors.InternalServerError("go.mock", "failed")},
	}

	c := NewClient(Response("go.mock", response))

	for _, r := range response {
		req := c.NewJsonRequest("go.mock", r.Method, map[string]interface{}{"foo": "bar"})
		var rsp interface{}

		err := c.Call(context.TODO(), req, &rsp)

		if err != r.Error {
			t.Fatalf("Expecter error %v got %v", r.Error, err)
		}

		t.Log(rsp)
	}

}

Test struct works with mock client


// Copyright 2011 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.

// +build 386 arm arm64 ppc64 ppc64le appengine

package crc32

// The file contains the generic version of updateCastagnoli which does
// slicing-by-8, or uses the fallback for very small sizes.
func updateCastagnoli(crc uint32, p []byte) uint32 {
	// only use slicing-by-8 when input is >= 16 Bytes
	if len(p) >= 16 {
		return updateSlicingBy8(crc, castagnoliTable8, p)
	}
	return update(crc, castagnoliTable, p)
}

func updateIEEE(crc uint32, p []byte) uint32 {
	// only use slicing-by-8 when input is >= 16 Bytes
	if len(p) >= 16 {
		iEEETable8Once.Do(func() {
			iEEETable8 = makeTable8(IEEE)
		})
		return updateSlicingBy8(crc, iEEETable8, p)
	}
	return update(crc, IEEETable, p)
}

// Copyright 2011 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.

// +build 386 arm arm64 ppc64 ppc64le appengine gccgo

package crc32

// The file contains the generic version of updateCastagnoli which does
// slicing-by-8, or uses the fallback for very small sizes.
func updateCastagnoli(crc uint32, p []byte) uint32 {
	// only use slicing-by-8 when input is >= 16 Bytes
	if len(p) >= 16 {
		return updateSlicingBy8(crc, castagnoliTable8, p)
	}
	return update(crc, castagnoliTable, p)
}

func updateIEEE(crc uint32, p []byte) uint32 {
	// only use slicing-by-8 when input is >= 16 Bytes
	if len(p) >= 16 {
		iEEETable8Once.Do(func() {
			iEEETable8 = makeTable8(IEEE)
		})
		return updateSlicingBy8(crc, iEEETable8, p)
	}
	return update(crc, IEEETable, p)
}

Add gccgo to generic build


package main

import "time"

func main() {
	now := time.Now().Unix()
	metrics := []string{"example"}

	var accessTimes map[string]int64
	// accessTimes = make(map[string]int64)
	for _, m := range metrics {
		accessTimes[m] = now
	}
}

package main

import "time"

func main() {
	now := time.Now().Unix()
	metrics := []string{"example"}

	var accessTimes map[string]int64 // ISSUE
	for _, m := range metrics {
		accessTimes[m] = now
	}
}

Add comment to example file


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

package testing

import (
	"time"

	"launchpad.net/juju-core/utils"
)

// ShortWait is a reasonable amount of time to block waiting for something that
// shouldn't actually happen. (as in, the test suite will *actually* wait this
// long before continuing)
const ShortWait = 50 * time.Millisecond

// LongWait is used when something should have already happened, or happens
// quickly, but we want to make sure we just haven't missed it. As in, the test
// suite should proceed without sleeping at all, but just in case. It is long
// so that we don't have spurious failures without actually slowing down the
// test suite
const LongWait = 10 * time.Second

var LongAttempt = &utils.AttemptStrategy{
	Total: LongWait,
	Delay: ShortWait,
}

// SupportedSeries lists the series known to Juju.
var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty"}

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

package testing

import (
	"time"

	"launchpad.net/juju-core/utils"
)

// ShortWait is a reasonable amount of time to block waiting for something that
// shouldn't actually happen. (as in, the test suite will *actually* wait this
// long before continuing)
const ShortWait = 50 * time.Millisecond

// LongWait is used when something should have already happened, or happens
// quickly, but we want to make sure we just haven't missed it. As in, the test
// suite should proceed without sleeping at all, but just in case. It is long
// so that we don't have spurious failures without actually slowing down the
// test suite
const LongWait = 10 * time.Second

var LongAttempt = &utils.AttemptStrategy{
	Total: LongWait,
	Delay: ShortWait,
}

// SupportedSeries lists the series known to Juju.
var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty", "utopic"}

Update tests to support "utopic"


// +build !linux

package lxc

import "github.com/docker/docker/daemon/execdriver"

func setHostname(hostname string) error {
	panic("Not supported on darwin")
}

func finalizeNamespace(args *execdriver.InitArgs) error {
	panic("Not supported on darwin")
}

// +build !linux

package lxc

func setHostname(hostname string) error {
	panic("Not supported on darwin")
}

func finalizeNamespace(args *InitArgs) error {
	panic("Not supported on darwin")
}

Fix lxc driver build issue on Mac OS X


package cf

import (
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/urfave/cli"
)

func deleteStack(ctx *cli.Context) error {
	name := ctx.Args().First()
	if name == "" {
		cli.ShowSubcommandHelp(ctx)
		return nil
	}

	_, err := cfClient.DeleteStack(&cloudformation.DeleteStackInput{
		StackName: aws.String(name),
	})
	if err != nil {
		log.Fatalln("ERROR", err)
	}

	printStackEvents(name)
	return nil
}

package cf

import (
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/sam701/awstools/sess"
	"github.com/urfave/cli"
)

func deleteStack(ctx *cli.Context) error {
	name := ctx.Args().First()
	if name == "" {
		cli.ShowSubcommandHelp(ctx)
		return nil
	}

	cfClient = cloudformation.New(sess.FromEnvVar())
	_, err := cfClient.DeleteStack(&cloudformation.DeleteStackInput{
		StackName: aws.String(name),
	})
	if err != nil {
		log.Fatalln("ERROR", err)
	}

	printStackEvents(name)
	return nil
}

Fix invalid memory address by CF delete operation