package deje

type Document struct {
	Channel    IRCLocation
	Events     EventSet
	Syncs      SyncSet
	Timestamps TimestampSet `json:""`
}

func NewDocument() Document {
	return Document{
		Events: make(EventSet),
		Syncs:  make(SyncSet),
	}
}

package deje

// A document is a single managed DEJE object, associated with
// a single immutable IRCLocation, and self-describing its
// actions and permissions as part of the content.
//
// The content of a Document is the result of applying the
// "official" chain of history, in much the same way that the
// Bitcoin ledger is the result of playing through the transactions
// in every block of the longest valid blockchain.
type Document struct {
	Channel    IRCLocation
	Events     EventSet
	Syncs      SyncSet
	Timestamps TimestampSet `json:""`
}

// Used for serializing and deserializing docs to files.
//
// This allows us to use more complicated structures for actual
// documents, that allow for storing Timestamps, and other data
// that we must not trust the file to provide.
type DocumentFile struct {
	Channel IRCLocation
	Events  EventSet
	Syncs   SyncSet
}

// Create a new, blank Document, with fields initialized.
func NewDocument() Document {
	return Document{
		Events: make(EventSet),
		Syncs:  make(SyncSet),
	}
}

// Copies the data from a DocumentFile into a Document.
func (d *Document) FromFile(df *DocumentFile) {
	d.Channel = df.Channel
	d.Events = df.Events
	d.Syncs = df.Syncs
}

// Copies the data from a Document into a DocumentFile.
func (d *Document) ToFile() *DocumentFile {
	return &DocumentFile{
		Channel: d.Channel,
		Events:  d.Events,
		Syncs:   d.Syncs,
	}
}

Split off DocumentFile type for serialization/deserialization


package main

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

func main() {
	raw, err := ioutil.ReadFile("activity.dat")

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

	encoded := strings.Split(string(raw), "\\n")
	var decoded []byte

	for _, line := range encoded {
		b, err := base64.StdEncoding.DecodeString(line)

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

		decoded = append(decoded, b...)
	}

	fmt.Println(decoded)
}

package main

import (
	"bytes"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"strings"
	"time"
)

type trackPoint struct {
	Longitude float32
	Latitude  float32
	Elevation float32
	Time      time.Time
}

func read(r io.Reader) (trackPoint, error) {
	var point trackPoint
	var timestamp int64

	if err := binary.Read(r, binary.BigEndian, &timestamp); err != nil {
		return trackPoint{}, nil
	}

	point.Time = time.Unix(timestamp/1000, timestamp%1000*1000)

	if err := binary.Read(r, binary.BigEndian, &point.Longitude); err != nil {
		return trackPoint{}, err
	}

	if err := binary.Read(r, binary.BigEndian, &point.Latitude); err != nil {
		return trackPoint{}, err
	}

	if err := binary.Read(r, binary.BigEndian, &point.Elevation); err != nil {
		return trackPoint{}, err
	}

	rest := make([]byte, 18)

	if err := binary.Read(r, binary.BigEndian, rest); err != nil {
		return trackPoint{}, err
	}

	return point, nil
}

func main() {
	raw, err := ioutil.ReadFile("activity.dat")

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

	encoded := strings.Split(string(raw), "\\n")
	var decoded []byte

	for _, line := range encoded {
		var b []byte
		b, err = base64.StdEncoding.DecodeString(line)

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

		decoded = append(decoded, b...)
	}

	buf := bytes.NewBuffer(decoded)
	var size int32

	if err = binary.Read(buf, binary.BigEndian, &size); err != nil {
		log.Fatal(err)
	}

	fmt.Println(size)

	for i := 0; i < int(size); i++ {
		point, err := read(buf)

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

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

Add GPS trace decoding code


package socket

import (
	"time"
	"github.com/neliseev/logger"
)

// Defaults
const maxTCPQueries  int           = 256
const tcpIdleTimeout time.Duration = 60 * time.Second
const rtimeout       time.Duration = 2 * time.Second // Socket read timeout
const msgSep         []byte          = []byte(":")
const udpMsgSize     int           = 508             // RFC 791 (Min IP Size - Max IP Header Size - UDP Header Size)
const maxMsgSize     int           = 128             // ToDo Set configurable?

// Init logger subsystem
var log logger.Log

func init() {
	log.New()
}

package socket

import (
	"time"
	"github.com/neliseev/logger"
)

// Defaults vars
var msgSep = byte(":")

// Constants
const maxTCPQueries  int           = 256
const tcpIdleTimeout time.Duration = 60 * time.Second
const rtimeout       time.Duration = 2 * time.Second // Socket read timeout
const udpMsgSize     int           = 508             // RFC 791 (Min IP Size - Max IP Header Size - UDP Header Size)
const maxMsgSize     int           = 128             // ToDo Set configurable?

// Init logger subsystem
var log logger.Log

func init() {
	log.New()
}

Fix errors with types in conditions


package vsphere

import "github.com/cloudfoundry/bosh-bootloader/storage"

type TemplateGenerator struct{}

func NewTemplateGenerator() TemplateGenerator {
	return TemplateGenerator{}
}

func (t TemplateGenerator) Generate(state storage.State) string {
	return ""
}

package vsphere

import "github.com/cloudfoundry/bosh-bootloader/storage"

type TemplateGenerator struct{}

func NewTemplateGenerator() TemplateGenerator {
	return TemplateGenerator{}
}

func (t TemplateGenerator) Generate(state storage.State) string {
	return `output "dummy" { value = "dummy" }`
}

Add dummy terraform output because terraform output -json exits 1


package models

type Config struct {
    Id                     string `rethink:"id,omitempty"`
    Guild                  string `rethink:"guild"`

    Prefix                 string `rethink:"prefix"`

    CleanupEnabled         bool `rethink:"cleanup_enabled"`

    AutoRepliesEnabled     bool `rethink:"auto_replies_enabled"`
    AutoReplies            map[string]string `rethink:"auto_replies"`

    AnnouncementsEnabled   bool `rethink:"announcements_enabled"`
    AnnouncementsChannel   string `rethink:"announcements_channel"`

    WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
    WelcomeNewUsersText    string `rethink:"welcome_new_users_text"`
}

func (c Config) Default(guild string) Config {
    return Config{
        Guild: guild,

        Prefix: "%",

        CleanupEnabled: false,

        AutoRepliesEnabled: false,
        AutoReplies: make(map[string]string),

        AnnouncementsEnabled: false,
        AnnouncementsChannel: "",

        WelcomeNewUsersEnabled: false,
        WelcomeNewUsersText: "",
    }
}

package models

type Config struct {
    Id                     string `rethink:"id,omitempty"`
    Guild                  string `rethink:"guild"`

    Prefix                 string `rethink:"prefix"`

    CleanupEnabled         bool `rethink:"cleanup_enabled"`

    AnnouncementsEnabled   bool `rethink:"announcements_enabled"`
    AnnouncementsChannel   string `rethink:"announcements_channel"`

    WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
    WelcomeNewUsersText    string `rethink:"welcome_new_users_text"`
}

func (c Config) Default(guild string) Config {
    return Config{
        Guild: guild,

        Prefix: "%",

        CleanupEnabled: false,

        AnnouncementsEnabled: false,
        AnnouncementsChannel: "",

        WelcomeNewUsersEnabled: false,
        WelcomeNewUsersText: "",
    }
}

Remove autoreplies from db template


package ops

import (
	"bsearch/index"
)

type HeaderCollector interface {
	Add(key, value string)
}

// QueryOp is the interface for search queries implemented by everything
// that will return documents. Each QueryOp is assumed to define access
// to a sorted set of documents sorted on IbDoc.order.
type QueryOp interface {

	// CurrentDoc returns the last document returned by NextDoc
	// or the first document from this query if NextDoc hasn't been
	// called yet.
	CurrentDoc() *index.IbDoc

	// NextDoc returns the document equal to `search` or next higher.
	NextDoc(search *index.IbDoc) *index.IbDoc

	// Recursively adds any headers this might need to return.
	ProcessHeaders(hc HeaderCollector)
}

// QueryContainer is an interface for ops that not only implement sets of
// documents like QueryOp, but are also containers for other queries.
// This applies to intersections and unions.
type QueryContainer interface {
	QueryOp
	// Add adds one or more QueryOp to the container.
	Add(...QueryOp)
}

package ops

import (
	"bsearch/index"
)

type HeaderCollector interface {
	Add(key, value string)
}

// QueryOp is the interface for search queries implemented by everything
// that will return documents. Each QueryOp is assumed to define access
// to a sorted set of documents sorted on IbDoc.order.
type QueryOp interface {

	// CurrentDoc returns the last document returned by NextDoc
	// or the first document from this query if NextDoc hasn't been
	// called yet.
	// Can't be called on invalid or exhausted QueryOp.
	CurrentDoc() *index.IbDoc

	// NextDoc returns the document equal to `search` or next higher.
	NextDoc(search *index.IbDoc) *index.IbDoc

	// Recursively adds any headers this might need to return.
	ProcessHeaders(hc HeaderCollector)
}

// QueryContainer is an interface for ops that not only implement sets of
// documents like QueryOp, but are also containers for other queries.
// This applies to intersections and unions.
type QueryContainer interface {
	QueryOp
	// Add adds one or more QueryOp to the container.
	Add(...QueryOp)
}

Document that CurrentDoc is not callable on invalid ops.


package koding

import (
	"koding/kites/kloud/klient"
	"time"
)

type infoFunc func(format string, formatArgs ...interface{})

// GetInfoLogger returns a customized logger with a another prefix. Usually for
// user based logging.
func (p *Provider) GetInfoLogger(prefix string) infoFunc {
	return func(format string, formatArgs ...interface{}) {
		format = "[%s] " + format
		args := []interface{}{prefix}
		args = append(args, formatArgs...)
		p.Log.Info(format, args...)
	}
}

// IsKiteReady returns true if Klient is ready and it can receive a ping.
func (p *Provider) IsKlientReady(querystring string) bool {
	// FIXME: Hack. Connecting to Klient slows the tests down. Disable it
	// temporarily, we are gonna test the correct behaviour later.
	if p.Test {
		return false
	}
	klientRef, err := klient.NewWithTimeout(p.Kite, querystring, time.Minute*2)
	if err != nil {
		p.Log.Warning("Connecting to remote Klient instance err: %s", err)
		return false
	}

	defer klientRef.Close()
	p.Log.Debug("Sending a ping message")
	if err := klientRef.Ping(); err != nil {
		p.Log.Debug("Sending a ping message err:", err)
		return false
	}

	return true
}

package koding

import (
	"koding/kites/kloud/klient"
	"time"
)

type infoFunc func(format string, formatArgs ...interface{})

// GetInfoLogger returns a customized logger with a another prefix. Usually for
// user based logging.
func (p *Provider) GetInfoLogger(prefix string) infoFunc {
	return func(format string, formatArgs ...interface{}) {
		format = "[%s] " + format
		args := []interface{}{prefix}
		args = append(args, formatArgs...)
		p.Log.Info(format, args...)
	}
}

// IsKiteReady returns true if Klient is ready and it can receive a ping.
func (p *Provider) IsKlientReady(querystring string) bool {
	klientRef, err := klient.NewWithTimeout(p.Kite, querystring, time.Minute*2)
	if err != nil {
		p.Log.Warning("Connecting to remote Klient instance err: %s", err)
		return false
	}

	defer klientRef.Close()
	p.Log.Debug("Sending a ping message")
	if err := klientRef.Ping(); err != nil {
		p.Log.Debug("Sending a ping message err:", err)
		return false
	}

	return true
}

Remove temporary hack that disables klient connection check when on test mode.


package main

import (
	"fmt"
	"strings"
)

// HelpForHelp shows overall usage information for the BigV client, including a list of available commands.
func (cmds *CommandSet) HelpForHelp() {
	// TODO(telyn): write real usage information
	fmt.Println("bigv command-line client (the new, cool one)")
	fmt.Println()
	fmt.Println("There would be some usage output here if I had actually written any.")
	fmt.Println()
}

// Help implements the help command, which gives usage information specific to each command. Usage: bigv help [command]
func (cmds *CommandSet) Help(args []string) {
	if len(args) == 0 {
		cmds.HelpForHelp()
		return
	}

	// please try and keep these in alphabetical order
	switch strings.ToLower(args[0]) {
	case "config":
		cmds.HelpForConfig()
	case "debug":
		cmds.HelpForDebug()
	case "delete":
		cmds.HelpForDelete()
	case "exit":
		cmds.HelpForExitCodes()
	case "exit-codes":
		cmds.HelpForExitCodes()
	case "show":
		cmds.HelpForShow()
	}

}

package main

import (
	"fmt"
	"strings"
)

// HelpForHelp shows overall usage information for the BigV client, including a list of available commands.
func (cmds *CommandSet) HelpForHelp() {
	fmt.Println("bigv command-line client (the new, cool one)")
	fmt.Println()
	fmt.Println("Usage")
	fmt.Println()
	fmt.Println("    go-bigv [flags] <command> [flags] [args]")
	fmt.Println()
	fmt.Println("Commands available")
	fmt.Println()
	fmt.Println("    help, config, create, debug, delete, list, show")
	fmt.Println("    AND MAYBE MORE OR FEWER - THIS LIST IS NOT FINAL")
	fmt.Println()
	fmt.Println("See `go-bigv help <command>` for help specific to a command")
	fmt.Println()
}

// Help implements the help command, which gives usage information specific to each command. Usage: bigv help [command]
func (cmds *CommandSet) Help(args []string) {
	if len(args) == 0 {
		cmds.HelpForHelp()
		return
	}

	// please try and keep these in alphabetical order
	switch strings.ToLower(args[0]) {
	case "config":
		cmds.HelpForConfig()
	case "debug":
		cmds.HelpForDebug()
	case "delete":
		cmds.HelpForDelete()
	case "exit":
		cmds.HelpForExitCodes()
	case "exit-codes":
		cmds.HelpForExitCodes()
	case "show":
		cmds.HelpForShow()
	}

}

Write some real-ish usage information


package day8

import (
	"fmt"

	"github.com/domdavis/adventofcode/2016/day8/display"
)

func Solution() string {
	return fmt.Sprintf("Part 1: %d, Part 2: %s",
		part1(data), "Not yet done")
}

func part1(input string) int {
	s := display.New(50, 6)
	s.BulkTransform(input)
	return s.Count()
}

package day8

import (
	"fmt"

	"github.com/domdavis/adventofcode/2016/day8/display"
)

func Solution() string {
	s := display.New(50, 6)
	s.BulkTransform(data)
	return fmt.Sprintf("Part 1: %d, Part 2:\n%s",
		s.Count(), s)
}

Add day 8 part 2 solution


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

package btrees

// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
	var findLCA func(t, n0, n1 *BTree) (cnt int, ancestor *BTree)
	findLCA = func(t, n0, n1 *BTree) (cnt int, ancestor *BTree) {
		if t == nil {
			return 0, nil // Base case.
		}

		// Post-order walk.
		lc, la := findLCA(t.left, n0, n1)
		if lc == 2 {
			return lc, la
		}
		rc, ra := findLCA(t.right, n0, n1)
		if rc == 2 {
			return rc, ra
		}

		cnt = lc + rc
		if t == n0 {
			cnt++
		}
		if t == n1 {
			cnt++
		}
		if cnt == 2 {
			ancestor = t
		}
		return cnt, ancestor
	}
	_, a := findLCA(t, n0, n1)
	return a
}

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

package btrees

// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
	var findLCA func(t *BTree) (cnt int, ancestor *BTree)
	findLCA = func(t *BTree) (cnt int, ancestor *BTree) {
		if t == nil {
			return 0, nil // Base case.
		}

		// Post-order walk.
		lc, la := findLCA(t.left)
		if lc == 2 {
			return lc, la
		}
		rc, ra := findLCA(t.right)
		if rc == 2 {
			return rc, ra
		}

		cnt = lc + rc
		if t == n0 {
			cnt++
		}
		if t == n1 {
			cnt++
		}
		if cnt == 2 {
			ancestor = t
		}
		return cnt, ancestor
	}

	_, a := findLCA(t)
	return a
}

Remove unnecessary variable passing to function literal


package task

import (
	"reflect"
	"testing"
)

func TestTaskState(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.State
	want := TaskStateUnknown
	if want != got {
		t.Errorf("Incorrect task state: want %q, got %q", want, got)
	}
}

func TestTaskCommand(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.Command
	want := "dummy"
	if want != got {
		t.Errorf("Incorrect task command: want %q, got %q", want, got)
	}
}

func TestTaskArgs(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.Args
	want := []string{"foo", "bar"}
	if !reflect.DeepEqual(want, got) {
		t.Errorf("Incorrect task args: want %q, got %q", want, got)
	}
}

func TestTaskTimeReceived(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.TimeReceived
	var want int64 = 0
	if want != got {
		t.Errorf("Incorrect task time received: want %q, got %q", want, got)
	}
}

package task

import (
	"reflect"
	"testing"
)

func TestTaskState(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.State
	want := TaskStateUnknown
	if want != got {
		t.Errorf("Incorrect task state: want %q, got %q", want, got)
	}
}

func TestTaskCommand(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.Command
	want := "dummy"
	if want != got {
		t.Errorf("Incorrect task command: want %q, got %q", want, got)
	}
}

func TestTaskArgs(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")
	got := dummyTask.Args
	want := []string{"foo", "bar"}
	if !reflect.DeepEqual(want, got) {
		t.Errorf("Incorrect task args: want %q, got %q", want, got)
	}
}

func TestTaskTimeReceivedProcessed(t *testing.T) {
	dummyTask := NewTask("dummy", "foo", "bar")

	// Task time received and processed should be 0 when initially created
	var want int64 = 0

	got := dummyTask.TimeReceived
	if want != got {
		t.Errorf("Incorrect task time received: want %q, got %q", want, got)
	}

	got = dummyTask.TimeProcessed
	if want != got {
		t.Errorf("Incorrect task time processed: want %q, got %q", want, got)
	}
}

Add unit test for task time processed


package cache

import (
	"encoding/json"
	"github.com/centurylinkcloud/clc-go-cli/state"
	"time"
)

const (
	LONG_AUTOCOMPLETE_REFRESH_TIMEOUT = 30 // seconds
)

func Put(key string, opts []string) {
	data, err := json.Marshal(opts)
	if err == nil {
		state.WriteToFile(data, key, 0666)
	}
}

func Get(key string) ([]string, bool) {
	info, err := state.GetFileInfo(key)
	if err != nil {
		return nil, false
	}

	if time.Now().Sub(info.ModTime()) > time.Second*LONG_AUTOCOMPLETE_REFRESH_TIMEOUT {
		return nil, false
	}

	data, err := state.ReadFromFile(key)
	if err != nil {
		return nil, false
	}

	opts := []string{}
	err = json.Unmarshal(data, &opts)
	if err != nil {
		return nil, false
	}

	return opts, true
}

package cache

import (
	"encoding/json"
	"github.com/centurylinkcloud/clc-go-cli/state"
	"time"
)

var (
	LONG_AUTOCOMPLETE_REFRESH_TIMEOUT = 30 // seconds
)

func Put(key string, opts []string) {
	data, err := json.Marshal(opts)
	if err == nil {
		state.WriteToFile(data, key, 0666)
	}
}

func Get(key string) ([]string, bool) {
	info, err := state.GetFileInfo(key)
	if err != nil {
		return nil, false
	}

	if time.Now().Sub(info.ModTime()) > time.Second*time.Duration(LONG_AUTOCOMPLETE_REFRESH_TIMEOUT) {
		return nil, false
	}

	data, err := state.ReadFromFile(key)
	if err != nil {
		return nil, false
	}

	opts := []string{}
	err = json.Unmarshal(data, &opts)
	if err != nil {
		return nil, false
	}

	return opts, true
}

Make a variable out of the refresh timeout for testing purposes


package main

import (
	"fmt"
	"net"
	"os"
	"sync"
	"time"
)

var (
	host string // The host address to scan
)

func init() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
		os.Exit(1)
	}
	host = os.Args[1]
}

func main() {
	d := net.Dialer{Timeout: 10 * time.Second}
	p := make(chan struct{}, 500) // make 500 parallel connection
	wg := sync.WaitGroup{}

	c := func(port int) {
		conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
		if err == nil {
			conn.Close()
			fmt.Printf("%d passed\n", port)
		}
		<-p
		wg.Done()
	}

	wg.Add(65536)
	for i := 0; i < 65536; i++ {
		p <- struct{}{}
		go c(i)
	}

	wg.Wait()
}

package main

import (
	"fmt"
	"net"
	"os"
	"sync"
	"time"
)

var (
	host string // The host address to scan
)

func init() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
		os.Exit(1)
	}
	host = os.Args[1]
}

func main() {
	d := net.Dialer{Timeout: 2 * time.Second}
	p := make(chan struct{}, 500) // make 500 parallel connection
	wg := sync.WaitGroup{}

	c := func(port int) {
		conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
		if err == nil {
			conn.Close()
			fmt.Printf("%d passed\n", port)
		}
		<-p
		wg.Done()
	}

	wg.Add(65536)
	for i := 0; i < 65536; i++ {
		p <- struct{}{}
		go c(i)
	}

	wg.Wait()
}

Move package spork/life to github.com/redforks/life


/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package server

import (
	"os"
	"os/signal"
)

var onlyOneSignalHandler = make(chan struct{})

// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() (stopCh <-chan struct{}) {
	close(onlyOneSignalHandler) // panics when called twice

	stop := make(chan struct{})
	c := make(chan os.Signal, 2)
	signal.Notify(c, shutdownSignals...)
	go func() {
		<-c
		close(stop)
		<-c
		os.Exit(1) // second signal. Exit directly.
	}()

	return stop
}

/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package server

import (
	"os"
	"os/signal"
)

var onlyOneSignalHandler = make(chan struct{})

// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() <-chan struct{} {
	close(onlyOneSignalHandler) // panics when called twice

	stop := make(chan struct{})
	c := make(chan os.Signal, 2)
	signal.Notify(c, shutdownSignals...)
	go func() {
		<-c
		close(stop)
		<-c
		os.Exit(1) // second signal. Exit directly.
	}()

	return stop
}

Remove useless named return value


package local

import (
	db_schema "github.com/creativesoftwarefdn/weaviate/database/schema"
)

func (l *LocalSchemaManager) RegisterSchemaUpdateCallback(callback func(updatedSchema db_schema.Schema)) {
	l.callbacks = append(l.callbacks, callback)
}

func (l *LocalSchemaManager) triggerCallbacks() {
	schema := l.GetSchema()

	for _, cb := range l.callbacks {
		cb(schema)
	}
}

package local

import (
	db_schema "github.com/creativesoftwarefdn/weaviate/database/schema"
)

func (l *localSchemaManager) RegisterSchemaUpdateCallback(callback func(updatedSchema db_schema.Schema)) {
	l.callbacks = append(l.callbacks, callback)
}

func (l *localSchemaManager) triggerCallbacks() {
	schema := l.GetSchema()

	for _, cb := range l.callbacks {
		cb(schema)
	}
}

Extend schema to also be able to store state for a connector.


package accumulate

import (
	"fmt"
	"strings"
	"testing"
)

func echo(c string) string {
	return c
}

var tests = []struct {
	expected  []string
	slice     []string
	converter func(string) string
}{
	{[]string{}, []string{}, echo},
	{[]string{"HELLO", "WORLD"}, []string{"hello", "world"}, strings.ToUpper},
}

func TestAccumulate(t *testing.T) {
	for _, test := range tests {
		actual := Accumulate(test.slice, test.converter)
		if fmt.Sprintf("%s", actual) != fmt.Sprintf("%s", test.expected) {
			t.Errorf("Allergies(%s, %s): expected %s, actual %s", test.slice, test.converter, test.expected, actual)
		}
	}
}

package accumulate

import (
	"fmt"
	"strings"
	"testing"
)

func echo(c string) string {
	return c
}

var tests = []struct {
	expected    []string
	given       []string
	converter   func(string) string
	description string
}{
	{[]string{}, []string{}, echo, "echo"},
	{[]string{"HELLO", "WORLD"}, []string{"hello", "world"}, strings.ToUpper, "upcase"},
}

func TestAccumulate(t *testing.T) {
	for _, test := range tests {
		actual := Accumulate(test.given, test.converter)
		if fmt.Sprintf("%s", actual) != fmt.Sprintf("%s", test.expected) {
			t.Fatalf("Allergies(%s, %s): expected %s, actual %s", test.given, test.converter, test.expected, actual)
		} else {
			t.Logf("PASS: %s %v", test.description, test.given)
		}
	}
}

Tweak test output for accumulate in Go


package gohr

import (
	"fmt"
	"os"

	"golang.org/x/crypto/ssh/terminal"
)

//get number of columns of terminal from crypto subdirectory ssh/terminal
func getCols() int {
	c, _, err := terminal.GetSize(int(os.Stdout.Fd()))
	if err != nil {
		panic(err)
	}
	return c
}

// DrawHr fills a row with '#' by default (if no arguments are provided) or take command line arguments and print each pattern on a new line
func DrawHr(args ...string) {
	cols := getCols()

	if len(args) == 0 {
		for i := 0; i < cols; i++ {
			fmt.Printf("#")
		}
		fmt.Println()
	} else {
		for _, arg := range args {
			l := len(arg)
			for i := 0; i < cols/l; i++ {
				fmt.Printf(arg)
			}
			// Fill ups the remaining columns in the row with part of the pattern
			fmt.Printf("%v\n", arg[:cols%l])
		}
	}
}

package gohr

import (
	"fmt"
	"log"
	"os"

	"golang.org/x/crypto/ssh/terminal"
)

// getWidth gets number of width of terminal from crypto subdirectory ssh/terminal
func getWidth() (int, error) {
	w, _, err := terminal.GetSize(int(os.Stdout.Fd()))
	if err != nil {
		return -1, err
	}
	return w, nil
}

// Draw fills a row with '#' by default (if no arguments are provided) or takes arguments and prints each pattern on a new line.
func Draw(args ...string) {
	w, err := getWidth()
	if err != nil {
		log.Fatalf("Error getting terminal width: %s\n", err)
	}

	if len(args) == 0 {
		for i := 0; i < w; i++ {
			fmt.Printf("#")
		}
		fmt.Printf("\n")
	} else {
		for _, arg := range args {
			l := len(arg)
			for i := 0; i < w/l; i++ {
				fmt.Printf(arg)
			}
			// Fills up the remaining columns in the row with part of the pattern
			fmt.Printf("%s\n", arg[:w%l])
		}
	}
}

Return appropriate error from getWidth()


package static

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"path/filepath"
)

func exists(name string) bool {
	_, err := os.Stat(name)
	return !os.IsNotExist(err)
}

// Static returns a middleware handler that serves static files in the given directory.
func Serve(directories ...interface{}) gin.HandlerFunc {
	fileservers := []http.Handler{}

	for i := 0; i < len(directories); i++ {
		directory, err := filepath.Abs(directories[i].(string))
		if err != nil {
			panic(err)
		}
		fileservers = append(fileservers, http.FileServer(http.Dir(directory)))
	}

	return func(c *gin.Context) {
		for i := 0; i < len(directories); i++ {
			directory := directories[i].(string)
			p := path.Join(directory, c.Request.URL.Path)
			if exists(p) {
				fileservers[i].ServeHTTP(c.Writer, c.Request)
				c.Abort(-1)
				break
			}
		}
	}
}

package static

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"path/filepath"
)

func exists(name string) bool {
	_, err := os.Stat(name)
	return !os.IsNotExist(err)
}

// Static returns a middleware handler that serves static files in the given directory.
func Serve(directories ...interface{}) gin.HandlerFunc {
	fileservers := []http.Handler{}

	for i := 0; i < len(directories); i++ {
		directory, err := filepath.Abs(directories[i].(string))
		if err != nil {
			panic(err)
		}
		fileservers = append(fileservers, http.FileServer(http.Dir(directory)))
	}

	return func(c *gin.Context) {
		for i := 0; i < len(directories); i++ {
			directory := directories[i].(string)
			p := path.Join(directory, c.Request.URL.Path)
			if exists(p) {
				fileservers[i].ServeHTTP(c.Writer, c.Request)
				c.Abort()
				break
			}
		}
	}
}

Delete argument "-1" from Abort()


package std

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

// Y is Y combinator which takes a function whose first argument is itself
// applied to the combinator.
var Y = core.NewLazyFunction(
	core.NewSignature(
		[]string{"function"}, nil, "",
		nil, nil, "",
	),
	func(ts ...*core.Thunk) core.Value {
		if len(ts) != 1 {
			return core.NumArgsError("y", "1")
		}

		xfxx := core.PApp(core.Partial, fxx, ts[0])
		return core.PApp(xfxx, xfxx)
	})

var fxx = core.NewLazyFunction(
	core.NewSignature(
		[]string{"f", "x"}, nil, "",
		nil, nil, "",
	),
	func(ts ...*core.Thunk) core.Value {
		return core.PApp(core.Partial, ts[0], core.PApp(ts[1], ts[1]))
	})

package std

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

// Y is Y combinator which takes a function whose first argument is itself
// applied to the combinator.
var Y = core.NewLazyFunction(
	core.NewSignature(
		[]string{"function"}, nil, "",
		nil, nil, "",
	),
	func(ts ...*core.Thunk) core.Value {
		xfxx := core.PApp(core.Partial, fxx, ts[0])
		return core.PApp(xfxx, xfxx)
	})

var fxx = core.NewLazyFunction(
	core.NewSignature(
		[]string{"f", "x"}, nil, "",
		nil, nil, "",
	),
	func(ts ...*core.Thunk) core.Value {
		return core.PApp(core.Partial, ts[0], core.PApp(ts[1], ts[1]))
	})

Delete unuseful check of number of arguments


package service

import (
	"fmt"
	"strings"

	"github.com/docker/docker/api/client"
	"github.com/docker/docker/cli"
	"github.com/spf13/cobra"
	"golang.org/x/net/context"
)

func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command {

	cmd := &cobra.Command{
		Use:     "rm [OPTIONS] SERVICE",
		Aliases: []string{"remove"},
		Short:   "Remove a service",
		Args:    cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			return runRemove(dockerCli, args)
		},
	}
	cmd.Flags()

	return cmd
}

func runRemove(dockerCli *client.DockerCli, sids []string) error {
	client := dockerCli.Client()

	ctx := context.Background()

	var errs []string
	for _, sid := range sids {
		err := client.ServiceRemove(ctx, sid)
		if err != nil {
			errs = append(errs, err.Error())
			continue
		}
		fmt.Fprintf(dockerCli.Out(), "%s\n", sid)
	}
	if len(errs) > 0 {
		return fmt.Errorf(strings.Join(errs, "\n"))
	}
	return nil
}

package service

import (
	"fmt"
	"strings"

	"github.com/docker/docker/api/client"
	"github.com/docker/docker/cli"
	"github.com/spf13/cobra"
	"golang.org/x/net/context"
)

func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command {

	cmd := &cobra.Command{
		Use:     "rm [OPTIONS] SERVICE [SERVICE...]",
		Aliases: []string{"remove"},
		Short:   "Remove a service",
		Args:    cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			return runRemove(dockerCli, args)
		},
	}
	cmd.Flags()

	return cmd
}

func runRemove(dockerCli *client.DockerCli, sids []string) error {
	client := dockerCli.Client()

	ctx := context.Background()

	var errs []string
	for _, sid := range sids {
		err := client.ServiceRemove(ctx, sid)
		if err != nil {
			errs = append(errs, err.Error())
			continue
		}
		fmt.Fprintf(dockerCli.Out(), "%s\n", sid)
	}
	if len(errs) > 0 {
		return fmt.Errorf(strings.Join(errs, "\n"))
	}
	return nil
}

Fix the usage for `service rm` command


package db

import sq "github.com/lann/squirrel"

// CoreOfferRecordSelect is a sql fragment to help select form queries that
// select into a CoreOfferRecord
var CoreOfferRecordSelect = sq.Select(
	"co.accountid",
	"co.offerid",
).From("offers co")

// CoreOfferRecord is row of data from the `offers` table from stellar-core
type CoreOfferRecord struct {
	Accountid string
	Offerid   int64
}

package db

import sq "github.com/lann/squirrel"

// CoreOfferRecordSelect is a sql fragment to help select form queries that
// select into a CoreOfferRecord
var CoreOfferRecordSelect = sq.Select(
	"co.accountid",
	"co.offerid",
	"co.paysalphanumcurrency",
	"co.paysissuer",
	"co.getsalphanumcurrency",
	"co.getsissuer",
	"co.amount",
	"co.pricen",
	"co.priced",
	"co.price",
).From("offers co")

// CoreOfferRecord is row of data from the `offers` table from stellar-core
type CoreOfferRecord struct {
	Accountid            string
	Offerid              int64
	Paysalphanumcurrency string
	Paysissuer           string
	Getsalphanumcurrency string
	Getsissuer           string
	Amount               int64
	Pricen               int32
	Priced               int32
	Price                int64
}

Add additional columns to CoreOfferRecord


package main

import (
	"github.com/spf13/cobra"
)

var autocompleteTarget string

var cmdAutocomplete = &cobra.Command{
	Use:   "autocomplete",
	Short: "Generate shell autocompletion script",
	Long: `The "autocomplete" command generates a shell autocompletion script.

NOTE: The current version supports Bash only.
      This should work for *nix systems with Bash installed.

By default, the file is written directly to /etc/bash_completion.d
for convenience, and the command may need superuser rights, e.g.:

$ sudo restic autocomplete`,

	DisableAutoGenTag: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := cmdRoot.GenBashCompletionFile(autocompleteTarget); err != nil {
			return err
		}
		return nil
	},
}

func init() {
	cmdRoot.AddCommand(cmdAutocomplete)

	cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/etc/bash_completion.d/restic.sh", "autocompletion file")
	// For bash-completion
	cmdAutocomplete.Flags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
}

package main

import (
	"github.com/spf13/cobra"
)

var cmdAutocomplete = &cobra.Command{
	Use:   "autocomplete",
	Short: "Generate shell autocompletion script",
	Long: `The "autocomplete" command generates a shell autocompletion script.

NOTE: The current version supports Bash only.
      This should work for *nix systems with Bash installed.

By default, the file is written directly to /etc/bash_completion.d
for convenience, and the command may need superuser rights, e.g.:

$ sudo restic autocomplete`,

	DisableAutoGenTag: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := cmdRoot.GenBashCompletionFile(autocompleteTarget); err != nil {
			return err
		}
		return nil
	},
}

var autocompleteTarget string

func init() {
	cmdRoot.AddCommand(cmdAutocomplete)

	cmdAutocomplete.Flags().StringVarP(&autocompleteTarget, "completionfile", "", "/usr/share/bash-completion/completions/restic", "autocompletion file")
	// For bash-completion
	cmdAutocomplete.Flags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
}

Correct bash completion file path


package creational

import "sync"

// PoolObject represents the object to be stored in the Pool.
type PoolObject struct {
}

// Pool represents the pool of objects to use.
type Pool struct {
	*sync.Mutex
	inuse     []*PoolObject
	available []*PoolObject
}

// NewPool creates a new pool.
func NewPool() *Pool {
	return &Pool{}
}

// Acquire acquires a new PoolObject to use from the pool.
// Here acquire creates a new instance of a PoolObject if none available.
func (p *Pool) Acquire() *PoolObject {
	p.Lock()
	var object *PoolObject = nil
	if len(p.available) != 0 {
		object = p.available[0]
		p.available = append(p.available[:0], p.available[1:]...)
		p.inuse = append(p.inuse, object)
	} else {
		object := &PoolObject{}
		p.inuse = append(p.inuse, object)
	}
	p.Unlock()
	return object
}

// Release releases a PoolObject back to the Pool.
func (p *Pool) Release(object *PoolObject) {
	p.Lock()
	p.available = append(p.available, object)
	for i, v := range p.inuse {
		if v == object {
			p.inuse = append(p.inuse[:i], p.inuse[i+1:]...)
			break
		}
	}
	p.Unlock()
}

Add initial version of object pool


package frame

import (
	"fmt"
	"os"
	"strings"

	"github.com/zetamatta/go-windows-netresource"
	"github.com/zetamatta/go-windows-subst"
)

func optionNetUse(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		_, err := netresource.NetUse(piece[0], piece[1])
		if err != nil {
			fmt.Fprintf(os.Stderr, "--netuse: %s: %s\n", arg, err.Error())
		}
	}
}

func optionSubst(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		subst.Define(piece[0], piece[1])
	}
}

package frame

import (
	"strings"

	"github.com/zetamatta/go-windows-netresource"
	"github.com/zetamatta/go-windows-subst"
)

func optionNetUse(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		netresource.NetUse(piece[0], piece[1])
	}
}

func optionSubst(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		subst.Define(piece[0], piece[1])
	}
}

Revert "If option --netuse fails, print error"


package main

import (
	"fmt"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
	"os"
	"os/exec"
)

func verifyNotificationsAreAvailable() {
	_, err := exec.LookPath("terminal-notifier")
	if err != nil {
		fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed.

To remedy this:

    brew install terminal-notifer

To learn more about terminal-notifier:

    https://github.com/alloy/terminal-notifier
`)
		os.Exit(1)
	}
}

func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) {
	if suitePassed {
		sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName))
	} else {
		sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName))
	}
}

func sendNotification(title string, subtitle string) {
	args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"}

	terminal := os.Getenv("TERM_PROGRAM")
	if terminal == "iTerm.app" {
		args = append(args, "-activate", "com.googlecode.iterm2")
	} else if terminal == "Apple_Terminal" {
		args = append(args, "-activate", "com.apple.Terminal")
	}

	if notify {
		exec.Command("terminal-notifier", args...).Run()
	}
}

package main

import (
	"fmt"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
	"os"
	"os/exec"
)

func verifyNotificationsAreAvailable() {
	_, err := exec.LookPath("terminal-notifier")
	if err != nil {
		fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed.

To remedy this:

    brew install terminal-notifier

To learn more about terminal-notifier:

    https://github.com/alloy/terminal-notifier
`)
		os.Exit(1)
	}
}

func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) {
	if suitePassed {
		sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName))
	} else {
		sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName))
	}
}

func sendNotification(title string, subtitle string) {
	args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"}

	terminal := os.Getenv("TERM_PROGRAM")
	if terminal == "iTerm.app" {
		args = append(args, "-activate", "com.googlecode.iterm2")
	} else if terminal == "Apple_Terminal" {
		args = append(args, "-activate", "com.apple.Terminal")
	}

	if notify {
		exec.Command("terminal-notifier", args...).Run()
	}
}

Fix typo in 'terminal-notifier' instructions


package main

import (
	"fmt"
	"os"
	"strings"
	"time"
)

func Usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s [STOP|START] [STOPFILE]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	if len(os.Args) != 3 {
		Usage()
	}
	mode := strings.ToLower(os.Args[1])
	filename := os.Args[2]
	switch mode {
	case "start":
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			f, err := os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error:", err)
				os.Exit(1)
			}
			f.Close()
		}
		tick := time.NewTicker(time.Second)
		for _ = range tick.C {
			if _, err := os.Stat(filename); os.IsNotExist(err) {
				fmt.Println("Exiting now...")
				return
			}
			fmt.Println("Hello")
		}
	case "stop":
		os.Remove(filename)
	default:
		Usage()
	}
}

package main

import (
	"fmt"
	"os"
	"strings"
	"time"
)

func Usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s [STOP|START] [STOPFILE]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	if len(os.Args) != 3 {
		Usage()
	}
	mode := strings.ToLower(os.Args[1])
	filename := os.Args[2]
	switch mode {
	case "start":
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			f, err := os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error:", err)
				os.Exit(1)
			}
			f.Close()
		}
		tick := time.NewTicker(time.Second)
		for range tick.C {
			if _, err := os.Stat(filename); os.IsNotExist(err) {
				fmt.Println("Exiting now...")
				return
			}
			fmt.Println("Hello")
		}
	case "stop":
		os.Remove(filename)
	default:
		Usage()
	}
}

Update for to be for range.


package main

import (
	"crypto/x509"
	"flag"
	"log"
	"path/filepath"

	"github.com/lxc/lxd/lxd/vsock"
	"github.com/lxc/lxd/shared"
	"github.com/pkg/errors"
)

var tlsClientCertFile = filepath.Join("/", "media", "lxd_config", "server.crt")
var tlsServerCertFile = filepath.Join("/", "media", "lxd_config", "agent.crt")
var tlsServerKeyFile = filepath.Join("/", "media", "lxd_config", "agent.key")

func main() {
	var debug bool
	var cert *x509.Certificate

	flag.BoolVar(&debug, "debug", false, "Enable debug mode")
	flag.Parse()

	l, err := vsock.Listen(8443)
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to listen on vsock"))
	}

	cert, err = shared.ReadCert(tlsClientCertFile)
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to read client certificate"))
	}

	tlsConfig, err := serverTLSConfig()
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to get TLS config"))
	}

	httpServer := restServer(tlsConfig, cert, debug)

	log.Println(httpServer.ServeTLS(networkTLSListener(l, tlsConfig), tlsServerCertFile, tlsServerKeyFile))
}

package main

import (
	"crypto/x509"
	"flag"
	"log"

	"github.com/lxc/lxd/lxd/vsock"
	"github.com/lxc/lxd/shared"
	"github.com/pkg/errors"
)

func main() {
	var debug bool
	var cert *x509.Certificate

	flag.BoolVar(&debug, "debug", false, "Enable debug mode")
	flag.Parse()

	l, err := vsock.Listen(8443)
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to listen on vsock"))
	}

	cert, err = shared.ReadCert("server.crt")
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to read client certificate"))
	}

	tlsConfig, err := serverTLSConfig()
	if err != nil {
		log.Fatalln(errors.Wrap(err, "Failed to get TLS config"))
	}

	httpServer := restServer(tlsConfig, cert, debug)

	log.Println(httpServer.ServeTLS(networkTLSListener(l, tlsConfig), "agent.crt", "agent.key"))
}

Load certs from current dir


package builtin

import (
	"fmt"
	"os"
	"strconv"

	"github.com/NeowayLabs/nash/errors"
	"github.com/NeowayLabs/nash/sh"
)

type (
	exitFn struct {
		status int
	}
)

func newExit() *exitFn {
	return &exitFn{}
}

func (e *exitFn) ArgNames() []string {
	return []string{"status"}
}

func (e *exitFn) Run() (sh.Obj, error) {
	os.Exit(e.status)
	return nil, nil //Unrecheable code
}

func (e *exitFn) SetArgs(args []sh.Obj) error {
	if len(args) != 1 {
		return errors.NewError("exit expects one argument")
	}

	obj := args[0]
	if obj.Type() != sh.StringType {
		return errors.NewError(
			"exit expects a status string, but a %s was provided",
			obj.Type(),
		)
	}
	statusstr := obj.(*sh.StrObj).Str()
	status, err := strconv.Atoi(statusstr)
	if err != nil {
		return fmt.Errorf(
			"exit:linux:error[%s] converting status[%s] to int",
			err,
			statusstr,
		)

	}
	e.status = status
	return nil
}

package builtin

import (
	"fmt"
	"os"
	"strconv"

	"github.com/NeowayLabs/nash/errors"
	"github.com/NeowayLabs/nash/sh"
)

type (
	exitFn struct {
		status int
	}
)

func newExit() *exitFn {
	return &exitFn{}
}

func (e *exitFn) ArgNames() []string {
	return []string{"status"}
}

func (e *exitFn) Run() (sh.Obj, error) {
	os.Exit(e.status)
	return nil, nil //Unrecheable code
}

func (e *exitFn) SetArgs(args []sh.Obj) error {
	if len(args) != 1 {
		return errors.NewError("exit expects one argument")
	}

	obj := args[0]
	if obj.Type() != sh.StringType {
		return errors.NewError(
			"exit expects a status string, but a %s was provided",
			obj.Type(),
		)
	}
	statusstr := obj.(*sh.StrObj).Str()
	status, err := strconv.Atoi(statusstr)
	if err != nil {
		return fmt.Errorf(
			"exit:error[%s] converting status[%s] to int",
			err,
			statusstr,
		)

	}
	e.status = status
	return nil
}

Remove unnecessary linux on error message


package Golf

import (
	"net/http"
	"strings"
)

// A wrapper of http.Request
type Request struct {
	*http.Request
	Params map[string]string
	IP     string
}

func NewRequest(req *http.Request) *Request {
	request := new(Request)
	request.Request = req
	request.IP = strings.Split(req.RemoteAddr, ":")[0]
	return request
}

func (req *Request) GetCookie(key string) string {
	cookie, err := req.Request.Cookie(key)
	if err != nil {
		return ""
	} else {
		return cookie.Value
	}
}

package Golf

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

// A wrapper of http.Request
type Request struct {
	*http.Request
	Params map[string]string
	IP     string
}

func NewRequest(req *http.Request) *Request {
	request := new(Request)
	request.Request = req
	request.IP = strings.Split(req.RemoteAddr, ":")[0]
	return request
}

// Query returns query data by the query key.
func (req *Request) Query(key string, index ...int) (string, error) {
	req.ParseForm()
	if val, ok := req.Form[key]; ok {
		if len(index) == 1 {
			return val[index[0]], nil
		} else {
			return val[0], nil
		}
	} else {
		return "", errors.New("Query key not found.")
	}
}

// Cookie returns request cookie item string by a given key.
func (req *Request) Cookie(key string) string {
	cookie, err := req.Request.Cookie(key)
	if err != nil {
		return ""
	} else {
		return cookie.Value
	}
}

// Protocol returns the request protocol string
func (req *Request) Protocol() string {
	return req.Proto
}

Add Query and Protocol support


// Copyright 2012 Dorival de Moraes Pedroso. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import "github.com/cpmech/gosl/plt"

func main() {
	Nf := []float64{5, 7, 10, 13, 15, 20}
	Eave := []float64{3.5998e-12, 2.9629e-10, 6.0300e-8, 3.3686e-6, 2.5914e-5, 1.1966e-3}
	plt.SetForEps(0.75, 200)
	plt.Plot(Nf, Eave, "'b-', marker='.', clip_on=0")
	plt.SetYlog()
	plt.Gll("$N_f$", "$E_{ave}$", "")
	plt.SaveD("/tmp/goga", "multierror.eps")
}

// Copyright 2012 Dorival de Moraes Pedroso. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import "github.com/cpmech/gosl/plt"

func main() {
	Nf := []float64{5, 7, 10, 13, 15, 20}
	Eave := []float64{2.33e-12, 2.39e-10, 5.76e-8, 2.39e-6, 2.58e-5, 1.12e-3}
	plt.Reset(true, &plt.A{Eps: true, Prop: 0.75, WidthPt: 220})
	plt.HideBorders(&plt.A{HideR: true, HideT: true})
	plt.Plot(Nf, Eave, &plt.A{C: "r", M: ".", Lw: 1.2, NoClip: true})
	plt.SetYlog()
	plt.Gll("$N_f$", "$E_{ave}$", nil)
	plt.Save("/tmp/goga", "multierror")
}

Fix code to plot multi-obj errors


package cliedit

import (
	"github.com/elves/elvish/cli"
	"github.com/elves/elvish/cli/addons/histwalk"
	"github.com/elves/elvish/cli/histutil"
	"github.com/elves/elvish/eval"
)

func initHistWalk(app *cli.App, ev *eval.Evaler, ns eval.Ns, fuser *histutil.Fuser) {
	bindingVar := newBindingVar(emptyBindingMap)
	binding := newMapBinding(app, ev, bindingVar)
	ns.AddNs("history",
		eval.Ns{
			"binding": bindingVar,
		}.AddGoFns("<edit:history>", map[string]interface{}{
			"start": func() {
				buf := app.CodeArea.CopyState().CodeBuffer
				walker := fuser.Walker(buf.Content[:buf.Dot])
				histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
			},
			"prev":  func() error { return histwalk.Prev(app) },
			"next":  func() error { return histwalk.Next(app) },
			"close": func() { histwalk.Close(app) },
		}))
}

package cliedit

import (
	"github.com/elves/elvish/cli"
	"github.com/elves/elvish/cli/addons/histwalk"
	"github.com/elves/elvish/cli/el"
	"github.com/elves/elvish/cli/histutil"
	"github.com/elves/elvish/eval"
)

func initHistWalk(app *cli.App, ev *eval.Evaler, ns eval.Ns, fuser *histutil.Fuser) {
	bindingVar := newBindingVar(emptyBindingMap)
	binding := newMapBinding(app, ev, bindingVar)
	ns.AddNs("history",
		eval.Ns{
			"binding": bindingVar,
		}.AddGoFns("<edit:history>", map[string]interface{}{
			"start": func() { histWalkStart(app, fuser, binding) },
			"up":    func() error { return histwalk.Prev(app) },
			"down":  func() error { return histwalk.Next(app) },
			"close": func() { histwalk.Close(app) },
		}))
}

func histWalkStart(app *cli.App, fuser *histutil.Fuser, binding el.Handler) {
	buf := app.CodeArea.CopyState().CodeBuffer
	walker := fuser.Walker(buf.Content[:buf.Dot])
	histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
}

Rename the functions in history: to be backward compatible.


package main

import (
	"github.com/psmithuk/xlsx"
)

func main() {

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

	sh := xlsx.NewSheetWithColumns(c)

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

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "2",
		}

		sh.AppendRow(r)
    }

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

package main

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

func main() {

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

	sh := xlsx.NewSheetWithColumns(c)

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

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "2",
		}

		sh.AppendRow(r)
	}

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

Use fork of xlsx in large test


package main

import (
	"fmt"
	"net/http"
	"strings"

	"gopkg.in/redis.v3"
)

func apiClusterSpecHandler(w http.ResponseWriter, r *http.Request, redisClient *redis.Client) {
	queryCluster := strings.TrimSpace(r.FormValue("cluster"))
	hosts, err := redisClient.SInter("index:live").Result()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
	}

	for _, i := range hosts {
		// we now break at ':' and save the clusters piece
		s := strings.SplitN(i, ":", 2)
		if s[0] == queryCluster {
			// if the custer matches the query, throw the host in a tmp set
			redisClient.SAdd("tmp:cluster:index", s[1])
		}
	}
	// grab the set and delete
	clusters, err := redisClient.SInter("tmp:cluster:index").Result()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
	}
	redisClient.Del("tmp:cluster:index")
	fmt.Fprintln(w, clusters)
}

package main

import (
	"fmt"
	"net/http"
	"strings"

	"gopkg.in/redis.v3"
)

func apiClusterSpecHandler(w http.ResponseWriter, r *http.Request, redisClient *redis.Client) {
	queryCluster := strings.TrimSpace(r.FormValue("cluster"))
	hosts, err := redisClient.SInter("index:live").Result()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
	}

	for _, i := range hosts {
		// we now break at ':' and save the clusters piece
		s := strings.SplitN(i, ":", 2)
		if s[0] == queryCluster {
			// if the custer matches the query, throw the host in a tmp set
			redisClient.SAdd("tmp:cluster:index", s[1])
		}
	}
	// grab the set and delete
	clusters, err := redisClient.SInter("tmp:cluster:index").Result()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
	}
	if fmt.Sprintf("%x", clusters) == "[]" {
		// empty reply, return 400
		w.WriteHeader(http.StatusBadRequest)
	} else {
		redisClient.Del("tmp:cluster:index")
		fmt.Fprintln(w, clusters)
	}
}

Add logic to return 400 when cluster is empty


package dbg

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"runtime/pprof"
	"time"

	"github.com/sirupsen/logrus"
)

const (
	path = "/var/cores/"
)

// DumpGoMemoryTrace output memory profile to logs.
func DumpGoMemoryTrace() {
	m := &runtime.MemStats{}
	runtime.ReadMemStats(m)
	res := fmt.Sprintf("%#v", m)
	logrus.Infof("==== Dumping Memory Profile ===")
	logrus.Infof(res)
}

// DumpGoProfile output goroutines to file.
func DumpGoProfile() error {
	trace := make([]byte, 5120*1024)
	len := runtime.Stack(trace, true)
	return ioutil.WriteFile(path+time.Now().String()+".stack", trace[:len], 0644)
}

func DumpHeap() {
	f, err := os.Create(path + time.Now().String() + ".heap")
	if err != nil {
		logrus.Errorf("could not create memory profile: %v", err)
		return
	}
	defer f.Close()
	if err := pprof.WriteHeapProfile(f); err != nil {
		logrus.Errorf("could not write memory profile: %v", err)
	}
}

package dbg

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"runtime/pprof"
	"time"

	"github.com/sirupsen/logrus"
)

const (
	path = "/var/cores/"
)

// DumpGoMemoryTrace output memory profile to logs.
func DumpGoMemoryTrace() {
	m := &runtime.MemStats{}
	runtime.ReadMemStats(m)
	res := fmt.Sprintf("%#v", m)
	logrus.Infof("==== Dumping Memory Profile ===")
	logrus.Infof(res)
}

// DumpGoProfile output goroutines to file.
func DumpGoProfile() error {
	trace := make([]byte, 5120*1024)
	len := runtime.Stack(trace, true)
	return ioutil.WriteFile(path+time.Now().Format("2006-01-02T15:04:05.999999-0700MST")+".stack", trace[:len], 0644)
}

func DumpHeap() {
	f, err := os.Create(path + time.Now().Format("2006-01-02T15:04:05.999999-0700MST") + ".heap")
	if err != nil {
		logrus.Errorf("could not create memory profile: %v", err)
		return
	}
	defer f.Close()
	if err := pprof.WriteHeapProfile(f); err != nil {
		logrus.Errorf("could not write memory profile: %v", err)
	}
}

Remove whitespace from .stack & .heap filenames.


package commands

import (
	"fmt"
	"time"

	"github.com/spf13/cobra"
)

func GetStringFlag(ctx *cobra.Command, name string) string {
	return ctx.Flag(name).Value.String()
}

func GetBoolFlag(ctx *cobra.Command, name string) bool {
	return ctx.Flag(name).Value.String() == "true"
}

func FormatDateTime(t time.Time) string {
	return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d",
		t.Year(), t.Month(), t.Day(),
		t.Hour(), t.Minute(), t.Second())
}

func Truncate(s string, maxlen int) string {
	if len(s) <= maxlen {
		return s
	}
	return s[:maxlen]
}

package commands

import (
	"fmt"
	"time"

	"github.com/spf13/cobra"
)

func GetStringFlag(ctx *cobra.Command, name string) string {
	flag := ctx.Flag(name)
	if flag == nil {
		return ""
	}
	return flag.Value.String()
}

func GetBoolFlag(ctx *cobra.Command, name string) bool {
	flag := ctx.Flag(name)
	if flag == nil {
		return false
	}
	return flag.Value.String() == "true"
}

func FormatDateTime(t time.Time) string {
	return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d",
		t.Year(), t.Month(), t.Day(),
		t.Hour(), t.Minute(), t.Second())
}

func Truncate(s string, maxlen int) string {
	if len(s) <= maxlen {
		return s
	}
	return s[:maxlen]
}

Fix a bug if the flag doesn't exist


package main

import "testing"

func TestSomethingExciting(t *testing.T) {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // OK
	}
	doStuffTo(transport)
}

func doStuffTo(t *http.Transport) {}

package main

import (
	"crypto/tls"
	"net/http"
	"testing"
)

func TestSomethingExciting(t *testing.T) {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // OK
	}
	doStuffTo(transport)
}

func doStuffTo(t *http.Transport) {}

Fix frontend errors in `DisabledCertificateCheck` tests.


package scraper

import "testing"

func TestScrape(t *testing.T) {
	getItem = func(url string) {
		defer wg.Done()

		ch <- Item{
			"FooTitle",
			"FooSize",
			"10.00",
			"FooDescription",
		}
	}

	urls := []string{
		"http://foo.com/",
		"http://bar.com/",
		"http://baz.com/",
	}

	result := Scrape(urls)
	response := result.Total
	expected := "30.00"

	if response != expected {
		t.Errorf("The response:\n '%s'\ndidn't match the expectation:\n '%s'", response, expected)
	}
}

package scraper

import "testing"

func TestScrapeResultsTotal(t *testing.T) {
	getItem = func(url string) {
		defer wg.Done()

		ch <- Item{
			"FooTitle",
			"FooSize",
			"10.00",
			"FooDescription",
		}
	}

	urls := []string{
		"http://foo.com/",
		"http://bar.com/",
		"http://baz.com/",
	}

	result := Scrape(urls)
	response := result.Total
	expected := "30.00"

	if response != expected {
		t.Errorf("The response:\n '%s'\ndidn't match the expectation:\n '%s'", response, expected)
	}
}

Rename Test to be more descriptive


package errors

import "fmt"

type HTTP struct {
	*primitive
	code int
}

func (h HTTP) Code() int {
	return h.code
}

func NewHTTP(cause error, code int, message string) error {
	return &HTTP{
		primitive: newPrimitive(cause, message),
		code:      code,
	}
}

func HTTPf(cause error, code int, format string, args ...interface{}) error {
	return &HTTP{
		primitive: newPrimitive(cause, fmt.Sprintf(format, args...)),
		code:      code,
	}
}

package errors

import "fmt"

type HTTP interface {
	error
	Code() int
}

type http struct {
	*primitive
	code int
}

func (h http) Code() int {
	return h.code
}

func NewHTTP(cause error, code int, message string) error {
	return &http{
		primitive: newPrimitive(cause, message),
		code:      code,
	}
}

func HTTPf(cause error, code int, format string, args ...interface{}) error {
	return &http{
		primitive: newPrimitive(cause, fmt.Sprintf(format, args...)),
		code:      code,
	}
}

Make HTTP error type an interface


package main

import (
	"fmt"
	"github.com/leocassarani/pew/command"
	"os"
)

func main() {
	args := os.Args
	if len(args) < 2 {
		printUsage(args)
		os.Exit(1)
	}

	cmd := args[1]
	cmdArgs := args[2:]

	switch cmd {
	case "run":
		err := command.Run(cmdArgs)
		exit(err)
	case "help":
		fallthrough
	case "--help":
		printUsage(args)
		os.Exit(0)
	}

}

func exit(err error) {
	if err != nil {
		log(err)
		os.Exit(1)
	}
	os.Exit(0)
}

func log(err error) {
	fmt.Fprintf(os.Stderr, "pew: %v\n", err)
}

func printUsage(args []string) {
	fmt.Printf("usage: %s <command>\n", args[0])
}

package main

import (
	"fmt"
	"github.com/leocassarani/pew/command"
	"os"
)

func main() {
	args := os.Args
	if len(args) < 2 {
		printUsage(args)
		os.Exit(1)
	}

	cmd := args[1]
	cmdArgs := args[2:]

	switch cmd {
	case "run":
		err := command.Run(cmdArgs)
		exit(err)
	case "help":
		fallthrough
	case "--help":
		printUsage(args)
		exit(nil)
	default:
		err := fmt.Errorf("'%s' is not a command. See '%s --help'.", cmd, args[0])
		exit(err)
	}

}

func exit(err error) {
	if err != nil {
		log(err)
		os.Exit(1)
	}
	os.Exit(0)
}

func log(err error) {
	fmt.Fprintf(os.Stderr, "pew: %v\n", err)
}

func printUsage(args []string) {
	fmt.Printf("usage: %s <command>\n", args[0])
}

Handle unrecognised CLI commands in a git-like fashion


package main

import (
  "fmt"
  "net"
  "net/http"
  "net/http/fcgi"
  "os"
)

type FastCGIServer struct{}

func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
  resp.Write([]byte("{}"))
}

func main() {
  listener, err := net.Listen("tcp", "127.0.0.1:9000")
  if err != nil {
    fmt.Fprint(os.Stderr, "Failed to open socket 9000: ", err)
  }

  srv := new(FastCGIServer)
  err = fcgi.Serve(listener, srv)
  if err != nil {
    fmt.Fprint(os.Stderr, "Server crashed: ", err)
  }
}

package main

import (
  "fmt"
  "net"
  "net/http"
  "net/http/fcgi"
  "os"
  "time"
)

type FastCGIServer struct{}

func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
  resp.Write([]byte("{}"))
}

func main() {
  fmt.Fprintln(os.Stderr, "Server started at ", time.Now().String())

  listener, err := net.Listen("tcp", "127.0.0.1:9000")
  if err != nil {
    fmt.Fprintln(os.Stderr, "Failed to open socket 9000: ", err)
    os.Exit(1)
  }

  srv := new(FastCGIServer)
  err = fcgi.Serve(listener, srv)
  if err != nil {
    fmt.Fprintln(os.Stderr, "Server crashed: ", err)
    os.Exit(1)
  }

  fmt.Fprintln(os.Stderr, "Server stopped at ", time.Now().String())
}

Exit on failure and log server start/stop


// Copyright © 2015-2018 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

/*
#include <yara.h>
*/
import "C"

func init() {
	_ = C.yr_initialize()
}

// Finalize releases all the resources allocated by the library. It should be
// called when your program is about to exit. Calling Finalize is not strictly
// required as the program is going to die anyways, but it's highly recommended
// because memory profiling tools can detect and report memory leaks if you
// don't. The recommended practice is calling it as a defered function in your
// program's main:
//  defer yara.Finalize()
func Finalize() {
	C.yr_finalize()
}

// Copyright © 2015-2018 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

/*
#include <yara.h>
*/
import "C"

func init() {
	if err := initialize(); err != nil {
		panic(err)
	}
}

// Prepares the library to be used.
func initialize() error {
	return newError(C.yr_initialize())
}

// Finalize releases all the resources allocated by the library. It should be
// called when your program is about to exit. Calling Finalize is not strictly
// required as the program is going to die anyways, but it's highly recommended
// because memory profiling tools can detect and report memory leaks if you
// don't. The recommended practice is calling it as a defered function in your
// program's main:
//  defer yara.Finalize()
func Finalize() error {
	return newError(C.yr_finalize())
}

Make Finalize() to return an error. Panic if YARA failed while being initialized.


package model_test

import (
	"encoding/json"
	"github.com/crezam/actions-on-google-golang/internal/test"
	"github.com/crezam/actions-on-google-golang/model"
	"os"
	"testing"
	"time"
)

func TestRequestParsing(t *testing.T) {

	var req model.ApiAiRequest

	file, _ := os.Open("./data/sample_request1.json")
	dec := json.NewDecoder(file)

	err := dec.Decode(&req)

	// test if any issues decoding file
	test.Ok(t, err)

	// assert correct parsing
	test.Equals(t, "209eefa7-adb5-4d03-a8b9-9f7ae68a0c11", req.Id)

	expectedTimestamp, _ := time.Parse(time.RFC3339Nano, "2016-10-10T07:41:40.098Z")
	test.Equals(t, expectedTimestamp, req.Timestamp)

	test.Equals(t, "Hi, my name is Sam!", req.Result.ResolvedQuery)
}

package model_test

import (
	"encoding/json"
	"github.com/crezam/actions-on-google-golang/internal/test"
	"github.com/crezam/actions-on-google-golang/model"
	"os"
	"testing"
	"time"
)

func TestRequestParsing(t *testing.T) {

	var req model.ApiAiRequest

	file, _ := os.Open("./data/sample_request1.json")
	dec := json.NewDecoder(file)

	err := dec.Decode(&req)

	// test if any issues decoding file
	test.Ok(t, err)

	// assert correct parsing
	test.Equals(t, "209eefa7-adb5-4d03-a8b9-9f7ae68a0c11", req.Id)

	expectedTimestamp, _ := time.Parse(time.RFC3339Nano, "2016-10-10T07:41:40.098Z")
	test.Equals(t, expectedTimestamp, req.Timestamp)

	test.Equals(t, "Hi, my name is Sam!", req.Result.ResolvedQuery)
	test.Equals(t, "agent", req.Result.Source)
	test.Equals(t, "greetings", req.Result.Action)
	test.Equals(t, false, req.Result.ActionIncomplete)
	test.Equals(t, "Sam", req.Result.Parameters.Parameters["user_name"])

}

Add tests for parameters (verified broken), fix next commit


// Copyright 2014 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 darwin linux

package main

import (
	"log"
	"time"

	"github.com/rakyll/sensors"
	"golang.org/x/mobile/app"
)

func main() {
	app.Main(func(a app.App) {
		sensor.Enable(a, sensor.Accelerometer, time.Millisecond)
		sensor.Enable(a, sensor.Gyroscope, time.Second)

		for e := range a.Events() {
			log.Println(e)
		}
	})
}

// Copyright 2014 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 darwin linux

package main

import (
	"log"
	"time"

	"github.com/rakyll/sensors"
	"golang.org/x/mobile/app"
)

func main() {
	app.Main(func(a app.App) {
		sensor.Enable(a, sensor.Accelerometer, 10*time.Millisecond)
		sensor.Enable(a, sensor.Gyroscope, time.Second)

		go func() {
			<-time.Tick(time.Second)
			sensor.Disable(sensor.Gyroscope)
		}()

		for e := range a.Events() {
			log.Println(e)
		}
	})
}

Disable gyroscope events after a sec.


package resourcepool

import (
	"sync"
	"testing"
)

type IntMaker struct{}

var wg sync.WaitGroup = sync.WaitGroup{}

func (*IntMaker) Create() (interface{}, error) {
	i := 1
	return &i, nil
}

func (*IntMaker) Check(interface{}) error {
	return nil
}

func (*IntMaker) Destroy(interface{}) error {
	wg.Done()
	return nil
}

func TestResourcePool(t *testing.T) {

	wg.Add(2)

	pool, err := NewResourcePool(
		&IntMaker{},
		2,
		2,
		2,
	)
	if err != nil {
		t.Error(err)
	}

	r1, err := pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r2, err := pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	pool.ReturnResource(r1)
	pool.ReturnResource(r2)

	r1, err = pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r2, err = pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	pool.ReturnResource(r1)
	pool.ReturnResource(r2)

	wg.Wait()

}

package resourcepool

import (
	"sync"
	"testing"
)

type IntMaker struct{}

var wg sync.WaitGroup = sync.WaitGroup{}

func (*IntMaker) Create() (interface{}, error) {
	i := 1
	return &i, nil
}

func (*IntMaker) Check(interface{}) error {
	return nil
}

func (*IntMaker) Destroy(interface{}) error {
	wg.Done()
	return nil
}

func TestResourcePool(t *testing.T) {

	wg.Add(2)

	pool, err := NewResourcePool(
		&IntMaker{},
		2,
		2,
		2,
	)
	if err != nil {
		t.Error(err)
	}

	r1, err := pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r2, err := pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r1.Close()
	r2.Close()

	r1, err = pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r2, err = pool.GetResource()
	if err != nil {
		t.Error(err)
	}

	r1.Close()
	r2.Close()

	wg.Wait()

}

Check Close() function on pool resources.


package logger

import (
	"net/http"
	"time"

	"github.com/Sirupsen/logrus"
)

// responseWriter implements the http.ResponseWriter interface and
// keeps track of the header status
type responseWriter struct {
	Status int
	Writer http.ResponseWriter
}

func (rw *responseWriter) Header() http.Header {
	return rw.Writer.Header()
}

func (rw *responseWriter) Write(b []byte) (int, error) {
	return rw.Writer.Write(b)
}

func (rw *responseWriter) WriteHeader(s int) {
	rw.Status = s
	rw.Writer.WriteHeader(s)
}

func Request(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rw := responseWriter{Status: 200, Writer: w}
		defer func() {
			logrus.WithFields(map[string]interface{}{
				"status":  rw.Status,
				"latency": time.Since(start),
				"ip":      r.RemoteAddr,
				"method":  r.Method,
				"url":     r.URL.String(),
			}).Info()
		}()
		next.ServeHTTP(&rw, r)
	})
}

// Package logger implements middleware loggeing.
package logger

import (
	"net/http"
	"time"

	"github.com/Sirupsen/logrus"
)

// responseWriter implements the http.ResponseWriter interface and
// keeps track of the header status
type responseWriter struct {
	Status int
	Writer http.ResponseWriter
}

func (rw *responseWriter) Header() http.Header {
	return rw.Writer.Header()
}

func (rw *responseWriter) Write(b []byte) (int, error) {
	return rw.Writer.Write(b)
}

func (rw *responseWriter) WriteHeader(s int) {
	rw.Status = s
	rw.Writer.WriteHeader(s)
}

// Request returns an http.Handler that can be used as middleware to log requests.
func Request(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rw := responseWriter{Status: 200, Writer: w}
		defer func() {
			logrus.WithFields(map[string]interface{}{
				"status":  rw.Status,
				"latency": time.Since(start),
				"ip":      r.RemoteAddr,
				"method":  r.Method,
				"url":     r.URL.String(),
			}).Info()
		}()
		next.ServeHTTP(&rw, r)
	})
}

Add doc to package logger


package random

import (
	"fmt"
	"math/rand"
	"sort"
	"testing"
)

func TestIntn(t *testing.T) {
	for i := 0; i < 100; i++ {
		rn := Intn(10)
		if 0 <= rn && rn < 10 {
			continue
		}
		t.Errorf("Intn should return in the range of [0, n)")
	}
}

func ExampleShuffle() {
	figures := sort.StringSlice{"rectangle", "hexagon", "square", "circle", "triangle", "pentagon"}
	deterministic := rand.New(rand.NewSource(1))
	Shuffle(figures.Len(), deterministic.Intn, figures.Swap)
	fmt.Println(figures)
	// Output:
	// [pentagon circle rectangle square hexagon triangle]
}

package random

import (
	"fmt"
	"math/rand"
	"sort"
	"testing"
)

func TestIntn(t *testing.T) {
	for i := 0; i < 100; i++ {
		rn := Intn(10)
		if 0 <= rn && rn < 10 {
			continue
		}
		t.Errorf("Intn should return in the range of [0, n)")
	}
}

func ExampleShuffle() {
	figures := sort.StringSlice{"rectangle", "hexagon", "square", "circle", "triangle", "pentagon"}
	// For test purpose. For better randomness, you may use random.Intn.
	deterministic := rand.New(rand.NewSource(1))
	Shuffle(figures.Len(), deterministic.Intn, figures.Swap)
	fmt.Println(figures)
	// Output:
	// [pentagon circle rectangle square hexagon triangle]
}

Add comments on the example.


package vm

type Closure struct {
	function      *Thunk
	freeVariables []*Thunk
}

func (c Closure) Call(ts ...*Thunk) *Thunk {
	o := c.function.Eval()
	f, ok := o.(Callable)

	if !ok {
		return NotCallableError(o)
	}

	return f.Call(append(c.freeVariables, ts...)...)
}

func Partial(ts ...*Thunk) *Thunk {
	if len(ts) == 0 {
		return NumArgsError("partial", ">= 1")
	}

	return Normal(Closure{ts[0], ts[1:]})
}

package vm

type Closure struct {
	function      *Thunk
	freeVariables []*Thunk
}

func (c Closure) Call(ts ...*Thunk) *Thunk {
	o := c.function.Eval()
	f, ok := o.(Callable)

	if !ok {
		return NotCallableError(o)
	}

	return f.Call(append(c.freeVariables, ts...)...)
}

func Partial(ts ...*Thunk) *Thunk {
	switch len(ts) {
	case 0:
		return NumArgsError("partial", ">= 1")
	case 1:
		return ts[0]
	}

	return Normal(Closure{ts[0], ts[1:]})
}

Fix out of range error


package io_test

import (
	"os"

	. "github.com/cloudfoundry/cli/testhelpers/io"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("io helpers", func() {
	It("will never overflow the pipe", func() {
		str := ""
		for i := 0; i < 75000; i++ {
			str += "abc"
		}

		output := CaptureOutput(func() {
			os.Stdout.Write([]byte(str))
		})

		Expect(output).To(Equal([]string{str}))
	})
})

package io_test

import (
	"os"
	"strings"

	. "github.com/cloudfoundry/cli/testhelpers/io"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("io helpers", func() {
	It("will never overflow the pipe", func() {
		characters := make([]string, 0, 75000)
		for i := 0; i < 75000; i++ {
			characters = append(characters, "z")
		}

		str := strings.Join(characters, "")

		output := CaptureOutput(func() {
			os.Stdout.Write([]byte(str))
		})

		Expect(output).To(Equal([]string{str}))
	})
})

Speed up this test by a factor of a lot


package namecheap

import (
	"net/url"
	"testing"
)

func TestNewClient(t *testing.T) {
	c := NewClient("anApiUser", "anToken", "anUser")

	if c.BaseURL != defaultBaseURL {
		t.Errorf("NewClient BaseURL = %v, want %v", c.BaseURL, defaultBaseURL)
	}
}

// Verify that the MakeRequest function assembles the correct API URL
func TestMakeRequest(t *testing.T) {
	c := NewClient("anApiUser", "anToken", "anUser")
	c.BaseURL = "https://fake-api-server/"
	requestInfo := ApiRequest{
		method:  "GET",
		command: "namecheap.domains.getList",
		params:  url.Values{},
	}
	req, _ := c.makeRequest(requestInfo, nil)

	// correctly assembled URL
	outURL := "https://fake-api-server/?ApiKey=anToken&ApiUser=anApiUser&ClientIp=127.0.0.1&Command=namecheap.domains.getList&UserName=anUser"

	// test that URL was correctly assembled
	if req.URL.String() != outURL {
		t.Errorf("NewRequest() URL = %v, want %v", req.URL, outURL)
	}
}

Add some very simple tests for NewClient and MakeRequest.


package auth

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"net/http"
)

const (
	tokenCookieName = "access_token"
)

func AddRoutes(r *mux.Router, service Service) {
	// Explicitly only serve login over https.
	r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {

		decoder := json.NewDecoder(r.Body)
		req := LoginRequest{}
		err := decoder.Decode(&req)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to decode login request from request body: %v", err), 400)
			return
		}

		token, err := service.Login(req)
		if err != nil {
			// Explicitly do not pass up the reason for login failure.
			http.Error(w, "Invalid username or password.", 403)
		}

		signedString, err := service.Sign(token)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to issue token: %v", err), 503)
		}

		// Return token as a cookie.
		w.Header().Add("Set-Cookie", fmt.Sprintf("%v=%v; Secure; HttpOnly;", tokenCookieName, signedString))

		w.WriteHeader(http.StatusNoContent)
	}).Methods("POST").Schemes("https")
}

package auth

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"net/http"
)

const (
	tokenCookieName = "access_token"
)

func AddRoutes(r *mux.Router, service Service) {
	// Explicitly only serve login over https.
	r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {

		decoder := json.NewDecoder(r.Body)
		req := LoginRequest{}
		err := decoder.Decode(&req)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to decode login request from request body: %v", err), 400)
			return
		}

		token, err := service.Login(req)
		if err != nil {
			// Explicitly do not pass up the reason for login failure.
			http.Error(w, "Invalid username or password.", 403)
		}

		signedString, err := service.Sign(token)
		if err != nil {
			http.Error(w, fmt.Sprintf("failed to issue token: %v", err), 503)
		}

		// Return token as a cookie.
		w.Header().Add("Set-Cookie", fmt.Sprintf("%v=%v; Path=/api; Secure; HttpOnly;", tokenCookieName, signedString))

		w.WriteHeader(http.StatusNoContent)
	}).Methods("POST").Schemes("https")
}

Set auth cookie to be returned on all api calls


package main

import (
	"fmt"
	"os"

	"github.com/lluchs/mima"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: mimarun <filename>")
		return
	}

	filename := os.Args[1]
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Parsing...\n")
	program, err := mima.Parse(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	// Print the program.
	fmt.Println("Pointer")
	for mark, pointer := range program.Marks {
		fmt.Println(mark, pointer)
	}

	fmt.Println("Instructions")
	for address, instruction := range program.Instructions {
		fmt.Printf("%s = %s(%s)\n", address, instruction.Op, instruction.Argument)
	}
}

package main

import (
	"fmt"
	"os"

	"github.com/lluchs/mima"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: mimarun <filename>")
		return
	}

	filename := os.Args[1]
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("Parsing...\n")
	program, err := mima.Parse(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	// Print the program.
	fmt.Println("Pointer")
	for mark, pointer := range program.Marks {
		fmt.Println(mark, pointer)
	}

	fmt.Println("Instructions")
	for address, instruction := range program.Instructions {
		fmt.Printf("%s = %s(%s)\n", address, instruction.Op, instruction.Argument)
	}

	fmt.Println("\n\nAssembling...\n")
	bytecode, err := program.Assemble()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Print the assembled code.
	fmt.Printf("Start: 0x%06X\n", bytecode.Start)
	printMem(bytecode.Mem)

	fmt.Println("\n\nRunning...\n")
	mem, err := bytecode.Run()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Print the resulting memory.
	printMem(mem)

}

// Print all memory locations which are not 0.
func printMem(mem []uint32) {
	for pos, content := range mem {
		if content != 0 {
			fmt.Printf("0x%06X: 0x%06X\n", pos, content)
		}
	}
}

Implement assembling and running code


package main

import (
    "net/http"
    "fmt"
    "encoding/json"
)

func handlePing(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    type Input struct {
        FeedId string `json:"feed_id"`
        FeedUrl string `json:"feed_url"`
    }

    if r.Method != http.MethodPost {
        http.Error(w, "Not allowed", http.StatusMethodNotAllowed)
        return
    }

    var inputs []Input
    err := json.NewDecoder(r.Body).Decode(&inputs)

    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
    }

    for _, input := range inputs {
        fmt.Fprintf(w, "%s", input.FeedUrl)
    }
}

func init() {
    http.HandleFunc("/ping", handlePing)
    http.HandleFunc("/handle", handleRequest)
}

package main

import (
    "net/http"
    "fmt"
)

func handlePing(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

type Input struct {
    FeedId string
    FeedUrl string
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Not allowed", http.StatusMethodNotAllowed)
        return
    }

    input, err := parseInput(r)

    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
    }

    fmt.Fprintf(w, "%s", input.FeedUrl)
}

func parseInput(r *http.Request) (i Input, err error) {
    feed_id := r.FormValue("feed_id")
    feed_url := r.FormValue("feed_url")

    return Input{feed_id, feed_url}, nil
}

func init() {
    http.HandleFunc("/ping", handlePing)
    http.HandleFunc("/handle", handleRequest)
}

Handle input with a http form, rather than JSON


package main

import (
	"fmt"
	"os"

	"strings"

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

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

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

	return env, nil
}

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

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

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

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

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"strings"

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

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

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

	return env, nil
}

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

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

	c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	project, _, err := c.GetProject(ctx, "pypi", "cookiecutter")

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

Update cmd to pass context to request


// Copyright (c) 2015 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package blockchain

// TODO Make benchmarking tests for various functions, such as sidechain
// evaluation.

// Copyright (c) 2019 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package blockchain

import (
	"testing"
)

// BenchmarkAncestor benchmarks ancestor traversal for various numbers of nodes.
func BenchmarkAncestor(b *testing.B) {
	// Construct a synthetic block chain with consisting of the following
	// structure.
	// 	0 -> 1 -> 2 -> ... -> 499997 -> 499998 -> 499999  -> 500000
	// 	                                      \-> 499999a
	// 	                            \-> 499998a
	branch0Nodes := chainedFakeNodes(nil, 500001)
	branch1Nodes := chainedFakeNodes(branch0Nodes[499998], 1)
	branch2Nodes := chainedFakeNodes(branch0Nodes[499997], 1)

	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		branchTip(branch0Nodes).Ancestor(0)
		branchTip(branch0Nodes).Ancestor(131072) // Power of two.
		branchTip(branch0Nodes).Ancestor(131071) // One less than power of two.
		branchTip(branch0Nodes).Ancestor(131070) // Two less than power of two.
		branchTip(branch1Nodes).Ancestor(0)
		branchTip(branch2Nodes).Ancestor(0)
	}
}

Add benchmark for ancestor traversal.


package repository

import (
	"fmt"

	"gopkg.in/asaskevich/govalidator.v6"
)

func ValidateCreate(r *Repository) error {
	if err := validateName(r.Name); err != nil {
		return err
	}

	if err := validateDescription(r.Description); err != nil {
		return err
	}

	if err := validateWebsite(r.Website); err != nil {
		return err
	}

	return nil
}

func validateID(id string) error {
	if ok := govalidator.IsUUIDv4(id); !ok {
		return fmt.Errorf("id is not a valid uuid v4")
	}
	return nil
}

func validateName(name string) error {
	if ok := govalidator.IsAlphanumeric(name); !ok {
		return fmt.Errorf("username is not alphanumeric")
	}
	if ok := govalidator.IsByteLength(name, 4, 32); !ok {
		return fmt.Errorf("username is not between 4 and 32 characters long")
	}
	return nil
}

func validateDescription(description string) error {
	return nil
}

func validateWebsite(website string) error {
	if ok := govalidator.IsURL(website); !ok {
		return fmt.Errorf("%s is not a url", website)
	}

	return nil
}

package repository

import (
	"fmt"

	"gopkg.in/asaskevich/govalidator.v6"
)

func ValidateCreate(r *Repository) error {
	if err := validateName(r.Name); err != nil {
		return err
	}

	if err := validateDescription(r.Description); err != nil {
		return err
	}

	if err := validateWebsite(r.Website); err != nil {
		return err
	}

	return nil
}

func validateID(id string) error {
	if ok := govalidator.IsUUIDv4(id); !ok {
		return fmt.Errorf("id is not a valid uuid v4")
	}
	return nil
}

func validateName(name string) error {
	if ok := govalidator.IsAlphanumeric(name); !ok {
		return fmt.Errorf("name is not alphanumeric")
	}
	if ok := govalidator.IsByteLength(name, 4, 32); !ok {
		return fmt.Errorf("name is not between 4 and 32 characters long")
	}
	return nil
}

func validateDescription(description string) error {
	return nil
}

func validateWebsite(website string) error {
	if ok := govalidator.IsURL(website); !ok {
		return fmt.Errorf("%s is not a url", website)
	}

	return nil
}

Fix typo in repository name validator errors


package main

import (
	"flag"
	"fmt"
	"os"
	"time"

	_ "github.com/jackwilsdon/svnwatch/types"
)

func fatalf(format interface{}, a ...interface{}) {
	fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
	os.Exit(1)
}

func main() {
	configDir := flag.String("config", "/etc/svnwatch", "the configuration directory for svnwatch")
	interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exists after a single check)")

	flag.Parse()

	watcher, err := loadWatcher(*configDir)

	if *interval < 0 {
		fatalf("%s: invalid interval: %d", os.Args[0], *interval)
	}

	if err != nil {
		fatalf(err)
	}

	for {
		if err := watcher.update(); err != nil {
			fatalf(err)
		}

		if err := watcher.save(*configDir); err != nil {
			fatalf(err)
		}

		if *interval > 0 {
			time.Sleep(time.Duration(*interval) * time.Second)
		} else {
			break
		}
	}
}

package main

import (
	"flag"
	"fmt"
	"os"
	"time"

	_ "github.com/jackwilsdon/svnwatch/types"
)

func fatalf(format interface{}, a ...interface{}) {
	fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
	os.Exit(1)
}

func main() {
	configDir := flag.String("config", "/etc/svnwatch", "the configuration directory for svnwatch")
	interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exits after a single check)")

	flag.Parse()

	watcher, err := loadWatcher(*configDir)

	if *interval < 0 {
		fatalf("%s: invalid interval: %d", os.Args[0], *interval)
	}

	if err != nil {
		fatalf(err)
	}

	for {
		if err := watcher.update(); err != nil {
			fatalf(err)
		}

		if err := watcher.save(*configDir); err != nil {
			fatalf(err)
		}

		if *interval > 0 {
			time.Sleep(time.Duration(*interval) * time.Second)
		} else {
			break
		}
	}
}

Fix typo (exists -> exits)


package main

import (
	"fmt"
	"koding/db/mongodb/modelhelper"
	"socialapi/workers/common/runner"
	"socialapi/workers/migrator/controller"
)

var (
	Name = "Migrator"
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		fmt.Println(err)
		return
	}
	defer r.Close()

	modelhelper.Initialize(r.Conf.Mongo)

	handler, err := controller.New(r.Log)
	if err != nil {
		panic(err)
	}

	if err := handler.Start(); err != nil {
		panic(err)
	}

}

package main

import (
	"flag"
	"fmt"
	"koding/db/mongodb/modelhelper"
	"socialapi/workers/common/runner"
	"socialapi/workers/migrator/controller"
)

var (
	Name         = "Migrator"
	flagSchedule = flag.Bool("s", false, "Schedule worker")
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		fmt.Println(err)
		return
	}
	defer r.Close()

	modelhelper.Initialize(r.Conf.Mongo)

	handler, err := controller.New(r.Log)
	if err != nil {
		panic(err)
	}

	if *flagSchedule {
		r.ShutdownHandler = handler.Shutdown
		if err := handler.Schedule(); err != nil {
			panic(err)
		}
		r.Wait()

		return
	}

	handler.Start()
}

Add scheduler support to migrator by adding -s flag


package main

import (
	"github.com/hashicorp/terraform/plugin"
	"github.com/terraform-providers/terraform-provider-kubernetes/kubernetes"
)

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

package main

import (
	"github.com/hashicorp/terraform/plugin"
	"github.com/sl1pm4t/terraform-provider-kubernetes/kubernetes"
)

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

Update import path to fix build.


package peer

import (
	"fmt"
	"io/ioutil"
	"testing"
)

func TestCrStates(t *testing.T) {
	t.Log("Running Peer Tests")

	text, err := ioutil.ReadFile("crstates.json")
	if err != nil {
		t.Log(err)
	}
	crStates, err := CrStatesUnMarshall(text)
	if err != nil {
		t.Log(err)
	}
	fmt.Println(len(crStates.Caches), "caches found")
	for cacheName, crState := range crStates.Caches {
		t.Logf("%v -> %v", cacheName, crState.IsAvailable)
	}

	fmt.Println(len(crStates.Deliveryservice), "deliveryservices found")
	for dsName, deliveryService := range crStates.Deliveryservice {
		t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations))
	}

}

package peer

import (
	"fmt"
	"io/ioutil"
	"testing"
)

func TestCrStates(t *testing.T) {
	t.Log("Running Peer Tests")

	text, err := ioutil.ReadFile("crstates.json")
	if err != nil {
		t.Log(err)
	}
	crStates, err := CrstatesUnMarshall(text)
	if err != nil {
		t.Log(err)
	}
	fmt.Println(len(crStates.Caches), "caches found")
	for cacheName, crState := range crStates.Caches {
		t.Logf("%v -> %v", cacheName, crState.IsAvailable)
	}

	fmt.Println(len(crStates.Deliveryservice), "deliveryservices found")
	for dsName, deliveryService := range crStates.Deliveryservice {
		t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations))
	}

}

Fix TM2 test to match renamed symbol


package util

import (
	"encoding/json"
)

func String(v interface{}) string {
	e, _ := json.Marshal(v)
	return string(e[:])
}

func StringPrettify(v interface{}) string {
	e, _ := json.MarshalIndent(v, "", "  ")
	return string(e[:])
}

Add a string prettify method which formats the json nicely


package golog

import "testing"

func TestAsserta(t *testing.T) {
    db0 := NewDatabase()
    db1 := db0.Asserta(NewTerm("alpha"))
    db2 := db1.Asserta(NewTerm("beta"))
    db3 := db2.Asserta(NewTerm("gamma", NewTerm("greek to me")))

    // do we have the right number of clauses?
    if db0.ClauseCount() != 0 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db1.ClauseCount() != 1 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db2.ClauseCount() != 2 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db3.ClauseCount() != 3 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
}

package golog

import "testing"

func TestAsserta(t *testing.T) {
    db0 := NewDatabase()
    db1 := db0.Asserta(NewTerm("alpha"))
    db2 := db1.Asserta(NewTerm("beta"))

    foo := NewTerm("foo", NewTerm("one"), NewTerm("two"))
    body := NewTerm("alpha")
    db3 := db2.Asserta(NewTerm(":-", foo, body))
    t.Logf(db3.String()) // helpful for debugging

    // do we have the right number of clauses?
    if db0.ClauseCount() != 0 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db1.ClauseCount() != 1 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db2.ClauseCount() != 2 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
    if db3.ClauseCount() != 3 {
        t.Errorf("db0: wrong number of clauses: %d", db0.ClauseCount())
    }
}

Test against a clause head and body


package model

// A LightBulb is a Switch and additionally has a brightness, saturation and hue value.
//
// TODO(brutella): The HAP protocol defines brightness, saturation and hue as optional. This
// is currently no reflected in the LightBulb interface yet.
type LightBulb interface {
	Switch

	// OnBrightnessChanged sets the brightness changed callback
	OnBrightnessChanged(func(int))

	// OnHueChanged sets the hue changed callback
	OnHueChanged(func(float64))

	// OnSaturationChanged sets the saturation changed callback
	OnSaturationChanged(func(float64))

	// GetBrightness returns the light bulb's brightness
	GetBrightness() int

	// SetBrightness sets the light bulb's brightness
	SetBrightness(int)

	// GetHue returns the light bulb's hue
	GetHue() float64

	// SetHue sets the light bulb's hue
	SetHue(float64)

	// GetSaturation returns the light bulb's saturation
	GetSaturation() float64

	// SetSaturation sets the light bulb's saturation
	SetSaturation(float64)
}

package model

// A LightBulb is a Switch and additionally has a brightness, saturation and hue value.
//
// TODO(brutella): The HAP protocol defines brightness, saturation and hue as optional. This
// is currently no reflected in the LightBulb interface yet.
type LightBulb interface {
	Switch

	// OnBrightnessChanged sets the brightness changed callback
	OnBrightnessChanged(func(int))

	// OnHueChanged sets the hue changed callback
	OnHueChanged(func(float64))

	// OnSaturationChanged sets the saturation changed callback
	OnSaturationChanged(func(float64))

	// GetBrightness returns the light bulb's brightness between 0 and 100
	GetBrightness() int

	// SetBrightness sets the light bulb's brightness
	// The argument should be between 0 and 100
	SetBrightness(int)

	// GetHue returns the light bulb's hue between 0.0 and 360.0
	GetHue() float64

	// SetHue sets the light bulb's hue
	// The argument should be between 0.0 and 360.0
	SetHue(float64)

	// GetSaturation returns the light bulb's saturation between 0.0 and 100.0
	GetSaturation() float64

	// SetSaturation sets the light bulb's saturation
	// The argument should be between 0 and 100
	SetSaturation(float64)
}

Update min and max value documentation of brightness, saturation and hue characteristic


// Copyright 2012 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 ignore

package main

import (
	"image"
	"image/color"

	"code.google.com/p/go-tour-french/pic"
)

type Image struct {
	Height, Width int
}

func (m Image) ColorModel() color.Model {
	return color.RGBAModel
}

func (m Image) Bounds() image.Rectangle {
	return image.Rect(0, 0, m.Height, m.Width)
}

func (m Image) At(x, y int) color.Color {
	c := uint8(x ^ y)
	return color.RGBA{c, c, 255, 255}
}

func main() {
	m := Image{256, 256}
	pic.ShowImage(m)
}

// Copyright 2012 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 ignore

package main

import (
	"image"
	"image/color"

	"github.com/dupoxy/go-tour-fr/pic"
)

type Image struct {
	Height, Width int
}

func (m Image) ColorModel() color.Model {
	return color.RGBAModel
}

func (m Image) Bounds() image.Rectangle {
	return image.Rect(0, 0, m.Height, m.Width)
}

func (m Image) At(x, y int) color.Color {
	c := uint8(x ^ y)
	return color.RGBA{c, c, 255, 255}
}

func main() {
	m := Image{256, 256}
	pic.ShowImage(m)
}

Update imports from googlecode to github


package godbg

import (
	"os"
	"testing"
	. "github.com/smartystreets/goconvey/convey"
)

func TestProject(t *testing.T) {
	Convey("Test buffers", t, func() {

		Convey("By Default, equals to std", func() {
			So(Out(), ShouldEqual, os.Stdout)
			So(Err(), ShouldEqual, os.Stderr)
		})
		Convey("When set to buffer, no longer equals to std", func() {
			SetBuffers(nil)
			So(Out(), ShouldNotEqual, os.Stdout)
			So(Err(), ShouldNotEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance buffer equals to std", func() {
			apdbg := NewPdbg()
			So(apdbg.Out(), ShouldEqual, os.Stdout)
			So(apdbg.Err(), ShouldEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance set to buffer writes no longer equals to std", func() {
			apdbg := NewPdbg(SetBuffers)
			So(apdbg.Out(), ShouldNotEqual, os.Stdout)
			So(apdbg.Err(), ShouldNotEqual, os.Stderr)
		})
	})
}

package godbg

import (
	"fmt"
	"os"
	"testing"
	. "github.com/smartystreets/goconvey/convey"
)

func TestProject(t *testing.T) {
	Convey("Test buffers", t, func() {

		Convey("By Default, equals to std", func() {
			So(Out(), ShouldEqual, os.Stdout)
			So(Err(), ShouldEqual, os.Stderr)
		})
		Convey("When set to buffer, no longer equals to std", func() {
			SetBuffers(nil)
			So(Out(), ShouldNotEqual, os.Stdout)
			So(Err(), ShouldNotEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance buffer equals to std", func() {
			apdbg := NewPdbg()
			So(apdbg.Out(), ShouldEqual, os.Stdout)
			So(apdbg.Err(), ShouldEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance set to buffer writes no longer equals to std", func() {
			apdbg := NewPdbg(SetBuffers)
			So(apdbg.Out(), ShouldNotEqual, os.Stdout)
			So(apdbg.Err(), ShouldNotEqual, os.Stderr)
		})
		Convey("Test custom buffer on global pdbg", func() {
			SetBuffers(nil)
			fmt.Fprintln(Out(), "test content")
			fmt.Fprintln(Err(), "err1 cerr")
			fmt.Fprintln(Err(), "err2 cerr2")
			fmt.Fprint(Out(), "test2 content2")
			So(OutString(), ShouldEqual, `test content
test2 content2`)
			So(ErrString(), ShouldEqual, `err1 cerr
err2 cerr2
`)
		})
	})
}

Test String() on Out() and Err() global pdgb


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

// +build !gccgo

package vsphere

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

var (
	Provider environs.EnvironProvider = providerInstance
)

func init() {
	environs.RegisterProvider(providerType, providerInstance)
}

func ExposeEnvFakeClient(env *environ) *fakeClient {
	return env.client.connection.RoundTripper.(*fakeClient)
}

var _ environs.Environ = (*environ)(nil)

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

// +build !gccgo

package vsphere

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

var (
	Provider environs.EnvironProvider = providerInstance
)

func ExposeEnvFakeClient(env *environ) *fakeClient {
	return env.client.connection.RoundTripper.(*fakeClient)
}

var _ environs.Environ = (*environ)(nil)

Drop registering the provider during tests.